Previous lesson: Python Syntax
How to create variables
Unlike other programming languages, Python has no command to declare a variable. A variable is created when you assign it a value.
x = 5 y = "Sasha" print(x) print(y)
It is not necessary to specify a specifictype of variable when declaring it. You can even change their type after creation.
x = 4 # now x is int x = "Alyona" # now x is str print(x)
A variable can have a short name (e.g.,
y) or a more meaningful name
total_volume). The rules for variables in Python:
- A variable name must start with a letter or underscore character.
- It cannot begin with a number.
- A variable name can only contain alphanumeric characters and underscores (Az, 0-9 and
- Variable names are case sensitive
AGEare three different variables)
Remember that variables are case-sensitive
x = "unbelievable." print("Python " + x)
Python is improbable
You can also use the
+ symbol to add a variable to another variable:
x = "Python " y = "unbelievable" z = x + y print(z)
Python is unbelievable
For numbers, the
+ symbol works like a mathematical operator:
x = 5 y = 10 print(x + y)
If you try to concatenate a string and a number, Python will show you an error message:
x = 5 y = "Sasha" print(x + y)
TypeError: unsupported operand type(s) for +: 'int' and 'str'