3. Variables in Python
What are Variables?
Variables are containers that store temporary values or information in computer memory. To use a variable in a program, you must declare a variable.
What do we mean by declaring a Variable in Python?
In Python, the moment we store any information or value in a variable, the variable is declared. We can use variables in a program once we declare them or store a value in them. There are two most important entities to declare a variable: a. Variable name b. Value
For Example:
In [1]:
age = 10
print(age)10Here, 10 is a value stored in a variable named age. This is how we declare a Variable in Python.
Naming Convention in Variable:
There are some rules and best practices to follow while naming a variable:
Rule 1: Variables are Case-Sensitive. It means a variable with lowercase is different than the variable in upper case.
In [2]:
age = 10
Age = 20
AGE = 30
print(age,Age,AGE)Rule 2: We cannot name a variable starting with a digit. 1age = 10 will give an error.
In [3]:
Rule 3: We cannot use whitespaces or any symbol while naming a variable, though an underscore is allowed (_). For Example -
a ge = 10 , @%age=10 will give error
_age = 10 , voting_age = 18 is good.
In [1]:
Best Practice: While naming a variable, keep in mind to give variables a meaningful name. a = 10 does not give a clearer message than age = 10
How to assign or store multiple values in multiple variables:
To assign multiple values in multiple variables, we can simply write them in a single line of code using commas. For Example:
In [2]:
How to assign a single Value in multiple variables:
To assign a single value in multiple variables , we can simply write them in a single line of code using = sign. For Example:
In [3]:
How to change a value of a variable:
Suppose there is a variable named age with value 10 , we will write it like this (age = 10) to change the value of variable we will again store another value to the same variable. for Example:
In [4]:
Assignment:
Create a variable and store any numerical value.
Change the value stored in a variable.
Store 10,20,30 in three different variables in a single line.
Store 10 in three different variables in a single line.
Last updated