Variables and Datatypes

Variables and Datatypes


In the last chapter, we left with an error in python. Type the below code and check

print("Hi" + 10)

Typeerror means python cannot add a number and a string. In python, the variables are assigned dynamically. Use the below code to check.

print("Hi " + str(10))

Here, the number '10' is converted as string.


Now, we will get input from user and store it in a variable.

a = input("Enter a number: ")

The command input('text to be displayed') is used to get data from the user. The value entered inside the brackets will be displayed in the user screen when you run the program.

Lets try to multiply the number by 5

print(a*5)

You could see that the result is not the multiplication of the number by 5 rather the number gets printed 5 times. It happens because python input function always consider input as string. So, if we want to to get an integer input then we need to explicitly specify it in code.


Now, lets try to get a number input

a = int(input("Enter a number: "))
print(a*5)

Now, we get the expected output.



Now, lets try to format the output.

a = int(input("Enter a number: "))
print("The number multiplied by 5 is %d" %(a*5))

Lets write a program to find the area of rectange.

length = float(input("Enter the length: "))
breadth = float(input("Enter the breadth: "))
area = length * breath
print("The area of the rectange is %.2f" %(area))

Note that here we use float since the input can be floating point type. In the same way we need to print the area value containing only 2 digits after the decimal point.


We will find the area of a circle by importing a library.

import math
radius = float("Enter the radius of the circle: ")
area = math.pi * radius * radius
print("Area of the circle with a radius of %.2f is .2f" %(radius, area))

Here we import a library called math. 'math' library is predefined in python and has lot of functions. One such function is pi which we used in the above program. To use the function we need to write the library name followed by a dot and the function name(ie. math.pi). To learn more about the available functions in the library click here.


Let us understand the different datatypes available in python.

print(10)
type(10)

type(value) is used to identify the type of the variable. Here '10' is of integer type.


Try the same for float and string.

type(10.5)
type("Hello")

There are more datatypes in python which will be discussed as the course progresses.