Beginner · First steps in Python · topic 3 of 50 · 20 min
Variables: giving names to values
Explanation
Why we need variables
Programs work with values: prices, names, marks. If you want to use a value more than once, or change it later, you give it a name. That name is called a variable.
price = 120
quantity = 3
total = price * quantity
print(total)The = sign means "store", not "equals"
In maths, = means both sides are equal. In Python, = is the assignment operator: it takes the value on the right and stores it in the name on the left. Assignment means "give a value to a name".
marks = 70
marks = marks + 5
print(marks)Rules for variable names
- Use letters, digits and the underscore _. No spaces.
- A name cannot start with a digit: 2nd_place is wrong, second_place is fine.
- Names are case-sensitive: Age and age are two different variables.
- Do not use Python's own keywords such as if, for, class or print as names.
Values have types
Every value has a type, which tells Python what kind of thing it is. The most common types are int (whole numbers), float (numbers with a decimal point), str (text) and bool (True or False). The function type() tells you the type.
name = "Priya"
age = 21
height = 5.4
is_student = True
print(type(name), type(age), type(height), type(is_student))Assigning several variables at once
a, b = 5, 10
a, b = b, a
print(a, b)Watch the lesson
Variables: giving names to values · 1/7
In this lesson you will learn about variables, the names that hold values in your program.
Prefer a video by a teacher? Find free videos on “python variables and data types for beginners” on YouTube ↗
In real life: Splitting a restaurant bill
Aman and three friends had dinner. The bill is 1,840 rupees and they want to add a 10% tip, then split it equally. Variables keep each value labelled, so anyone reading the code knows what each number means.
bill = 1840
tip = bill * 10 / 100
friends = 4
each_pays = (bill + tip) / friends
print("Each friend pays", each_pays, "rupees")Practice (0/2 done)
Inside the function total_cost(), create a variable price = 45 and a variable quantity = 4, then return price multiplied by quantity.
Write a function swap(a, b) that returns the two values in the opposite order, as a pair: swap(1, 2) should give (2, 1).
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.