Introduction to Programming and Python Basics
Introduction to Programming and Python Basics tests how a Python program is written and executed, the token categories, variable naming, standard data types, input/output, type conversion and operator precedence.
Core rules
- Python is an interpreted, dynamically typed language: a variable is a name bound to an object, and its type can change on reassignment.
- Tokens are keywords, identifiers, literals, operators and punctuators. Keywords such as
if,foranddefcannot be used as identifiers. - Core data types:
int,float,str,boolandcomplex. Usetype(x)to inspect one. input()always returns a string. Convert withint(),float()orstr()before arithmetic.print()displays values; commas insert spaces, andsepandendcontrol formatting.- Precedence:
**, then unary+ -, then* / // %, then+ -, then comparisons, thennot,and,or. Use brackets when in doubt. /gives a float,//gives floor division, and%gives the remainder.
Worked example
Evaluate 2 + 3 * 4 ** 2 // 8. Exponentiation binds first: 4 ** 2 = 16. Multiplication and floor division are evaluated left to right: 3 * 16 = 48, then 48 // 8 = 6. Finally 2 + 6 = 8. If you evaluated left to right without precedence, you would wrongly get 10.
Traps that cost marks
- Writing
input('Marks: ') + 5, which raises a TypeError because input returns a string. - Confusing
=(assignment) with==(comparison). - Assuming
//always rounds down toward zero; for negative numbers it rounds toward negative infinity. - Starting an identifier with a digit or using a keyword.
- Expecting
'5' + '3'to give 8; it gives the string'53'.