Variables
A variable is a name attached to a value. Python creates the variable the first time you assign to it, and you never declare its type.
Creating variables
age = 21
name = "Rohan"
height = 1.75
is_student = True
print(name, "is", age, "years old")The = sign is assignment, not equality. It means "make age refer to 21".
Variables can change type
Because the type belongs to the value, not the name, a variable can point at a different kind of value later. This is legal but usually confusing, so avoid it in real code.
x = 10
print(x, type(x))
x = "ten"
print(x, type(x))Naming rules
A variable name:
- must start with a letter or an underscore,
- can contain letters, digits and underscores,
- is case sensitive (
totalandTotalare different), - cannot be a keyword like
iforclass.
user_name = "ok"
_private = "ok"
score2 = "ok"
# 2score = "not ok" starts with a digit
# user-name = "not ok" hyphen is subtractionNaming conventions
The Python style guide (called PEP 8) recommends:
snake_casefor variables and functions:total_price,send_emailPascalCasefor classes:BankAccountUPPER_CASEfor constants that should never change:MAX_RETRIES = 3
Choose names that say what the value is. n is fine in a two line loop; in a 200 line script it is not.
Assigning several variables at once
a, b, c = 1, 2, 3
print(a, b, c)
x = y = z = 0
print(x, y, z)Swapping two variables needs no temporary variable:
a, b = 5, 9
a, b = b, a
print(a, b)Unpacking a collection
If the right hand side is a list or tuple, Python spreads its items across the names on the left. The counts must match.
fruits = ["apple", "banana", "cherry"]
first, second, third = fruits
print(second)Printing variables
print() accepts several values and separates them with a space. For more control, f-strings (covered in the strings lessons) let you embed variables directly in text:
city = "Jaipur"
temp = 34
print(f"It is {temp} degrees in {city} today")Practice
- Create variables for your name, your city and the year you started college, then print one sentence that uses all three.
- Store the numbers 3 and 8 in two variables, swap them in one line, and print the result.
