Python Flashcards
5*6 - 5 // 2 + 8 / 3
30.66666…
This is an example of bad code: it should be properly written as:
(5 * 6) - (5 // 2) + 8 / 3
= 30 - 2 + 2.66666…
What would print out if you ran this fragment of Java code:
System.out.println(3/2)
1
Java integer division differs from Python: the equivalent code (which is not equivalent!) in Python:
>>> print(3/2)
1.5
>>>
would print out 1.5
In Python, what is the value of:
2 << 2
8
The binary left shift operator will return a value which is double the value of the operand for each operation. So left shifting twice is the same thing as multiplying by 4. In general a << b == a*(2**b).
Why does the bit-wise 00shift operator << have the effect it does (ie, doubling the value of the operand each time?)
Because of binary representation; the << operator adds 0s to the right of the number and shifts everything to the left.
Eg:
1 << 1 == 2
1 is represented in Python as 00000001.
The operation shifts the 1 to the left and puts a zero into its place:
00000010
which is 2.
>>> x = 1
>>> x << 2
4
>>> x
?
x remains 1. The bit shift operators do not modify their operands.
What is the value of :
( (16 >> 3) == (17 >> 3))
True. Both 16 >> 3 and 17 >> 3 evaluate to 2.
>>> 16 >> 3
2
>>> 17 >> 1
8
>>> 17 >> 2
4
>>> 17 >> 3
2
>>> 16 >> 1
8
>>> 16 >> 2
4
>>> 16 >> 3
2
5 // (4 ** 1/2) ++ 56 % 7 % 2 % 2 % 2 % 2
2.0
>>> 56 % 7 % 2 % 2 % 2 % 2
0
>>> 56 % 7 % 2 % 2 % 2
0
>>> 56 % 7 % 2 % 2
0
>>> 56 % 7 % 2
0
>>> 56 % 7
0
>>>
>>> “Don’t Panic!” [7 :]
‘anic!’
“Foomping” [0 : 6] + “Breathe, Move” [9:]
>>> “Foomping” [0 : 6] + “Breathe, Move” [9:]
‘FoompiMove’
What do you get when you type:
range(6)
at the Python prompt?
>>> range(6)
range(0, 6)
The result of range(x) is a range object which operationally behaves like a list of numbers from 0 to x-1 but is not the same thing as a list because Python computes a value each time we ask range for a new value during for i in range(x) operations.
>>> list(range(9))[4:9]
>>> list(range(9))[4:9]
[4, 5, 6, 7, 8]
not (False and True and False and True or False)
True
>>> (False and True) or (True and False) and (“This is fun”.index(‘i’) == 5)
>>> (False and True) or (True and False) and (“This is fun”.index(‘i’) == 5)
False
0x00b & 0x555
>>> 0x00b & 0x555
1