Learn › Class 11 › Computer Science / Informatics Practices › Python programming fundamentals
Python fundamentals
You will learn to
- Use variables, data types and type conversion in Python
- Evaluate expressions with arithmetic, relational and logical operators
- Write programs with if, for and while
- Define functions and recognise common errors
Helpful to know first: Computer systems and data; Basic algebra.
Python is a high-level, interpreted language. You can type commands in interactive mode or save them as a script. A variable is a name that refers to a value, and its type is decided when it is assigned.
Common types are int, float, complex, bool and str. input() always returns a str, so use int() or float() to get a number. Identifiers may contain letters, digits and underscores, but cannot start with a digit or be a keyword.
Operators
/ always gives a float, so 7 / 2 is 3.5. // is floor division and % gives the remainder. ** is power and is right-associative. Logical operators are and, or and not.
Blocks are marked by indentation. if, elif and else choose between paths. for i in range(a, b, s) counts from a up to, but not including, b. while repeats as long as its condition is True; break leaves a loop early.
A function is defined with def and can return a value with return. Syntax errors stop the program from starting. Runtime errors, like ZeroDivisionError, occur while it runs. Logical errors give wrong answers without any message.
Common mix-ups
Not quite: range(1, 5) includes 5.
Instead: The stop value is excluded: range(1, 5) gives 1, 2, 3, 4.
Not quite: = and == mean the same thing.
Instead: = assigns a value to a name. == compares two values and gives True or False.