Python raw_input() function with Example


Python raw_input() function is used to take input string from user in Python 2.x. It returns the input string by striping trailing newline. In Python 3.x raw_input() method renamed to input() method.

Basic Syntax

Following is the basic syntax for raw_input() function:

In Python 2.x:

raw_input()

You can use the raw_input() function as:

age = raw_input("Enter your age : ")
print 'your age is ', age

In Python 3.x:

input()

You can use the input() function as:

age = input("Enter your age : ")
print 'your age is ', age

Return Value

raw_input() function in Python 2.x or input() function in Python 3.x returns the input string taken from user’s input.

Example

Following are the examples for raw_input() and input() functions:

Example 1 : Python 2.x, raw_input() function

import math

print "Program for calculating the area of circle and square."

length = raw_input("Enter the length of the square: ")
area_of_square = length**2
print "Area of the square is: ", area_of_square

radius = raw_input("Enter the radius of the circle: ")
area_of_circle = (radius**2) * math.pi
print "Area of the circle is: ", area_of_circle

The output for the above program is as given below:

Program for calculating the area of circle and square.Enter the length of the square: 10
Area of the square is: 100

Enter the radius of the circle: 10
Area of the circle is: 314.159265359

Example 2 : Python 3.x, input() function

import math

print "Program for calculating the area of circle and square."

length = input("Enter the length of the square: ")
area_of_square = length**2
print "Area of the square is: ", area_of_square

radius = input("Enter the radius of the circle: ")
area_of_circle = (radius**2) * math.pi
print "Area of the circle is: ", area_of_circle

The output for the above program is as given below:

Program for calculating the area of circle and square.Enter the length of the square: 10
Area of the square is: 100

Enter the radius of the circle: 10
Area of the circle is: 314.159265359