Basics of Types Flashcards
What are the three basic number types and their Python shorthand
Integers = int
Real numbers = float
Complex numbers = complex
How do you find out the type of an object?
Function: type(obj)
What is a string and what is the Python shorthand?
String is a sequence of characters, normally enclosed in single or double quotation marks.
How do you escape characters in strings?
Backslash - \
Eg,
» print(“My name is "Levi"”)
My name is “Levi”
How do you insert a tab into a string?
\t
How do you insert a newline into a string?
\n
How can you avoid having to escape special characters?
Triple quotation marks (‘’’ or “””)
Where the three main/basic binary operators that can be applied to strings?
+ (concatenation)
* (repeat string N times)
in (subset of?)
Give an example of the ‘in’ binary operator for strings?
> > print(‘z’ in ‘Zebra’)
True
How does assignment work?
>>> a = 1 >>> print(a) 1 The RHS is evaluated and then assigned to the LHS, allowing self-referential assignment: >>> a = a + 2 >>> print(a) 3
What is ‘stacking’ assignment variables?
>>> a = b = c = 2 >>> print(a) 2 >>> print(b) 2 >>> print(c) 2 >>> a = b = c = a + b + c >>> print(a," ",b," ",c) 6 6 6
What characters can a variable name start with?
(a-zA-Z) or underscore (_)
What characters can a variable name contain?
Alphanumeric (0-9a-zA-Z) and underscore (_)
Does case matter when naming variables?
Yes, apple != Apple, they are different variables
What are reserved words?
Operators, literals and built-in functions that cannot be used for variable names (eg in, print, not, str)
Calculate the ith Fibonacci number using only three variables.
a = 1
b = 2
c = a + b
Redefine a and b sequentially
How do we ‘cast’ a literal or variable as a different type?
Use functions of the same name as the type into which we want to cast: int(), float(), str(), complex()…
What does abs() do?
Returns the absolute value of the operand
What does len() do?
Return the length of the ITERABLE operand Eg, >>> len('string') 6 >>> len([1,2,3]) 3
Given num containing an int, calculate the number of digits in it.
> > > len(str(num))
What are the four basic types in this deck?
str, int, float, complex
How are string specified?
Using single or double quotation marks (‘ or “)
What is the difference between a literal and a variable?
A literal is fixed, a variable is not. A variable is a stored memory location for an assigned value.