Creating variables
name = "Ananya" age = 19 height = 1.62 print(name, age, height)
Write Python. Understand every error.
Python basics · topic 3 of 25
A variable is a name that refers to a value. You create one with =, which means "store the value on the right under the name on the left". It does not mean "equals" as in maths.
city = "Kolkata" students = 45 print(city, students)
A variable can be given a new value at any time. Python works out the right side first, so score = score + 5 takes the old score, adds 5, and stores the result. The shortcut score += 5 does the same thing.
Names may contain letters, digits and underscores, but cannot start with a digit or contain spaces. They are case-sensitive, so Total and total are different. Python programmers usually write names like total_marks.
Python can swap two variables in one line: a, b = b, a.
= stores a value; it does not compare.x += 1 is short for x = x + 1.price, not p.= stores a value. It does not compare two things.x += 1 is short for x = x + 1.price is clearer than p.2marks or total marks. Read the SyntaxError guide.
name = "Ananya" age = 19 height = 1.62 print(name, age, height)
score = 10 print(score) score = score + 5 print(score) score += 5 print(score)
a = 3 b = 8 a, b = b, a print(a, b)
length = 12 width = 5 area = length * width print("Area:", area)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
x = 5 x = x + 3 print(x)
The right side is worked out first: 5 + 3 = 8, and then stored back in x.
a = 10 b = a a = 20 print(b)
b = a copied the value 10. Changing a later does not change b.
Names cannot start with a digit, cannot contain spaces, and cannot be keywords like class.
a, b = 3, 7 a, b = b, a print(a, b)
a, b = b, a swaps the two values in one step.
count = 4 count += 2 count *= 3 print(count)
4 + 2 = 6, then 6 * 3 = 18. += and *= update the variable.