Table of Contents
Introduction Rules for naming variables Assigning values to variables Assigning a single value to multiple variables Assigning different values to multiple variables Variable having same 2 values Deleting variables in Python Concatenate operation (+) in Python Types of variables in Python Global keyword in Python Object References in Python Life cycle of an object Identity of object Reserved keywords ConclusionWhat are variables in Python?
Containers that store values are called variables in Python. Variables are only designated memory spaces for the storage of values. This implies that you set aside some memory when you create a variable.
The interpreter allots memory and determines what can be placed in the reserved memory based on the data type of a variable. Therefore, you may store integers, decimals, or characters in these variables by giving them alternative data types.
Variables do not need to be declared or specified beforehand in Python, unlike many other programming languages.
A lot of values need to be managed while developing a program. We utilize variables to store values. A variable’s value may be modified while a program is running.
Introduction
A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing.
Rules for naming variables
- Underscores (_), lowercase letters (a to z), capital letters (A to Z), or a combination of these should be used for constant and variable names. For Example: CODINGAL, Codingal, Codingal_KIDS, and many more.
- Never employ unique symbols like ! , @, #, $,%, etc
- Don’t begin the name of a variable with a digit.
- Use the underscore character to separate any two words in a variable name. For Example: codingal_kids, coding_love, and many more.
- One should make sure that a variable name is distinct from any language-specific keywords.
Assigning values to variables
When you provide a value to a variable, the declaration occurs automatically. For assigning values to variables, use the equal symbol (=).
The name of the variable is the operand to the left of the = operator, and the value that is placed in the variable is the operand to the right of the = operator.
Example:
1) Integer data type variable:
codingal = 1
Once this is done, codingal may be used in a statement or expression and its value will be replaced, which is read as “codingal is assigned the value 1.”
print(codingal)
1
2) Floating data type variable:
codingal = 1990.58
Once this is done, codingal may be used in a statement or expression and its value will be replaced, which is read as “codingal is assigned the value 1990.58.”
print(codingal)
1990.58
3) Strings data type variable:
codingal = “kids fall in love with coding”
Once this is done, codingal may be used in a statement or expression and its value will be replaced, which is read as “codingal is assigned the value kids fall in love with coding.”
print(codingal)
kids fall in love with coding
At different points in time, the variable might have different values. And during the course of the program, its value can vary.
codingal = “kids fall in love with coding”
print(codingal)
kids fall in love with coding
codingal = “Codingal is on the mission to make every kid fall in love with coding”
print(codingal)
Codingal is on the mission to make every kid fall in love with coding
Assigning a single value to multiple variables
Python enables you to simultaneously assign a single value to several variables.
Example:
Codingal = kids = love = 100
Here, the three variables are all allocated to the same memory region along with the creation of an integer object with the value 100. Additionally, you may link many objects to various variables.
print(codingal)
print(kids)
print(love)
100
100
100
Assigning different values to multiple variables
Python’s “,”operators enable us to add multiple values in a single line.
Codingal = kids = love = 100, 200000, “coding”
Here, two integer objects with values 100 and 200000 are assigned to variables codingal and kids respectively, and one string object with the value “coding” is assigned to the variable love.
print(codingal)
print(kids)
print(love)
100
200000
coding
Variable having same 2 values
The variable starts pointing to a new value and type if we use the same name.
codingal = 1
codingal = "Codingal is on the mission to make every kid fall in love with coding"
print(codingal)
Codingal is on the mission to make every kid fall in love with coding
Deleting variables in Python
When variables and functions are no longer needed, Python automatically deletes them to free up memory. Variables and functions can also be explicitly deleted by the user. When huge data structures are no longer required, eliminating them will free up memory for other applications, which might be advantageous. Python provides the delete feature to its users for this reason.
The Python del command can be used to delete a variable.
codingal=500
del codingal
print(codingal)
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(codingal)
NameError: name 'codingal' is not defined
Concatenate operation (+) in Python
In Python, you may join two or more strings with the + operator. The Python string concatenation operator is the name of this operator. You should place the + operator between the two strings you wish to combine.
Concatenation of 2 integer variables
kids = 2000
codingal = 1
print(kids+codingal)
2001
Concatenation of 1 integer variable and 1 string variable
For different types python would give an error.
kids = 2000
codingal = "Codingal is on the mission to make every kid fall in love with coding"
print(kids+codingal)
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(kids+codingal)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Concatenation of 2 string variables
kids = "Codingal is the best coding school in the world."
codingal = "Codingal is on the mission to make every kid fall in love with coding"
print(kids+codingal)
Codingal is the best coding school in the world.Codingal is on the mission to make every kid fall in love with coding
Types of variables in Python
In Python, there are 2 different types of variables:
Local Variables
Global Variables
Local variables in Python
The variables that are defined and declared inside of a function are called local variables. This variable cannot be used outside of the function.
def function():
codingal="Codingal is on the mission to make every kid fall in love with coding"
print(codingal)
function()
Codingal is on the mission to make every kid fall in love with coding
Global variables in Python
In order to use global variables inside a function, they must be defined and declared outside of the function.
def function():
print(codingal)
codingal="Codingal is on the mission to make every kid fall in love with coding"
function()
Codingal is on the mission to make every kid fall in love with coding
Global keyword in Python
A user can edit a variable outside of the current scope by using the global keyword. It is used to make global variables from non-global variables, such as variables inside of functions.
Printing and accessing do not need Global. Only when making assignments or changing variables do we utilize the global keyword within a function.
Norms of global keyword:
- Outside of a function, there is no need to use the global keyword.
- Implicitly global variables are those that are exclusively used inside of functions.
- Anywhere in the body of the function where a variable is given a value, unless specifically specified as global, it is presumed to be a local variable.
- To use a global variable inside of a function, we use the global keyword.
Example:
codingal = 10
def kids():
global codingal
codingal = codingal + 5
print("Value of codingal variable inside a function :", codingal)
kids()
print("Value of codingal variable outside a function :", codingal)
Value of codingal variable inside a function : 15
Value of codingal variable outside a function : 15
Object references in Python
What truly happens when you assign a variable?
Python’s answer to this question is somewhat different from that of many other programming languages, which makes it an important one.
The language Python is very object-oriented. The majority of the data in a Python program is actually objects of a certain type or class.
Example:
print(500)
500
The interpreter performs the following when given the statement print(500):
- It creates the integer object by using the built-in type() function.
- Assigns 500 value to it
- And then print it to the console window
A meaningful name that acts as a reference or pointer to an object is called a variable in Python. One can use the variable name to refer to an object once it has been allocated to it. However, the object itself still holds the data.
Case 1:
Now assume, the following code is executed, then:
codingal=10
In this assignment, the variable codingal is given the task to point to an integer object created that has the value 10.
Figure 1: Assignment of variable
The proof that codingal variable points to an integer object is provided by the code below:
print(codingal)
10
type(codingal)
<class 'int'>
Case 2:
Now assume, the following code is executed, then:
Codingal=kids
Figure 2: referencing of single object by 2 variables
Python doesn’t produce a new object. It only generates a new symbolic name or reference, kids, that refers to the same thing as codingal. In Python, this scenario where several names refer to the same object is known as a shared reference.
Case 3:
Now assume, the following code is executed, then:
codingal= “love”
Figure 3: new string object for codingal variable
A new string object will be created by python with the value “love” and then “codingal” will be referenced to it.
Case 4:
Now assume, the following code is executed, then:
kids= 200
Figure 4: new integer object for kids variable
A new integer object will be created by python with the value 200 and then “kids” will be referenced to it.
The integer object 10 is no longer referenced anywhere. There is no way to access it because it is not referenced by any variable. This concept refers to the concept of the Life cycle of an object.
Life cycle of an object
When an object is formed, at least one reference to it is made, and at that point, an object’s life begins.
There may be extra references established to an item over its lifetime as seen in case 2. Also References to it might also be removed as seen in case 4.
As long as there is at least one reference to an object, it remains active.
An object is no longer accessible when its reference count reaches zero. That is when its lifecycle ends.
The allocated memory will eventually become inaccessible, and Python will reclaim it so that it may be used for anything else. This operation is known as garbage collection in computer terminology.
Identity of object
Every newly formed object in Python is assigned a number that identifies it specifically. Any time that two objects’ lifetime overlap, it is assured that no two objects will ever have the same identifier.
An object is garbage collected after its reference count reaches zero, then its unique identification number becomes accessible and may be utilized once more.
The integer identification of an object is returned by the built-in Python function id(). You may confirm that two variables really do point to the same object by using the id() method.
Example 1:
Two objects with a different id.
codingal=10
kids=20
print("ID for codingal variable is:",id(codingal))
print("ID for kids variable is:",id(kids))
ID for codingal variable is: 140177633601760
ID for kids variable is: 140177633602080
Example 2:
Two variables sharing the same object will have the same id.
codingal=10
kids=codingal
print("ID for codingal variable is:",id(codingal))
print("ID for kids variable is:",id(kids))
ID for codingal variable is: 140120902031584
ID for kids variable is: 140120902031584
Reserved keywords
Identifier names are subject to one more limitation. A limited number of keywords designated as unique language functionality are reserved in the Python language. A reserved keyword cannot share a name with an object.
In Python, there are 33 reserved keywords as shown in table 1.
Table 1: Reserved Keywords
and | else | is | while | From |
as | except | lambda | with | or |
None | del | import | return | continue |
assert | finally | nonlocal | yield | global |
True | elif | in | try | pass |
False | def | if | raise | – |
break | for | not | class | – |
By entering help(“keywords”) into the Python interpreter at any moment, you may view this list. Reserved words must be used precisely as they are written and are case-sensitive. With the exception of False, None, and True, all are written in lowercase.
help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
An error occurs if you attempt to name a variable the same as any reserved word:
assert=1
File "main.py", line 1
assert=1
^
SyntaxError: invalid syntax
Conclusion
In Python, data-storing memory locations are referred to as variables. The stored data is retrieved via a variable, whose value may vary during the program.
The “=” operator is used to allocate values. When variables and functions are no longer needed, Python automatically deletes them to free up memory.
In Python, you can manually remove a variable by using the del command. In Python, there are 2 different types of variables: Local Variables & Global Variables.
Children can learn Python programming to build technical skills for the future. Codingal offers Python for kids course to help your child enhance cognitive, logical, and computational skills. Coding for kids has many beneficial advantages that develop cognitive abilities, enhance communication and entrepreneurship skills, and stimulate creativity. We provide 1:1 live interactive online coding classes with expert coding instructors for kids. Along with lifetime access to course content and downloadable learning resources, to cater to every child’s need by providing a personalized journey. Try a free class today!