Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
A variable is a name for a value. Instead of typing the same number or word again and again, you store it once and use the name.
You assign a value to a variable with =:
age = 12
name = "Sam"
score = 0
The name goes on the left, the value on the right. After that, whenever you use age, Python uses 12.
player_score, high_score, name22nd_place, my-name (use underscore instead of hyphen)You can use variables in print() and in calculations:
favourite_number = 7
print(favourite_number) # 7
print(favourite_number + 3) # 10
message = "My favourite number is"
print(message, favourite_number) # My favourite number is 7
If you assign a new value to the same variable, the old value is replaced:
lives = 3
print(lives) # 3
lives = 2
print(lives) # 2
You can ask the user to type something with input():
name = input("What is your name? ")
print("Hello,", name)
Whatever they type (until Enter) is stored as a string. If you want a number, you have to convert it: int(input("Enter a number: ")).
input() to ask for their name and then print “Hello, [name]”.Next: 1.3 Operators — maths and comparisons.