Worksheets › Class 11 › Getting Started with Python › Cheat sheet
Class 11 Getting Started with Python: cheat sheet
CBSE Computer Science. Python’s identifiers and keywords, data types, operators and their precedence, type conversion, input and print, and syntax, runtime and logical errors.
Key ideas
- An identifier starts with a letter or _, has only letters, digits and _, is case-sensitive, and cannot be a keyword such as for, True or None.
- The basic types are int, float, complex, bool, str, list, tuple, dict and NoneType; type(x) tells you which.
- / always gives a float; // rounds the quotient down (towards minus infinity), and % gives a remainder with the sign of the divisor.
- ** is done first and groups from the right, even before a unary minus; then *, /, // and %; then + and −; then comparisons; then not, and, or.
- input() always gives a string; int() and float() convert it, and int() simply drops the fraction part.
- and gives its first false value (else the last), and or its first true value (else the last): not always True or False.
- A syntax error stops Python before the program runs, a runtime error stops it while running, and a logical error gives a wrong answer.
Remember
| // and % | 17 // 5 = 3, 17 % 5 = 2; −17 // 5 = −4, −17 % 5 = 3 |
| They always fit | a = b × (a // b) + a % b |
| Precedence | 5 + 3 * 2 = 11; 2 ** 3 ** 2 = 512; −3 ** 2 = −9 |
| Floats | 10 / 5 = 2.0; 7 // 2.0 = 3.0; 4 + 1.0 = 5.0; True + 4 = 5 |
| round() | a tie goes to the even neighbour: round(2.5) = 2, round(3.5) = 4 |
| Conversion | int('12') + 3 = 15; str(4) + str(2) = '42'; int(7.9) = 7 |
| and, or | 5 and 9 gives 9; 0 and 9 gives 0; 5 or 9 gives 5; 0 or 9 gives 9 |
| print() | print(1, 2, sep='-') prints 1-2; end='' stops the new line |
Watch out
- Thinking // rounds towards zero: −7 // 2 is −4, not −3.
- Forgetting that input() gives text: typing 5 for a = input() makes a * 2 print 55.
- Writing 5 = x: the left side of = must be a name.
- Expecting round(4.5) to be 5: it is 4.
Worked example
What does this program print? Give (a) the first line (b) the second. a = 23 b = 1 - 23 print(a // b) print(a % b)
Working: a = 23, b = −22: // rounds down (towards minus infinity), and a = b × (a // b) + a % b
Answer: (a) −2; (b) −21
Practise Getting Started with Python
Revise with this page, then practise: every Getting Started with Python sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.