Variables are an essential part of any programming language. A variable is a name that refers to a value stored in the computer's memory, so you can use and change that value later in your program.
Creating variables
In Python you do not declare variables: they are created the first time you assign a value with the = operator.
name = "Ana"
age = 25
height = 1.68
is_student = True
print(name, age, height, is_student)
You also do not have to say which type of data a variable stores. Python deduces the type from the value, and the same name can later refer to a value of another type (this is called dynamic typing):
x = 10
print(type(x)) # <class 'int'>
x = "ten"
print(type(x)) # <class 'str'>
The type() function returns the type of a value.
Naming rules
- A name can contain letters, digits and underscores, but it cannot start with a digit.
- Names are case sensitive:
age,AgeandAGEare three different variables. - You cannot use reserved words such as
if,for,classorTrue. - By convention, names are written in
snake_case(lowercase words separated by underscores), for exampletotal_price.
total_price = 19.99 # valid
user_name = "Leo" # valid
# 2nd_place = 2 # invalid: starts with a digit
# for = 3 # invalid: reserved word
Assigning several variables at once
a = b = c = 0 # the same value for the three variables
x, y, z = 1, 2, 3 # one value for each variable
x, y = y, x # swap two values
Constants
Python has no real constants. By convention, a value that should not change is written in uppercase:
PI = 3.14159
MAX_ATTEMPTS = 3
Reading data into a variable
The input() function reads text typed by the user and returns it as a string, so you can store it in a variable:
name = input("What is your name? ")
print("Nice to meet you,", name)
Deleting a variable
The del statement removes a name: after del x, using x raises a NameError.