Podcast
Questions and Answers
Given that Python does not require explicit type declaration, what determines the data type of a variable during runtime?
Given that Python does not require explicit type declaration, what determines the data type of a variable during runtime?
- The first character of the variable name.
- A pre-defined setting in the interpreter.
- The module in which the variable is defined.
- The value assigned to the variable. (correct)
Consider a function in Python that does not explicitly include a return
statement. What is the default return behavior when this function is called?
Consider a function in Python that does not explicitly include a return
statement. What is the default return behavior when this function is called?
- It raises an exception.
- It returns an integer `0`.
- It implicitly returns `None`. (correct)
- It returns a boolean `False`.
Given the Python command string = "hello"
, what is the result of executing string[:2]
?
Given the Python command string = "hello"
, what is the result of executing string[:2]
?
- `olleh`
- `he` (correct)
- `lo`
- `hello`
Under what conditions will round(x, n)
raise an error?
Under what conditions will round(x, n)
raise an error?
What is the return type of the id()
function in Python, and what does this return value represent?
What is the return type of the id()
function in Python, and what does this return value represent?
Given that Python is dynamically typed, consider the code snippet: x = 13 / 2
. How can you ensure that x
is explicitly an integer in Python 3.x?
Given that Python is dynamically typed, consider the code snippet: x = 13 / 2
. How can you ensure that x
is explicitly an integer in Python 3.x?
What type of error is encountered when attempting to access an undefined variable?
What type of error is encountered when attempting to access an undefined variable?
Predict the output of the following code:
def example(a):
a = a + '2'
a = a * 2
return a
example("hello")
Predict the output of the following code:
def example(a):
a = a + '2'
a = a * 2
return a
example("hello")
Which of the following is a valid Python list?
Which of the following is a valid Python list?
If you need to store data in a key-value pair format, which core data type should you use?
If you need to store data in a key-value pair format, which core data type should you use?
Flashcards
What is a Class in Python?
What is a Class in Python?
Class is a user-defined datatype.
Default return value
Default return value
If a function doesn't explicitly return a value, it implicitly returns None.
String slicing
String slicing
String slicing extracts parts of strings using indices.
Integer division and type casting
Integer division and type casting
Signup and view all the flashcards
Function id()
Function id()
Signup and view all the flashcards
What is a dictionary?
What is a dictionary?
Signup and view all the flashcards
Power Operator
Power Operator
Signup and view all the flashcards
Floor division
Floor division
Signup and view all the flashcards
Order of Precedence
Order of Precedence
Signup and view all the flashcards
Modulus operator
Modulus operator
Signup and view all the flashcards
Study Notes
Core Data Types
- The
Class
datatype is not a core datatype - When a function returns nothing, the Python shell throws a
NoneType
object - The output of the following commands will be
"he"
>>>str="hello"
>>>str[:2]
>>>
- The following code will run without errors:
round(45.8)
round(6352.898,2)
- A function
id
returns a unique integer - The following code operations ensure that x has an integer value in Python 3.xx:
x = 13 // 2
x = int(13/2)
NameError
is the error that occurs when you execute the following code:
apple = mango
- The
L = [1, 23, ‘hello’, 1]
object is a List datatype - A
Dictionary
dataype is used to store values in terms of key and value - The following code results in a
SyntaxError
:"He said, "Yes!""
'3\'
- The code will print
"tom\ndick\nharry"
under these conditions:
print("" tom
\ndick
\nharry"" )
print(‘tom\ndick\nharry’)
- The average value of the following code is 85.0, as a decimal value to appear is the output:
>>>grade1 = 80
>>>grade2 = 90
>>>average = (grade1 + grade2) / 2
- The following code will print
hello-how-are-you
:
print(‘hello-‘ + ‘how-are-you’)
print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘-‘ + ‘you’)
- The return value of
trunc()
is an integer
Basic Operators
- The correct operator for power(x^y) is
X**y
, i.e.2**3=8
//
performs floor division- The order of precedence in Python is Parentheses, Exponentiation, Division, Multiplication, Addition, Subtraction (PEDMAS)
- The answer of
22 % 3
is1
since modulus operator gives remainder - Mathematical operations cannot be performed on strings, even if they look like integers
- Operators with the same precedence are evaluated from left to right
- The output of the expression
3*1**3
is3
, because exponentiation has higher precedence than multiplication, the solution is1**3 = 1; 3*1 = 3
- Addition and Subtraction or Multiplication and Division have the same precedence
Int(x)
converts the variable x to an integer- Parentheses have the highest precedence in an expression
Variable Names
-
Python is case-sensitive when dealing with identifiers
-
Identifiers can be of any length
-
Variable names should not begin with a number
-
Local variable names beginning with an underscore are discouraged to indicate variables that must not be accessed from outside the class
-
eval
is not a keyword, and can be used as a variable -
True
,False
, andNone
are capitalized, while all other keywords in Python are in lowercase -
Variable names in Python can have unlimited length
-
Spaces are not allowed in variable names
-
The word
in
is a keyword, and cannot be used as a variable
Regular Expressions
- The
re
module in Python is for regular expressions, import withimport re
re.compile(str)
creates a pattern object, and converts a given string into a pattern object- The function
re.match
matches a pattern at the start of the string, and will look for the pattern at the beginning returning None if its not found - The function
re.search
matches a pattern at any position in the string, will look for the pattern at any position in the string - The function
matched.groups()
returns all the subgroups that have been matched - The function
matched.group()
returns the entire match - The function
matched.group(2)
returns the particular subgroup - These regex functions return all the matches in a dictionary:
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.groupdict())
- These regex functions return all the subgroups that have been matched:
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.groups())
- This function returns the particular subgroup for regex:
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.group(2))
Numeric Types
Print 0.1 + 0.2 == 0.3
gives the output Falsek = 2 + 3l
is not a complex number- The type of inf is
float
- ~4 evaluates to -5
-
While and For Loops
-
The function
upper()
does not perform in place modification to a string. -
A code inside a
while True
code block will execute until abreak
occurs. -
The
else
part in awhile
loop is not executed if the loop breaks -
A
NameError
will occur if the variables are not defined -
The value of 'i' or 'x' is not altered if a condition always evaluates toÂ
True
-
The range() is computed only at the time of entering the loop
-
An object of type int is not iterable.
-
These functions use the keys of the dictionary and prints the values:
d = {0: 'a', 1: 'b', 2: 'c'}
for x in d.keys():
print(d[x])
-
0O11 is an octal number.
-
A TypeError arises when using the
center()
method incorrectly: The fill character must be exactly one character long. -
The output with a
string.translate()
function is the output with modified indexes -
Variables values aren't automatically retained by default on new iterations:
def f(i, values = []):
values.append(i)
return values
f(1)
f(2)
v = f(3)
print(v)
String Functions
- The
+
operator concatenates strings and, unlike the*
symbol, cannot be used with numbers - The
slice()
function is performed on a string string.ascii_lowercase+string.ascii_upercase
is the same asstring.ascii_letters
-1
corresponds to the last index\
is an escape sequence- String literals that are separated by white space are joined together
- The character values for 0xA and 0xB and 0xC are hexadecimal
- Code involving id attributes can show whether strings are in fact the same string or just have the same value
Numerical Operations
- Numerical comparison
>
operators and arithmetic operators such as+
cannot be used with dictionaries
List Methods
- The following list methods are available on lists:
print(list1[0]) # prints first item in list
print(list1[:2]) # prints the first two items in the list
print(list1[:-2]) # prints the list with the exceptions of the last two items
print(list1[4:6]) # prints items at index 4 to 6
- Slicing is allowed in lists just as in the case of character strings
- Max returns the maximum element in the list
- Min returns the minimum element in the list
- list1.reverse() will print the list is reverse
- listExample.extend([34, 5]) will extend at the new list
- listExample.pop(1) will remove the element at the position as specified in the parameter
- With the
string += [1]
statement will append all the elements individually into a new list - A list will passed in append:
- Numbers = [1, 2, 3, 4]
- numbers.append([5,6,7,8])
len(number)
= 5 because 1 list is appending so length is 5.
+
will append the element to the list- Tuples can be used for keys into dictionary because tuples can have mixed length and the other the items in the tuple is considered when comparing the equality of the keys
- SyntaxError, not in isn’t allowed in loop
Tuples
- Tuples are characterised by their round brackets,
()
- Values cannot be modified in the case of a tuple
- Slicing in tuples takes place just as in character strings, to get a
t = (1,2,4,3)
you can uset[1:3] = (2,4)
- The * operator concatenates tuples
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.