Two ways to run Python: interactive and script mode
Interactive mode: you type one statement after the >>> prompt and Python answers at once. Good for testing small things. Nothing is saved.
Script mode: you write many lines in a file ending in .py, save it and run it (F5 in IDLE). Good for real programs; you can run it again and again.
Structure of a program and indentation
A Python program is a list of statements, run from top to bottom. A comment starts with #; Python ignores it, but it helps humans read the code.
A line that ends with a colon : (like if, for, while) starts a block. Every line of the block must be pushed right by the same amount, usually 4 spaces. This is indentation. Python uses it instead of brackets. Wrong indentation gives an IndentationError.
if marks >= 33:
print("Pass")
else:
print("Try again")
Identifiers, keywords, constants and variables
Keywords are reserved words with a fixed meaning: if, else, elif, for, while, True, False, None, and, or, not, in, is, def, import, etc. You cannot use them as names.
An identifier is a name you give to a variable or function. Rules: letters, digits and _ only; cannot start with a digit; no spaces or symbols; not a keyword; case-sensitive (Marks and marks are different). Valid: total_marks, _x, mark2. Invalid: 2mark, total marks, if.
A variable is a name that refers to a value in memory: age = 16. Python works out its type from the value; no declaration is needed. = means "tie this name to this value", not "equals".
A constant is a value that should not change. Python has no true constants; by habit we write the name in capitals: PI = 3.14. Fixed values written directly (10, "hi", 3.5) are called literals.
Data types
- Numbers:
int(whole: 7, −3),float(decimal: 7.5),complex(3+4j). - bool:
TrueorFalse. - str (string): text in quotes,
"Ravi". - list: ordered, changeable,
[1, 2, 3]. - tuple: ordered, not changeable,
(1, 2, 3). - dict: key-value pairs,
{"roll": 5}. - None: means "no value".
Use type(x) to see a type.
Mutable and immutable types
Mutable: can be changed in place, same object. list, dict (and set).
Immutable: cannot be changed in place. int, float, bool, str, tuple. When you "change" them, Python makes a new value and moves the name tag. Example: s = "cat"; s[0] = "b" gives a TypeError, but L = [1,2]; L[0] = 9 works.
Operators and precedence
- Arithmetic:
+ - * /(always float),//(floor division),%(remainder),**(power). - Relational:
== != < > <= >=, give True/False. - Logical:
not, and, or. - Assignment:
= += -= *= /= //= %= **=. - Identity:
is, is not(same object?). - Membership:
in, not in("a" in "cat"→ True).
An expression is a mix of values, variables and operators that gives one value, like 2 + 3 * 4.
Precedence (high to low)
()**(right to left)- unary
+x -x * / // %+ -- relational
== != < > <= >=,is,in notandor
Same level: left to right (except **).
Input and output
input("prompt") shows a message, waits for the user, and always returns a string.
print(a, b, sep=" ", end="\n") shows values. sep is put between values, end at the end.
name = input("Name: ")
print("Hello", name, sep=", ", end="!\n")
Type conversion
Explicit (you ask for it): int("25") → 25, float("2.5") → 2.5, str(10) → "10", int(7.9) → 7 (cuts the decimal). int("abc") gives a ValueError.
Implicit (Python does it): 3 + 2.0 → 5.0 (int becomes float so no data is lost).
Since input() gives a string, write age = int(input("Age: ")) to do maths with it.
Debugging: three kinds of errors
- Syntax error: breaking the grammar rules. Python will not start. Example:
print("hi"(missing bracket), missing colon, wrong indentation. - Runtime error (exception): the grammar is fine but something fails while running. Example:
10 / 0(ZeroDivisionError),int("abc")(ValueError), using a name not defined (NameError). - Logical error: the program runs but gives a wrong answer. Example:
avg = a + b / 2instead of(a + b) / 2. Hardest to find, because there is no message.
Debugging means finding and fixing errors: read the error message and line number, print values in between, and test with small known inputs.
Try it: predict before you run
Open Python (IDLE or any online Python). Before pressing Enter, write down your guess for each: 7 // 2, 7 % 2, 2 ** 3 ** 2, "5" + "2", int("5") + 2, 10 / 5. Then run each. Every wrong guess: open step 6 in the 3D and watch that expression reduce.
Key formulas and definitions
- a // b = floor of a ÷ b; a % b = remainder; a == (a // b) * b + a % b
- / always returns float: 10 / 5 = 2.0
- Precedence: () > ** > unary > * / // % > + - > relational > not > and > or
- input() returns str; use int(), float() to convert
Worked examples
1. Evaluate 2 + 3 * 4 ** 2.
** first: 4 ** 2 = 16. Then 3 * 16 = 48. Then 2 + 48 = 50.
2. Evaluate 17 // 5 and 17 % 5.
17 ÷ 5 = 3 remainder 2. So 17 // 5 = 3 and 17 % 5 = 2. Check: 3 × 5 + 2 = 17.
3. Evaluate 2 ** 3 ** 2.
** goes right to left: 3 ** 2 = 9, then 2 ** 9 = 512 (not 64).
4. What is printed? x = 5; x += 3; x *= 2; print(x)
x = 5 → x = 8 → x = 16. Prints 16.
5. Evaluate not 5 > 3 and 2 == 2.
Relational first: 5 > 3 is True, 2 == 2 is True. Then not True = False. Then False and True = False.
6. a = input("Enter: ") and the user types 4. What is a * 3?
a is the string "4", so a * 3 = "444" (string repeated). To get 12, use int(a) * 3.
7. Find the error type: avg = m1 + m2 / 2 for m1 = 80, m2 = 60.
It runs and gives 80 + 30 = 110, which is wrong. This is a logical error. Fix: avg = (m1 + m2) / 2 = 70.0.
Common mistakes
- Forgetting that input() gives a string, so "4" + "5" = "45".
- Thinking 2 ** 3 ** 2 = 64. Power goes right to left: 512.
- Using = (assign) when you mean == (compare).
- Mixing tabs and spaces or forgetting to indent after a colon.