1 - Creating a variable in Python
Unlike other programming languages, Python does not have a command to declare a variable. A variable is created when you assign a value to it.
Example
x = 7
y = "Albert"
print (x)
print (y)
Variables do not have to be declared with a particular type and can even change type after being defined.
Example
x = 3
print (type (x)) # x is of type int
x = "Hello"
print (type (x)) # x is now of type string
2 - Variable names
A variable can have a short name (like x and y) or a name composed of several descriptive (age, weight, job).
3 - Rules for Python variables
- A variable name must begin with a letter or underscore
- A variable name can not start with a number
- A variable name can contain only alphanumeric characters and underscores (A-z, 0-9 and _)
- A Variable names are case-sensitive (alberto, Alberto, ALBERTO are three different variables)
- Remember that variables are case-sensitive
4 - Output of a Variable
The Python print() statement is often used to generate the output of variables. To combine text and a variable, Python uses the '+' character:
Example
s = "the best programming language"
print ("Python is" + s)
You can also use the '+' character to add a variable to another variable:
Example
x = "python is"
y = "object oriented"
z = x + y
print (z)
For numbers, the '+' character works as a mathematical operator:
Example
x = 7
y = 2
print (x + y) # displays 9
If you try to combine a string and a number, Python will give you an error:
Example
x = 3
y = "Alberto"
print (x + y) # Generates an error message indicating that it is not possible to add a string to a number!