← Back to Tutorials Chapter 2

Syntax & Control Flow

Basic Syntax

Python uses indentation to define code blocks instead of curly braces {}. The standard is 4 spaces per indentation level. Comments are written with #:

# This is a comment
x = 5  # inline comment
if x > 0:
    print("Positive")  # indented block

Variables

Python is dynamically typed — you do not need to declare a variable's type. Its type is inferred at runtime.

name = "Alice"      # str
age = 30            # int
pi = 3.14159        # float
is_active = True    # bool
nothing = None      # NoneType

Multiple Assignment

a, b, c = 1, 2, 3
x = y = z = 0

The Private Convention

Variable names prefixed with an underscore (e.g. _secret) are conventionally considered "private" — a hint to other developers, not enforced by the language.

Data Types

Python's fundamental built-in types include:

Type Casting

int("42")       # 42
str(3.14)       # "3.14"
float("2.5")    # 2.5
bool(1)         # True
bool(0)         # False

Operators

Arithmetic

+  -  *  /   # add, subtract, multiply, divide
//           # floor division
%            # modulus (remainder)
**           # exponentiation

Comparison

==  !=  <  >  <=  >=

Logical

and  or  not

Assignment

=   +=  -=  *=  /=  //=  %=  **=

Bitwise

&   |   ^   ~   <<   >>

Conditionals: if / elif / else

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

match-case (Python 3.10+)

command = "quit"
match command:
    case "quit":
        print("Exiting...")
    case "help":
        print("Available commands: ...")
    case _:
        print(f"Unknown: {command}")

Loops

for Loops

# Range-based
for i in range(5):
    print(i)          # 0 1 2 3 4

# Iterate over a sequence
for char in "hello":
    print(char)

# With enumerate
for idx, val in enumerate(["a", "b", "c"]):
    print(idx, val)

while Loops

count = 0
while count < 5:
    print(count)
    count += 1

break, continue, pass

for n in range(10):
    if n == 3:
        continue      # skip 3
    if n == 7:
        break         # stop at 7
    print(n)

# pass is a no-op placeholder
def unfinished_function():
    pass
Python control flow diagram
Note: Python uses elif (not else if or elsif). Indentation errors are a common beginner mistake — always check your whitespace.

Practice Exercise

Write a program that asks the user for a number and prints whether it is positive, negative, or zero. Then extend it so the user can enter up to 5 numbers and the program prints the sum and average. Use a for loop and a while loop — try both versions.