
Variables –
Variables in python provides a way to associate names with objects. In python, we do not need to declare a variable before using them or declare it’s type as compared to other programming languages.
To create a variable, you have to write
a = 10
b = 20
c = a + b
Here, a , b and c are three variables that we have created. And if you print their values you will get
print("a:", a)
print("b:", b)
print("c:", c)
output -
a: 10
b: 20
c: 30
The assignment operator = assign name to the left of the = symbol with the object to the right of = symbol.
Now, if I change the value of the variable a to 20 and print the result. You will see that value of a is equal to 20 but the value of c is still 30.
a = 20
print("a:", a)
print("b:", b)
print("c:", c)
output -
a: 20
b: 20
c: 30
To change the value of c after the new assignment of a, we need to call c again.
c = a + b
print("a:", a)
print("b:", b)
print("c:", c)
output -
a: 20
b: 20
c: 40
You can also assign a single value to multiple variables at once like this
a = b = c = 50
print("a:", a)
print("b:", b)
print("c:", c)
output -
a: 50
b: 50
c: 50
or assign different values to multiple variables at once like this
a , b, c = 100, 200, "python"
print("a:", a)
print("b:", b)
print("c:", c)
output -
a: 100
b: 200
c: python
And you don’t have to always assign numbers to a variable, you can assign any other data types like strings, boolean values, lists , dictionary etc. Here we assigned a string to the c variable. In our upcoming posts we will look at various data types in python so make sure to checkout our blog later or subscribe below to get notified.
Rules for creating variables –
There are few rules that you have to follow when creating variables otherwise python will throw errors.
1 . Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a number. For example a1 is a valid variable name but 1a is not.
2 . Spaces are not allowed in variable names, but you can use underscores to separate words in variable names. For example add_two_numbers
3 . You can not use reserve words in python for variable names like def, assert, global etc.
4 . Variable names are case sensitive. a and A is two different variable, they are not same.