Variables are most foundational and powerful building blocks of any progamming languages. Variable are used to store and manipulate the data, these are containers for storing data.
In Python, you don't need to explicitly declare the data type of a variable. You can create a variable simply by assigning a value to it. Here are two simple examples:
age = 22
first_name = 'arya'
last_name = 'stark'
input_value_flag = True
Python programmers follow snake case, here are high level summary of different patterns :
firstName
, pricePerHour
FirstName
, PricePerHour
first_name
, price_per_hour
In static typing variable types are explicitly declared and checked at compile-time, while in dynamic typing variables can be assigned to different types of values and the type checking is done at runtime.
Python is dynamically typed, which means that the type of a variable is determined at runtime based on the value assigned to it. You can change the value and type of a variable as needed.
Some basic rules of variable naming
name
and Name
are different.Some other points
If you want to assign same value to muliple variables, you can do so in one line
a = b = c = 22
print("a:",a)
print("b:",b)
print("c:",c)
output
a: 22
b: 22
c: 22
Same way multile variables can be assigned separate values on same line as below.
a, b, c = 22, 55.55, "HDFC Bank"
print("a:",a)
print("b:",b)
print("c:",c)
output
a: 22
b: 55.55
c: HDFC Bank
If we assign a new value to an existing variable, original value will get overwritten and variable will keep latest value
name = 'arya'
print('name:', name)
name = 'arya stark'
print('name:', name)
output
name: arya
name: arya stark
You can specify the data type of a variable using casting. This is specifically important if you are using user provided inputs.
age = int(input_age)
age = int(22) # age will be 22
age = str(22) # age will be '22'
age = float(22) # age will be 22.0
In many a cases, it is important to check data type of variable before using in, python provided built in function type()
to check data type.
post by Pravin