A variable is a name that refers to a memory location. A Python variable, also known as an identifier, is used to store data. Python is not a “statically typed” language. We do not need to declare variables or their types before using them. When we first assign a value to a variable, it is created. A variable in Python is the name given to a memory location. It is the fundamental storage unit in a program.
There are some rules to assign a name to the variable.
Python does not require us to declare variables before using them in our code. It enables us to create a variable at the appropriate time.
In Python, we don’t need to declare variables explicitly. When we assign a value to a variable, it is automatically declared.
To assign a value to a variable, use the equal (=) operator. For instance,
# declaring and assigning the var
Marks = 100
# display
print( Marks)
Output:
100
Python allows adding different values in a single line with “,” operators.
name, marks, age = "Rabecca Fatima", 80.2, 19
print(name)
print(marks)
print(age)
Output:
Rabecca Fatima
80.2
19
a = 10
b = 20
c = "Hello"
d = "World"
print(a+b)
print(c+d)
print(c+a)
Output:
30
Hello World
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Local variables are those defined and declared within a function. This variable cannot be accessed outside the function.
# This function uses local variable s
def f():
s = "Hello World"
print(s)
f()
Global variables are those that are defined and declared outside a function and must be used within one.
# This function uses global variable s
def f():
print(s)
#Global
s = "Hello World"
f()
We can delete the variable using the del keyword.
x = 6
print(x)
# deleting a variable.
del x
print(x)
Output:
6
Traceback (most recent call last):
File "<string>", line 6, in <module>
NameError: name 'x' is not defined
Note: also read about Python operators
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…