Python Match Case

Python Tutorial › Control Flow › Match Case

Python Match Case

BeginnerLesson 14 of 4710 min read6 runnable examples

match compares one value against a list of patterns and runs the block for the first pattern that fits. It is Python’s answer to the switch statement found in other languages, and it can also pull values out of lists and dictionaries.

In this lesson
  • Replace long elif chains with match
  • Combine values with OR patterns
  • Add conditions with guards
  • Match and unpack lists and dicts

Your first match statement

match was added in Python 3.10. Each case is a pattern. _ is the wildcard: it matches anything, so it works like else.

Python
status_code = 404 match status_code:    case 200:        print("OK")    case 404:        print("Not found")    case 500:        print("Server error")    case _:        print("Unknown status")
Output
Not found

Only the first matching case runs. Unlike C or Java, there is no fall-through and no break needed.

Several values in one case

Use | to mean “or”:

Python
def day_type(day):    match day.lower():        case "saturday" | "sunday":            return "weekend"        case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":            return "weekday"        case _:            return "not a day" for d in ["Sunday", "wednesday", "Funday"]:    print(d, "->", day_type(d))
Output
Sunday -> weekend
wednesday -> weekday
Funday -> not a day

Capture a value and add a guard

A bare name in a pattern captures the value. An if after the pattern is a guard: the case matches only if the guard is true.

Python
def grade(score):    match score:        case n if n >= 90:            return "A"        case n if n >= 75:            return "B"        case n if n >= 0:            return "C or below"        case _:            return "invalid" print(grade(95), grade(80), grade(40), grade(-5))
Output
A B C or below invalid
Tip

For simple range checks like this, if / elif is just as clear. match really shines when you need to look at the shape of the data, as below.

Match sequences

Patterns can describe lists and tuples. Names in the pattern are filled from the matching positions, and *rest collects the remaining items.

Python
def run(command):    match command.split():        case ["quit"]:            return "Bye"        case ["go", direction]:            return f"Going {direction}"        case ["take", first, *others]:            return f"Taking {first} and {len(others)} more"        case []:            return "Say something"        case _:            return f"Unknown command: {command!r}" for c in ["go north", "take key lamp rope", "quit", "", "dance"]:    print(run(c))
Output
Going north
Taking key and 2 more
Bye
Say something
Unknown command: 'dance'

Match dictionaries

A mapping pattern checks that certain keys exist and captures their values. Extra keys are ignored, which makes this ideal for JSON from an API.

Python
events = [    {"type": "click", "x": 10, "y": 20},    {"type": "key", "key": "Enter"},    {"type": "scroll"},] for event in events:    match event:        case {"type": "click", "x": x, "y": y}:            print(f"click at ({x}, {y})")        case {"type": "key", "key": key}:            print(f"key {key} pressed")        case {"type": other}:            print(f"unhandled event {other}")
Output
click at (10, 20)
key Enter pressed
unhandled event scroll

Match by type

int(), str() and other class names in a pattern check the type:

Python
def describe(value):    match value:        case bool():            return "a boolean"        case int() | float():            return "a number"        case str() if value == "":            return "an empty string"        case str():            return "a string"        case list():            return f"a list of {len(value)}"        case _:            return "something else" for v in [True, 3, 2.5, "", "hi", [1, 2], None]:    print(repr(v), "is", describe(v))
Output
True is a boolean
3 is a number
2.5 is a number
'' is an empty string
'hi' is a string
[1, 2] is a list of 2
None is something else
Note

bool() is checked before int() because True is also an int. As with elif, put the more specific case first.

Check your understanding

Predict the output

point = (0, 5)match point:    case (0, 0):        print("origin")    case (0, y):        print(f"on the y axis at {y}")    case (x, 0):        print(f"on the x axis at {x}")    case _:        print("somewhere else")

Quick quiz

1. Which Python version introduced match?

2. What does case _: do?

3. How do you match “y” or “yes” in one case?

Exercise: calculator

Write calc(a, op, b) with match that supports +, -, * and /, returns “cannot divide by zero” for division by 0, and “unknown operator” otherwise.

Input
calc(6, "*", 7), calc(9, "/", 0), calc(9, "/", 3), calc(1, "^", 2)
Expected output
42 cannot divide by zero 3.0 unknown operator
Hint 1

A guard like case "/" if b == 0: must come before case "/":.

Program Practice

The if-else programs are a great place to practise match: try rewriting a few solutions with it.

Python match case FAQ

Does Python have a switch case statement?

Yes, since Python 3.10 the match statement does everything a switch does, plus matching on the structure of lists, tuples, dicts and objects.

Do I need break in Python match case?

No. Only the first matching case runs and there is no fall-through.

What is the default case in Python match?

case _: matches any value, so it acts as the default.

Is match faster than if elif?

Not meaningfully. Choose match when it makes the code clearer, especially when unpacking structured data.

Python Operators & Booleans

Python Tutorial › Basics › Operators & Booleans

Python Operators & Booleans

BeginnerLesson 12 of 4712 min read12 runnable examples

Operators are the symbols that do the work in an expression: they add numbers, compare values and combine conditions. This lesson covers all seven groups of Python operators and the booleans they produce.

In this lesson
  • Arithmetic and assignment operators
  • Comparison operators and chaining
  • and, or, not with short-circuiting
  • is vs == and the in operator

Arithmetic operators

Python
a, b = 14, 4print(a + b, a - b, a * b)print(a / b, a // b, a % b, a ** 2)
Output
18 10 56
3.5 3 2 196

+ and * also work on strings and lists:

Python
print("ab" + "cd", "-" * 10)print([1, 2] + [3], [0] * 3)
Output
abcd ----------
[1, 2, 3] [0, 0, 0]

The Numbers & Math lesson explains //, % and rounding in detail.

Assignment operators

Augmented assignment updates a variable using its current value.

OperatorSame as
x += 3x = x + 3
x -= 3x = x - 3
x *= 3x = x * 3
x /= 3x = x / 3
x //= 3x = x // 3
x %= 3x = x % 3
x **= 3x = x ** 3
Python
balance = 1000balance -= 250      # withdrawalbalance *= 1.05     # 5% interestprint(balance)
Output
787.5

Comparison operators

Comparisons return a boolean: True or False.

OperatorMeaning
==equal
!=not equal
> / <greater than / less than
>= / <=greater or equal / less or equal
Python
score = 72print(score == 72, score != 72)print(score > 50, score <= 60)print("apple" < "banana")     # strings compare alphabeticallyprint(10 == 10.0)             # int and float with the same value are equal
Output
True False
True False
True
True

Python lets you chain comparisons, just like in maths:

Python
age = 25print(18 <= age < 60)
Output
True

Logical operators: and, or, not

ExpressionTrue when
a and bboth are true
a or bat least one is true
not aa is false
Python
has_ticket = Trueis_adult = Falseprint(has_ticket and is_adult)print(has_ticket or is_adult)print(not is_adult)
Output
False
True
True

Short-circuiting

and stops at the first falsy value and or stops at the first truthy value. They return that value itself, not always True/False. This gives two handy idioms:

Python
name = ""display = name or "Guest"          # default when name is emptyprint(display) items = []print(len(items) > 0 and items[0])  # items[0] is never evaluated
Output
Guest
False

Booleans and truthiness

True and False are the two boolean values, and bool is a subclass of int. In an if or while, any value is treated as true or false:

Python
print(True + True, True * 10)for value in [0, 3, "", "text", [], [1], None]:    print(repr(value), "->", "truthy" if value else "falsy")
Output
2 10
0 -> falsy
3 -> truthy
'' -> falsy
'text' -> truthy
[] -> falsy
[1] -> truthy
None -> falsy

Identity operators: is, is not

== asks “do these have the same value?” is asks “are these the very same object?”

Python
a = [1, 2]b = [1, 2]c = aprint(a == b, a is b)print(a is c)
Output
True False
True
Tip

Use is only to compare with None, True or False: if result is None:. For everything else use ==.

Membership operators: in, not in

Python
roles = ["admin", "tester", "viewer"]print("tester" in roles)print("guest" not in roles)print("py" in "python")                  # substring checkprint("id" in {"id": 7, "name": "x"})   # checks dict keys
Output
True
True
True
True

Bitwise operators

Bitwise operators work on the binary digits of integers. You will meet them in permissions, flags and low-level code.

Python
a, b = 6, 3       # 110 and 011 in binaryprint(a & b, a | b, a ^ b)print(~a, a << 1, a >> 1)
Output
2 7 5
-7 12 3

Operator precedence

From highest to lowest (operators on the same row are evaluated left to right, except **):

PrecedenceOperators
1() parentheses
2**
3+x, -x, ~x
4*, /, //, %
5+, -
6bitwise: << and >>, then &, then ^, then bitwise OR
7comparisons, in, not in, is, is not
8not
9and
10or
Python
print(True or False and False)    # and binds tighter: True or (False and False)print(not 1 == 2)                 # not (1 == 2)
Output
True
True

Check your understanding

Predict the output

x = 5print(x > 3 and x < 10, x > 3 or 1 / 0, 0 or "" or "last")

Quick quiz

1. What does 10 != 10.0 return?

2. What does "" or "default" return?

3. Which checks whether x is None?

4. What does 1 < 3 < 2 evaluate to?

Exercise: leap year check

A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. Print each year with True or False.

Input
1900, 2000, 2024, 2026
Expected output
1900 False
2000 True
2024 True
2026 False
Hint 1

Combine % with and and or.

Hint 2

(year % 4 == 0 and year % 100 != 0) or year % 400 == 0

Program Practice

Python operators FAQ

What is the difference between == and is in Python?

== compares values; is compares identity (whether two names refer to the same object). Two separate lists with the same items are == but not is.

Does Python have && and || operators?

No. Python uses the words and, or and not.

Does Python have ++ and — operators?

No. Use x += 1 and x -= 1.

What does the % operator do in Python?

It returns the remainder of a division (17 % 5 is 2). It is also used in old-style string formatting such as "%d items" % 3.

Python Type Casting

Python Tutorial › Basics › Type Casting

Python Type Casting

BeginnerLesson 11 of 479 min read8 runnable examples

Type casting means converting a value from one type to another, such as turning the text “42” from input() into the number 42. Python does some conversions for you, and you do the rest with built-in functions named after the types.

In this lesson
  • Implicit vs explicit conversion
  • Convert between numbers and strings
  • Convert between collections
  • Handle values that cannot be converted

Implicit conversion

When you mix an int and a float in arithmetic, Python converts the int to a float for you, so no precision is lost:

Python
qty = 3          # intprice = 19.5     # floattotal = qty * priceprint(total, type(total).__name__)print(True + True)    # bool is a kind of int: True is 1
Output
58.5 float
2

Python will not guess between text and numbers. Mixing them is an error:

Python
age = 30print("Age: " + age)
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print("Age: " + age)
          ~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str

Explicit conversion functions

FunctionConverts toExampleResult
int(x)whole numberint("42"), int(9.8)42, 9
float(x)decimalfloat("3.5"), float(2)3.5, 2.0
str(x)textstr(100)'100'
bool(x)True/Falsebool(0), bool("no")False, True
list(x)listlist("abc")['a', 'b', 'c']
tuple(x)tupletuple([1, 2])(1, 2)
set(x)setset([1, 1, 2]){1, 2}
dict(x)dictdict([("a", 1)]){'a': 1}

Numbers and strings

Python
age = 30print("Age: " + str(age))        # number to textprint(int("42") + 8)             # text to numberprint(float("3.75") * 2)print(int(9.99), int(-9.99))     # int() truncates towards zeroprint(int("  15\n"))             # surrounding whitespace is ignored
Output
Age: 30
50
7.5
9 -9
15

int() can also read numbers written in other bases:

Python
print(int("ff", 16), int("0b1010", 0), int("777", 8))
Output
255 10 511

Values that cannot be converted

Python
print(int("3.5"))
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(int("3.5"))
          ~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.5'

int() will not read a decimal string. Convert to float first, or catch the error:

Python
print(int(float("3.5"))) for text in ["12", "4.0", "abc"]:    try:        print(text, "->", int(text))    except ValueError:        print(text, "-> not a whole number")
Output
3
12 -> 12
4.0 -> not a whole number
abc -> not a whole number

Converting to bool

bool() returns False for “empty” or zero values and True for everything else.

Python
for v in [0, 0.0, "", "0", "False", [], [0], None]:    print(f"{v!r:8} -> {bool(v)}")
Output
0        -> False
0.0      -> False
''       -> False
'0'      -> True
'False'  -> True
[]       -> False
[0]      -> True
None     -> False
Watch out

bool("False") is True, because it is a non-empty string. To read a yes/no answer, compare the text: answer.strip().lower() in ("yes", "y", "true").

Between collections

Python
letters = list("banana")print(letters)print(set(letters))                    # duplicates removedprint(tuple(letters[:3]))print("".join(letters))               # list of strings back to one string pairs = [("chrome", 120), ("firefox", 118)]print(dict(pairs))print(list({"x": 1, "y": 2}))          # a dict converts to its keys
Output
['b', 'a', 'n', 'a', 'n', 'a']
{'a', 'b', 'n'}
('b', 'a', 'n')
banana
{'chrome': 120, 'firefox': 118}
['x', 'y']

Check your understanding

Predict the output

print(int("7") + float("2.5"), str(7) + str(2.5), int(True))

Quick quiz

1. What does int("3.9") do?

2. What does bool("0") return?

3. Which converts [3, 1, 3] to a collection with only unique items?

Exercise: sum numbers from text

A line of comma-separated numbers arrives as text. Convert it and print the total and the average.

Input
"12, 7.5, 30, 0.5"
Expected output
[12.0, 7.5, 30.0, 0.5]
Total: 50.0
Average: 12.5
Hint 1

split(",") gives the parts as strings; float() converts each one.

Program Practice

Python type casting FAQ

How do I convert a string to an integer in Python?

Use int("42"). If the string may contain a decimal point, use int(float(text)), and wrap it in try / except ValueError for user input.

How do I convert an integer to a string?

Use str(42), or put it in an f-string: f"{42}".

What is the difference between implicit and explicit type conversion?

Implicit conversion is done by Python automatically, such as int to float in 3 * 1.5. Explicit conversion is when you call a function such as int() or str() yourself.

How do I convert a list to a string?

Use ", ".join(items) for a list of strings. For other values, convert each one first: ", ".join(map(str, numbers)).

Python Numbers & Math

Python Tutorial › Basics › Numbers & Math

Python Numbers & Math

BeginnerLesson 10 of 4711 min read12 runnable examples

Python has three number types and a rich set of tools for working with them. This lesson covers arithmetic, rounding, the float precision trap, the math module and random numbers.

In this lesson
  • int, float and complex numbers
  • Arithmetic including // and %
  • Rounding and float precision
  • The math and random modules

Three number types

Python
count = 42          # int: whole number, any sizeratio = 0.75        # float: decimal numbersignal = 3 + 4j     # complex: real + imaginary part print(type(count).__name__, type(ratio).__name__, type(signal).__name__)print(abs(signal))  # length of the complex number
Output
int float complex
5.0

Large numbers are easier to read with underscores. Python ignores them:

Python
population = 1_428_627_663print(population)print(2 ** 64)
Output
1428627663
18446744073709551616

Arithmetic operators

OperatorMeaning17 ? 5
+add22
-subtract12
*multiply85
/divide (always float)3.4
//floor divide (round down)3
%remainder (modulo)2
**power1419857
Python
a, b = 17, 5print(a + b, a - b, a * b)print(a / b, a // b, a % b)print(a ** b)
Output
22 12 85
3.4 3 2
1419857

// and % work as a pair: a == (a // b) * b + a % b. divmod() gives both at once. A classic use is converting seconds:

Python
seconds = 3725minutes, secs = divmod(seconds, 60)hours, minutes = divmod(minutes, 60)print(f"{hours}h {minutes}m {secs}s")
Output
1h 2m 5s
Tip

n % 2 == 0 is the standard test for an even number. Many practice programs use it.

Order of operations

Python follows the usual maths rules: * first, then , /, //, %, then + and -. Use parentheses to make your intent clear.

Python
print(2 + 3 * 4)print((2 + 3) * 4)print(2 ** 3 ** 2)    # ** groups from the right: 2 ** 9print(-2 ** 2)        # ** binds tighter than the minus sign
Output
14
20
512
-4

Rounding

Python
price = 2.675print(round(price, 2))print(round(2.5), round(3.5))     # ties round to the even numberprint(int(7.9), int(-7.9))        # int() cuts off the decimals
Output
2.67
2 4
7 -7

round(2.5) gives 2 because Python uses “banker’s rounding”: a tie goes to the nearest even number. round(2.675, 2) gives 2.67 because 2.675 cannot be stored exactly as a float; it is really slightly less.

Float precision

Python
print(0.1 + 0.2)print(0.1 + 0.2 == 0.3) import mathprint(math.isclose(0.1 + 0.2, 0.3))
Output
0.30000000000000004
False
True

For money, use Decimal with string inputs, which stores decimal digits exactly:

Python
from decimal import Decimal print(Decimal("0.1") + Decimal("0.2"))total = Decimal("19.99") * 3print(total)
Output
0.3
59.97
Watch out

Never compare floats with ==. Use math.isclose() or compare rounded values.

Useful built-in functions

Python
nums = [4, -9, 15, 2]print(abs(-9), max(nums), min(nums), sum(nums))print(pow(2, 10), pow(2, 10, 1000))   # third argument: remainder
Output
9 15 -9 12
1024 24

The math module

Python
import math print(math.sqrt(144))print(math.floor(4.7), math.ceil(4.2))print(math.pi)print(math.factorial(5))print(math.gcd(48, 36), math.lcm(4, 6))print(round(math.log10(1000)), round(math.hypot(3, 4)))
Output
12.0
4 5
3.141592653589793
120
12 12
3 5

Random numbers

The random module picks pseudo-random values. random.seed() makes the sequence repeatable, which is useful in tests.

Python
import random random.seed(7)print(random.randint(1, 6))           # dice roll: 1 to 6 inclusiveprint(random.choice(["red", "green", "blue"]))print(round(random.random(), 3))      # float from 0.0 up to 1.0
Output
3
red
0.395

Number systems

Python
print(bin(10), oct(10), hex(255))print(int("1010", 2), int("ff", 16))
Output
0b1010 0o12 0xff
10 255

Check your understanding

Predict the output

print(7 // 2, -7 // 2, 7 % 3, -7 % 3)

Quick quiz

1. What does 10 / 2 return?

2. What does round(2.5) return?

3. How do you get the remainder of 17 divided by 5?

4. Which is the safe way to compare two floats?

Exercise: simple interest

Calculate simple interest and the total amount, rounded to 2 decimals.

Input
principal = 15000, rate = 7.5 (% per year), years = 3
Expected output
Interest: 3375.0
Total: 18375.0
Hint 1

Simple interest is principal * rate * years / 100.

Program Practice

Python numbers and math FAQ

What is the difference between / and // in Python?

/ is true division and always returns a float (7 / 2 is 3.5). // is floor division and rounds down (7 // 2 is 3).

Why does 0.1 + 0.2 not equal 0.3 in Python?

Floats are stored in binary, which cannot represent 0.1 exactly. The result is 0.30000000000000004. Use math.isclose() or decimal.Decimal when exactness matters.

How do I round a number to 2 decimal places in Python?

Use round(x, 2) to get a number, or f"{x:.2f}" to get a string for display.

How do I get the square root in Python?

Use math.sqrt(x) after import math, or x ** 0.5.

Python User Input

Python Tutorial › Getting Started › User Input

Python User Input

BeginnerLesson 7 of 478 min read7 runnable examples

input() pauses your program and waits for the user to type something and press Enter. It is the simplest way to make a program interactive, and it is used in many practice programs.

In this lesson
  • Read text with input()
  • Convert input to numbers
  • Read several values from one line
  • Handle input that is not a number

Read text with input()

input() shows an optional prompt, waits for the user and returns what they typed as a string.

Python
name = input("What is your name? ")print("Hello,", name)
Outputtyped input: Asha
What is your name? Asha
Hello, Asha
Note

When you press Try it and Run on this site, your browser shows a small box for each input(). The recorded output above shows a run where the user typed Asha, exactly as it appears in a terminal.

input() always returns a string

Even if the user types digits, you get a string. Adding two strings joins them instead of adding numbers:

Python
a = input("First number: ")b = input("Second number: ")print(a + b)print(type(a))
Outputtyped input: 5, 7
First number: 5
Second number: 7
57
<class 'str'>

Convert input to a number

Wrap input() in int() for whole numbers or float() for decimals.

Python
qty = int(input("Quantity: "))price = float(input("Price: "))print("Total:", qty * price)
Outputtyped input: 5, 7.5
Quantity: 5
Price: 7.5
Total: 37.5
You wantUseExample inputResult
Textinput()pune'pune'
Whole numberint(input())4242
Decimal numberfloat(input())3.753.75

Several values on one line

split() breaks a string on spaces and returns a list. Combine it with map() to convert every part:

Python
numbers = input("Enter numbers separated by spaces: ").split()print(numbers) values = list(map(int, numbers))print(sum(values))
Outputtyped input: 10 20 30
Enter numbers separated by spaces: 10 20 30
['10', '20', '30']
60

Unpack directly into variables when you know how many values to expect:

Python
width, height = map(int, input("Width and height: ").split())print("Pixels:", width * height)
Outputtyped input: 1920 1080
Width and height: 1920 1080
Pixels: 2073600

Handle invalid input

If the user types abc, int() cannot convert it and raises a ValueError:

Python
age = int(input("Age: "))
Outputtyped input: abc
Age: abc
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    age = int(input("Age: "))
ValueError: invalid literal for int() with base 10: 'abc'

Catch the error with try / except and ask again. The Exception Handling lesson explains this pattern fully.

Python
while True:    text = input("Age: ")    try:        age = int(text)    except ValueError:        print(f"{text!r} is not a whole number, try again")        continue    if age < 0:        print("Age cannot be negative")        continue    break print("Age saved:", age)
Outputtyped input: abc, -3, 29
Age: abc
'abc' is not a whole number, try again
Age: -3
Age cannot be negative
Age: 29
Age saved: 29
Tip

text.strip() removes spaces the user typed by accident before or after the value. Use it before comparing input, for example input().strip().lower() == "yes".

Check your understanding

Quick quiz

1. The user types 8. What is the type of input()‘s result?

2. What does "3" + "4" give?

3. Which reads two whole numbers typed on one line as 4 9?

Exercise: rectangle calculator

Ask for the width and height on one line and print the area and the perimeter.

Input
4 6
Expected output
Width and height: 4 6
Area: 24
Perimeter: 20
Hint 1

split() then map(int, ...) gives you two numbers.

Hint 2

Perimeter is 2 * (width + height).

Program Practice

Many basic programs read their values with input(). Try changing a solution to ask the user instead of using fixed values.

Python input FAQ

How do I take integer input in Python?

Wrap input() in int(): n = int(input("Enter a number: ")). Use float() for decimal numbers.

How do I take multiple inputs in one line?

Use split(): a, b = input().split(). Add map(int, ...) to convert them to numbers.

What happens if the user enters text when I expect a number?

int() raises ValueError. Catch it with try / except ValueError and ask again.

Is raw_input() still available?

No. raw_input() was Python 2. In Python 3, input() does the same job and always returns a string.

Python Output & Comments

Python Tutorial › Getting Started › Output & Comments

Python Output & Comments

BeginnerLesson 6 of 4710 min read10 runnable examples

print() is how your program talks to you, and comments are how you talk to the next person who reads your code. Both look simple, but a few options make them far more useful.

In this lesson
  • Print several values at once
  • Control separators with sep and end
  • Print variables neatly with f-strings
  • Write comments and docstrings that help

The print() function

print() writes text to the screen and then moves to a new line. You can give it any value: text, numbers, lists or the result of a calculation.

Python
print("Hello, Python")print(42)print(3.5 * 2)print([1, 2, 3])print()                 # an empty lineprint("after the blank line")
Output
Hello, Python
42
7.0
[1, 2, 3]

after the blank line

Print several values

Separate values with commas. print() converts each one to text and puts a space between them, so you can mix text and numbers without converting anything.

Python
name = "Asha"tests = 12print("Tester:", name, "ran", tests, "tests")
Output
Tester: Asha ran 12 tests

Change the separator: sep

sep sets what goes between the values. The default is a single space.

Python
print("2026", "11", "02", sep="-")print("a", "b", "c", sep="")print("login", "search", "checkout", sep=" | ")
Output
2026-11-02
abc
login | search | checkout

Change the line ending: end

end sets what is printed after the last value. The default is a newline ("\n"), so each print() starts a new line. Change it to keep printing on the same line.

Python
for step in range(1, 4):    print("step", step, end=" -> ")print("finished")
Output
step 1 -> step 2 -> step 3 -> finished

Print variables with f-strings

An f-string starts with f before the quote. Anything in { } is replaced by its value. This is the clearest way to build output.

Python
item = "keyboard"price = 1499.5qty = 2print(f"{qty} x {item} = {price * qty}")print(f"Price with 2 decimals: {price:.2f}")print(f"{qty=}")
Output
2 x keyboard = 2999.0
Price with 2 decimals: 1499.50
qty=2
Tip

{qty=} prints both the name and the value, which is handy while debugging. The String Formatting lesson covers alignment, padding and number formats.

Escape characters

A backslash inside a string starts an escape sequence:

EscapePrints
\na new line
\ta tab
\\one backslash
\"a double quote inside a double-quoted string
Python
print("Name\tScore")print("Asha\t91")print("Line one\nLine two")print("She said \"hi\"")print("C:\\tests\\report.txt")
Output
Name	Score
Asha	91
Line one
Line two
She said "hi"
C:\tests\report.txt

Print to a file

print() can write to a file instead of the screen with the file argument. The File Handling lesson explains open() in detail.

Python
with open("log.txt", "w") as log:    print("test started", file=log)    print("test passed", file=log) print(open("log.txt").read())
Output
test started
test passed

Comments

A comment starts with #. Python ignores everything from # to the end of the line. Use comments to explain why the code does something, not what it obviously does.

Python
# Prices are stored in paise to avoid rounding errors with floatsprice_paise = 149950 discount = 0.10   # 10% festival discount, ends 15 Novfinal = price_paise * (1 - discount)print(final / 100)
Output
1349.55

Multi-line comments

Python has no special multi-line comment. Put # at the start of each line. Most editors do this for a selection with Ctrl+/.

Python
# Step 1: read the users file# Step 2: keep only active users# Step 3: print their namesusers = [("asha", True), ("ravi", False), ("meena", True)]print([name for name, active in users if active])
Output
['asha', 'meena']

Docstrings

A string written as the first line of a function, class or module is a docstring. Unlike a comment, Python keeps it, and help() shows it.

Python
def area(width, height):    """Return the area of a rectangle."""    return width * height print(area(3, 4))print(area.__doc__)
Output
12
Return the area of a rectangle.
Note

A triple-quoted string on its own in the middle of code is not a comment. Python creates the string and throws it away. It works, but # is the correct tool for comments.

Check your understanding

Predict the output

print("a", "b", sep="*", end="!")print("c")

Quick quiz

1. What is the default value of sep in print()?

2. Which line prints Total: 5 when n = 5?

3. How do you write a comment in Python?

Exercise: print a receipt line

Print one receipt line from these variables, with the price to 2 decimal places and | between the fields.

Input
item = "Mouse", qty = 3, price = 349.5
Expected output
Mouse | 3 | 1048.50
Hint 1

Use an f-string and the format :.2f for the total.

Program Practice

Python print and comments FAQ

How do I print without a newline in Python?

Pass end="" (or any other text) to print(), for example print("Loading", end="").

How do I print a variable with text?

Use an f-string, for example print(f"Total: {total}"), or pass several values: print("Total:", total).

How do I write a multi-line comment in Python?

Start each line with #. Triple-quoted strings are for docstrings, not comments.

What is the difference between a comment and a docstring?

Python ignores comments completely. A docstring is a real string stored on the function, class or module, and tools such as help() and IDEs display it.

Python Syntax

Python Tutorial › Getting Started › Python Syntax

Python Syntax

BeginnerLesson 5 of 479 min read9 runnable examples

Syntax is the set of rules for how Python code must be written. Python’s rules are few, but one of them, indentation, is stricter than in most languages. Learn these rules once and most beginner errors disappear.

In this lesson
  • How statements and lines work
  • Why indentation defines blocks
  • How to split long lines
  • Python keywords and case sensitivity

Statements and lines

A Python program is a list of statements, normally one per line. Python runs them from top to bottom. No semicolon is needed at the end of a line.

Python
city = "Pune"temperature = 31print(city, temperature)
Output
Pune 31

Indentation defines blocks

Many languages use curly braces { } to group lines. Python uses indentation: the spaces at the start of a line. A line ending in a colon : starts a block, and every line in that block must be indented by the same amount.

Python
score = 82 if score >= 50:    print("Passed")          # inside the if block    print("Well done")       # also insideprint("Report finished")     # outside: runs every time
Output
Passed
Well done
Report finished
Tip

Use 4 spaces per level. Every IDE inserts 4 spaces when you press Tab in a .py file. Never mix tabs and spaces in one file.

Wrong indentation is a syntax error, and Python refuses to run the file:

Python
if True:print("not indented")
Output
  File "main.py", line 2
    print("not indented")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 1

Indenting a line that should not be indented is also an error:

Python
print("one")    print("two")
Output
  File "main.py", line 2
    print("two")
IndentationError: unexpected indent

Blocks inside blocks

Each new block adds one more level of indentation. Python knows a block has ended when the indentation goes back.

Python
for n in [1, 2, 3, 4]:    if n % 2 == 0:        print(n, "is even")    else:        print(n, "is odd")print("done")
Output
1 is odd
2 is even
3 is odd
4 is even
done

Long lines

Python ends a statement at the end of the line, except inside brackets (), [] or {}. So the easiest way to split a long line is to wrap it in parentheses.

Python
total = (    120    + 80    + 45)names = ["login", "search",         "checkout"]print(total, names)
Output
245 ['login', 'search', 'checkout']

A backslash \ at the end of a line also continues it, but brackets are clearer and are what the PEP 8 style guide recommends.

Several statements on one line

A semicolon lets you put two statements on one line. It works, but it hurts readability, so use it rarely.

Python
a = 1; b = 2; print(a + b)
Output
3

Case sensitivity

Python is case-sensitive: name, Name and NAME are three different variables, and Print is not the same as print.

Python
name = "Asha"Name = "Ravi"print(name, Name)Print("hello")
Output
Asha Ravi
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    Print("hello")
    ^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?

Keywords

Keywords are reserved words with a special meaning, such as if, for and def. You cannot use them as variable names. The keyword module lists them:

Python
import keywordprint(len(keyword.kwlist))print(keyword.kwlist)
Output
35
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Note

True, False and None are keywords too, and they start with a capital letter. true or none would be treated as ordinary (undefined) names.

Check your understanding

Predict the output

x = 5if x > 3:    print("big")print("end")if x > 10:    print("huge")

Quick quiz

1. What marks the start of a block in Python?

2. How many spaces per indentation level does PEP 8 recommend?

3. Which of these is a valid variable name?

Exercise: fix the indentation

This program should print “Even numbers:” once, then each even number, then “Done”. Fix the indentation so it runs.

Hint 1

Only the print(n) line belongs inside the if.

Hint 2

“Done” must print once, after the loop, so it should not be indented.

Program Practice

Python syntax FAQ

Does Python use semicolons?

Not normally. A newline ends a statement. A semicolon is only needed to put two statements on one line, which is rarely a good idea.

What is an IndentationError?

It is the error Python raises when lines in a block are not indented consistently, or when a block is missing after a colon.

Can I use tabs instead of spaces in Python?

Python accepts tabs, but not a mix of tabs and spaces in the same block. Use 4 spaces; every editor can insert them for you.

Is Python case-sensitive?

Yes. total and Total are different names, and built-in functions such as print must be lowercase.

Python Polymorphism

Polymorphism means same function name, different behaviors, depending on class or input.

Two types in Python:

TypeMeaning
Compile-time (Overloading)Same function, different parameters (simulated in Python)
Runtime (Overriding)Child class modifies parent method

Each object responds differently to the same speak() call.


Python doesn’t support true overloading, so we use default parameters.


Same function → different behavior based on object type.


Child classes provide unique logic for inherited structure.


Explanation

  • Admin & Customer override the login() method.
  • Same method name → different behaviors based on object type.

FeatureWhat It DoesExample
InheritanceReuse parent class featuresclass B(A)
Multiple InheritanceChild from multiple parentsclass C(A,B)
PolymorphismSame method, different behaviorOverriding
OverridingModify parent methodRedefine in child
OverloadingSame name, different argumentsDefault parameters

Python Inheritance

Inheritance allows a class (child) to acquire properties and methods of another class (parent).

This promotes:

  • Code reusability
  • Hierarchy / structure
  • Cleaner and scalable programs

Explanation

  • Animal is the parent/base class.
  • Dog is the child/derived class.
  • Dog gets the speak() method without writing it again.

📝 Child gets access to both:
➡ show() (from Parent)
➡ display() (its own)


📝 Chain of inheritance: A → B → C
Class C inherits everything.


📝 Child receives methods of both parents.


📝 One parent → Multiple children.


📝 super() is used to call parent methods/constructors.

Python Generators

Python Tutorial › Functions › Generators

Python Generators

IntermediateLesson 29 of 4710 min read8 runnable examples

A generator is a function that produces a sequence of values lazily, one at a time, using yield. Generators make iterators easy to write and let you process huge or endless data without loading it all into memory.

In this lesson
  • Write generator functions with yield
  • Understand how a generator pauses and resumes
  • Use generator expressions
  • Chain generators into pipelines

Your first generator

A function that contains yield is a generator function. Calling it does not run the body; it returns a generator object. Each next() runs the body until the next yield.

Python
def countdown(n):    while n > 0:        yield n        n -= 1 gen = countdown(3)print(gen)print(next(gen), next(gen), next(gen))print(list(countdown(5)))
Output
<generator object countdown at 0x000001D0A798A800>
3 2 1
[5, 4, 3, 2, 1]

Compare with the iterator class in the Iterators lesson: the same behaviour in four lines.

yield pauses, it does not end

return ends a function. yield hands out a value and pauses, keeping all local variables, until the next request.

Python
def steps():    print("start")    yield 1    print("after first yield")    yield 2    print("finished") for value in steps():    print("got", value)
Output
start
got 1
after first yield
got 2
finished

Why generators save memory

A list holds every item at once. A generator holds only its current state.

Python
import sys numbers_list = [n * n for n in range(1_000_000)]numbers_gen = (n * n for n in range(1_000_000)) print(sys.getsizeof(numbers_list) > 1_000_000)print(sys.getsizeof(numbers_gen) < 1_000)print(sum(numbers_gen))
Output
True
True
333332833333500000
Note

The exact byte sizes depend on the Python version, which is why the example prints comparisons. The list needs megabytes; the generator needs a few hundred bytes whatever the range.

Generator expressions

Round brackets around a comprehension make a generator expression. When it is the only argument to a function, you can drop the extra brackets:

Python
words = ["python", "generators", "save", "memory"]print(max(len(w) for w in words))print(any(w.startswith("g") for w in words))lengths = (len(w) for w in words)print(next(lengths), list(lengths))
Output
10
True
6 [10, 4, 6]

Infinite generators

Because values are produced on demand, a generator can run forever. Take only what you need:

Python
def fibonacci():    a, b = 0, 1    while True:        yield a        a, b = b, a + b fib = fibonacci()print([next(fib) for _ in range(10)])
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Generator pipelines

Chain generators so each one processes the output of the previous one. Only one item flows through the pipeline at a time, which is how large log files are processed efficiently.

Python
log_lines = [    "INFO start",    "ERROR db timeout",    "INFO request ok",    "ERROR disk full",] def errors(lines):    for line in lines:        if line.startswith("ERROR"):            yield line def messages(lines):    for line in lines:        yield line.split(" ", 1)[1] for msg in messages(errors(log_lines)):    print(msg)
Output
db timeout
disk full

yield from

yield from hands out every item of another iterable, which is perfect for recursive generators:

Python
def flatten(items):    for item in items:        if isinstance(item, list):            yield from flatten(item)        else:            yield item print(list(flatten([1, [2, [3, 4]], 5])))
Output
[1, 2, 3, 4, 5]

Generators are single-use

Python
gen = (x for x in range(3))print(list(gen))print(list(gen))
Output
[0, 1, 2]
[]

Call the generator function again (or rebuild the expression) when you need the values a second time.

Check your understanding

Predict the output

def g():    for i in range(3):        yield i * 10    yield "done" it = g()print(next(it), next(it), list(it))

Quick quiz

1. What does calling a generator function return?

2. What happens to local variables at a yield?

3. Which creates a generator expression?

Exercise: read in chunks

Write a generator chunks(items, size) that yields lists of size items, with a shorter final chunk if needed.

Input
chunks(list(range(1, 11)), 4)
Expected output
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10]
Hint 1

Loop with range(0, len(items), size) and yield a slice.

Program Practice

20 Python Iterator & Generator Programs

Every program has a step-by-step explanation, colour-coded code and its real output.

Start practising →
Related sets:All practice sets

Python generators FAQ

What is the difference between yield and return?

return sends back one value and ends the function. yield sends back a value and pauses, so the function can continue and yield more values later.

When should I use a generator instead of a list?

When the data is large, endless, or only needed once in order, such as reading a big file line by line or streaming API results.

Can a generator be reused?

No. Once exhausted it stays empty. Call the generator function again to get a fresh one.