By Ankit Sir • DevTeam
In this chapter, we will learn about variables, different data types in Python, rules for naming variables, operators, type conversion, and taking input from the user. This chapter builds the foundation for writing meaningful Python programs.
A variable is a name given to a memory location. It is used to store data values so that they can be reused later. Python automatically identifies the data type of a variable.
a = 71 # a is an integer
b = 88.44 # b is a float
name = "Harry" # name is a string
Python is a dynamically typed language. There is no need to declare the data type explicitly. Python automatically identifies the type of data stored in a variable.
a = 31
type(a) # <class 'int'>
b = "31"
type(b) # <class 'str'>
Valid Variable Names: Ankit, one8, seven, _seven
Invalid Variable Names: 8one ❌, my name ❌, @value ❌
The type() function is used to find the data type of a variable.
x = 10
type(x) # <class 'int'>
Typecasting means converting one data type into another. Python provides built-in functions for type conversion.
str(31) # "31"
int("32") # 32
float(32) # 32.0
Note: "31" is a string literal, while 31 is a numeric literal.
The input() function is used to take input from the user. Input is always taken as a string by default.
a = input("Enter number: ")
If user enters 34 → variable stores "34" (string)
a = int(input("Enter your age: "))
print(a + 5)
b = float(input("Enter price: "))
print(b * 1.18)
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Sum is:", x + y)
If user enters 12 and 8 → Output: Sum is: 20