Lesson 2 of 12

Python Syntax and Variables

Every language has grammar rules, and Python’s are short. Once you know how Python reads a line, how it groups lines into blocks and how it stores values in Python variables, you can read most beginner programs. This lesson continues from Python Introduction, so have Python installed and a .py file ready to experiment in.

How Python reads your code

A Python program is a list of statements, normally one per line. Python runs them from top to bottom. You do not need a semicolon at the end of a line, and you should not add one: it is legal, but other Python developers will find it odd.

  • Case matters. city, City and CITY are three different names, and Print() does not work because the function is called print().
  • Blank lines are ignored. Use them to split your code into readable groups.
  • Long lines can wrap inside brackets. If a line is inside ( ), [ ] or { }, you can continue it on the next line.

Indentation is part of the syntax

Many languages use curly braces to group lines. Python uses indentation instead. A line that ends with a colon (:), such as an if or a loop, starts a block, and every line of that block must be indented by the same amount. The standard is four spaces, and every good editor inserts four spaces when you press Tab in a .py file.

marks = 72

if marks >= 40:
    print("Result: Pass")
    print("Well done!")

print("This line is outside the if block.")
Output
Result: Pass
Well done!
This line is outside the if block.

Both indented lines belong to the if. The last line is back at the left edge, so it runs whatever the marks are. You will learn if properly in Python Conditions; for now, notice how the shape of the code shows its meaning.

Watch out: Mixing tabs and spaces, or indenting one line by three spaces and the next by four, causes an IndentationError and the program does not start at all. Set your editor to insert spaces and keep every block at four.

Comments

A comment starts with #. Python ignores everything from the # to the end of the line. Write comments to explain why you did something, not to repeat what the code obviously does. Python has no special multi-line comment; put a # at the start of each line instead. Text inside triple quotes at the top of a function is a docstring, which you will meet in Python Functions.

Python variables

A variable is a name that refers to a value. You create one by assigning a value with =. There is no keyword such as var or let, and you do not declare a type: Python works it out from the value. This is called dynamic typing.

# A simple bill at a tea stall in Madurai
customer = "Arun"
cups = 3
price_per_cup = 15

total = cups * price_per_cup
print(customer, "pays ₹", total)

# Update a variable: the old value is replaced
cups = cups + 2
total = cups * price_per_cup
print(customer, "now pays ₹", total)

# A variable can later point to a different kind of value
cups = "five"
print("cups is now the text:", cups)
Output
Arun pays ₹ 45
Arun now pays ₹ 75
cups is now the text: five

Read = as “now refers to”, not “equals”. The line cups = cups + 2 makes no sense in maths, but in Python it means: take the current value of cups, add 2, and store the result back in cups.

Naming rules and style

RuleValidInvalid
Start with a letter or underscorecity, _count2nd_place
Only letters, digits and underscorestotal_2026total-price, my price
Not a reserved keywordclass_nameclass, if, for

Python’s official style guide, PEP 8, recommends snake_case for variables: lower-case words joined by underscores, such as price_per_cup. Names in capitals, such as GST_RATE = 18, signal a constant: a value you do not intend to change. Python does not enforce this; it is a promise to other readers. Choose names that describe the value, so total_fee is far better than tf or x.

Assigning several variables at once

Python lets you assign more than one variable on a line. The most famous use is swapping two values without a temporary variable.

name, city, pincode = "Lakshmi", "Salem", 636001
print(name, city, pincode)

morning_shift = "Ravi"
evening_shift = "Meena"
morning_shift, evening_shift = evening_shift, morning_shift
print("Morning:", morning_shift)
print("Evening:", evening_shift)

stock_a = stock_b = 0
print(stock_a, stock_b)
Output
Lakshmi Salem 636001
Morning: Meena
Evening: Ravi
0 0

Printing variables neatly

You have already used print() with commas. Two optional arguments give you more control: sep sets what goes between the values (a space by default), and end sets what goes at the end (a new line by default). For mixing text and values, an f-string is usually the clearest choice; it also avoids the unwanted space you saw in ₹ 45 earlier.

day, month, year = 15, 8, 1947
print(day, month, year, sep="/")

print("Loading", end="... ")
print("done")

item = "Mysore Pak"
weight_g = 250
print(f"{item}: {weight_g} g pack")
Output
15/8/1947
Loading... done
Mysore Pak: 250 g pack

Tip: Python also lets you add an optional type hint, such as pincode: int = 605001. Python does not check it when the program runs, but editors and tools use it to warn you about mistakes. You will see light use of hints later in this track.

Next, find out what kinds of values Python variables can hold in Python Data Types.

Further reading

Key takeaways

  • Python runs statements top to bottom; no semicolons are needed and names are case-sensitive.
  • Blocks start after a colon and are marked by indentation, normally four spaces.
  • Comments start with # and should explain why, not what.
  • Create a variable with =; Python works out the type from the value.
  • Use snake_case names, UPPER_CASE for constants, and a, b = b, a to swap.

Quick quiz

Check what you learned – pick an answer.

1. Which of these is a valid Python variable name?

2. How does Python know which lines belong to an if block?

3. What does print(1, 2, 3, sep="-") show?

Practice exercise

A Chennai bookshop sells notebooks at ₹45 each. Store the customer name, the number of notebooks (4) and the price in variables. Print the total with an f-string, then a customer buys 2 more: update the quantity and print the new total.

Show a hint

Calculate the total from the variables each time instead of typing the number yourself.

Show the solution
customer = "Divya"
notebooks = 4
price = 45

print(f"{customer} pays ₹{notebooks * price} for {notebooks} notebooks")

notebooks = notebooks + 2
print(f"{customer} now pays ₹{notebooks * price} for {notebooks} notebooks")

Progress is saved in this browser only.