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)10 20 30Rule 2: We cannot name a variable starting with a digit. 1age = 10 will give an error.
In [3]:
1age = 20 File "<ipython-input-3-ef3a9e7a157c>", line 1
1age = 20
^
SyntaxError: invalid syntaxRule 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]:
_company = "Console Flare"
company_name = "ConsoleFlare"
print(_company,company_name)Console Flare ConsoleFlareBest 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]:
company , company_member = "Console Flare",5000
print(company,company_member)Console Flare 5000How 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]:
company = firm = startup = "Console flare"
print(company,firm,startup)Console flare Console flare Console flareHow 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]:
age = 10
print(age)
age = 20
print(age)10
20Assignment:
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