What is a variable?
A variable is a name that stores a value, like a labelled box. You create one with =, which in Python means *store*, not *equals*.
name = "Asha"
marks = 87
print(name, marks) # Asha 87
You can change what a variable holds at any time. The old value is replaced.
score = 10
score = score + 5 # take the old value, add 5, store it back
print(score) # 15
Rules for naming variables
| Rule | Allowed | Not allowed |
|---|---|---|
Letters, digits and _ only | total_marks | total-marks, total marks |
| Cannot start with a digit | class10 | 10class |
| Cannot be a keyword | my_class | class, if, for |
| Case matters | Name and name are two different variables |
Good names say what the value means: fee_per_month is better than x. Python programmers write variable names in lower case with underscores (this is called *snake_case*).
The four basic data types
| Type | Meaning | Examples |
|---|---|---|
int | whole number | 16, -3, 2026 |
float | number with a decimal point | 3.14, 99.5, -0.5 |
str | text (string), always in quotes | "Ranchi", 'A', "123" |
bool | truth value | True, False |
Use type() to check:
print(type(16)) # <class 'int'>
print(type(16.0)) # <class 'float'>
print(type("16")) # <class 'str'>
print(type(True)) # <class 'bool'>
Note that "16" in quotes is a string, not a number. "16" + "4" gives "164", not 20.
input(): let the user type a value
city = input("Which city do you live in? ")
print("You live in", city)
The program pauses, shows the message, and waits for the user to type and press Enter.
input() always gives a string
This is the most common beginner bug:
age = input("Your age: ") # the user types 15
print(age + 1) # TypeError: can only concatenate str (not "int") to str
Convert the text to a number first:
age = int(input("Your age: "))
print("Next year you will be", age + 1)
Converting between types
| Function | Converts to | Works | Fails |
|---|---|---|---|
int() | whole number | int("42"), int(9.8) gives 9 | int("9.8"), int("abc") |
float() | decimal | float("9.8"), float(3) gives 3.0 | float("ten") |
str() | text | str(25) gives "25" | (always works) |
int(9.8) cuts off the decimal part; it does not round. Use round(9.8) to round.
Converting text that is not a number gives a ValueError. You will learn to handle that safely in the errors and exceptions topic.
Multiple assignment and swapping
x, y, z = 1, 2, 3 # three variables in one line
a = b = 0 # both start at 0
p, q = 5, 9
p, q = q, p # swap: p is now 9, q is now 5
In most other languages swapping needs a third, temporary variable. In Python one line does it.
Example: a tea stall bill
tea = int(input("Cups of tea: "))
samosa = int(input("Samosas: "))
total = tea * 10 + samosa * 15
print("Total bill: Rs", total)
Common mistakes
- Forgetting to convert
input()before doing maths. - Putting a number in quotes by accident:
marks = "90"is text. - Using a variable before giving it a value:
NameError: name 'total' is not defined. - Spaces or hyphens in names:
first name = "Riya"is aSyntaxError.
Key points
=stores a value in a variable; the newest value replaces the old one.- The four basic types are
int,float,strandbool;type()shows which one you have. input()always returns a string, so wrap it inint()orfloat()for numbers.a, b = b, aswaps two values.
Practice questions
1. Which of these are valid variable names: 2nd_place, second_place, second-place, _temp?
second_place and _temp. A name cannot start with a digit or contain a hyphen.
2. What is printed by print("5" + "5") and by print(5 + 5)?
55 (two strings joined together) and 10 (two numbers added).
3. Write a program that asks for a temperature in Celsius and prints it in Fahrenheit.
c = float(input("Celsius: "))
f = c * 9 / 5 + 32
print("Fahrenheit:", f)4. What is the value of int(7.9), and how is it different from round(7.9)?
int(7.9) is 7 because it cuts off the decimal part. round(7.9) is 8.
5. After a, b = 3, 8 and then a, b = b, a, what are a and b?
a is 8 and b is 3. The values have been swapped.