Python Variable is containers which store values. Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program
Example of Python Variable
Var = "CodeHind"
- The value stored in a variable can be changed during program execution.
- A Python Variables is only a name given to a memory location, all the operations done on the variable effects that memory location.
Rules for Declaring Python Variables
- A variable name must start with a letter or the underscore character.
- The reserved words(keywords) cannot be used naming the variable.
- A variable name cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
- Variable names are case-sensitive (name, Name and NAME are three different variables).
Let’s see the simple variable Declaration:
# An integer assignment
age = 23
# A floating point
salary = 1456.8
# A string
name = "John"
Re-declare the Variable
# declaring the var
Number = 150
print("Before declare: ", Number)
# re-declare the var
Number = 100.3
print("After re-declare:", Number)
Before declare : 50
After re-declare : 100.3
Assigning a single value to multiple variables
Also, Python allows assigning a single value to several variables simultaneously with “=” operators.
a = b = c = 10
Assigning different values to multiple variables
Python allows adding different values in a single line with “,”operators.
a, b, c = 1, 20.2, "CodeHind"
Can we use the same name for different types?
If we use the same name, the variable starts referring to a new value and type.
a = 10
a = "CodeHind"
How does + operator work with variables?
a = 10
b = 20
a = "Code"
b = "Hind"
Global and Local Python Variables
Local variables are the ones that are defined and declared inside a function. We can not call this variable outside the function.
# This function uses global variable
s = "Welcome to CodeHind"
Welcome to CodeHind
Global variables are the ones that are defined and declared outside a function, and we need to use them inside a function.
# This function has a variable with
# name same as s.
# Global scope
s = "I love CodeHind"
I Love CodeHind