counter = 100 # An integer variable
name = "Evry" # A string variable
amount = 17.2 # A float variable1-Variables
Link to the Google Colaboratory notebook: 1-Variables
Variables
Variables store data values and can be used throughout the program.
Python variables
In Python, you don’t need to declare the variable and the type.
A Python variable is created and a place in memory is allocated when you assign a value to it.
To create a variable, use the = sign: on the left is the name of the variable, and on the right is the value.
You can print a variable using the print function:
counter = 100 # An integer variable
name = "Evry" # A string variable
print(counter)
print(name)100
Evry
String variables can be declared using either single or double quotes:
name = "Evry"
# is the same as
name = 'Evry'It is nonetheless recommended to keep the same notation for the strings. If you use single quotes, be consistent with it.
Variable names
Variables can have short (like x, y, ..,) or long (age, family_name, …) names.
There are rules for Python variables:
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (age, Age and AGE are three different variables)
- A variable name cannot be any of the Python keywords.
Here is a list of Python keywords that are reserved. Your variables, name of function, class should not be named with those words.
and |
as |
assert |
break |
class |
continue |
def |
del |
elif |
else |
except |
False |
finally |
for |
from |
global |
in |
is |
lambda |
None |
nonlocal |
not |
or |
pass |
raise |
return |
True |
try |
while |
with |
yield |
myname="Evry"
my_name="Evry"
myname2="Evry"
_my_name="Evry"
myName="Evry"
MYNAME="Evry" """
10myname="Evry"
my-name="Evry"
my name="Evry"
"""Assignment of multiple values
Python allows to assign values to multiple variables in one line:
city, age, country = "Evry", 77, "France"
print(city)
print(age)
print(country)Evry
77
France
Output variables
The print function allows you to output variables.
You can output multiple variables by separated them with a ,:
city, age, country = "Evry", 77, "France"
print(city, age, country)Evry 77 France
You can also use + to output multiple variables:
city, country = "Evry ", "France"
print(city + country)Evry France
Note that when you want to print multiple strings, the + doesn’t add a space.
You need to add it manually.
city, country = "Evry", "France"
print(city + country)EvryFrance
The + is working for strings, but act differently for other types:
x,y = 5, 10
print(x+y)15
Note that you can’t add a string and an integer with the + sign.
To print both of them, you can either separate them with ,, or cast the integer using the str function:
name, age = "Evry", 77
# print(name + age) # It will raise an error
print(name, age)
print(name + str(age))Evry 77
Evry77