CBSE Class 11: Python Fundamentals 5

Input function

Up till now, our programs were static. The value of variables was defined or hardcoded into the source code.
To allow flexibility we might want to take the input from the user. In Python, we have the input() function to allow this. The syntax for input() is

Syntax:
input([prompt])

variable=input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

Example:
(using double quotes)

a=input("Enter any no ")
print("a = ",a)

output:

Enter any no 10
a =  10
>>> 

Example:
(using single quotes)

a=input('Enter any no ')
print('a = ',a)

Output:

Enter any no 25
a =  25

Example:
Note: no message is displayed in input(), but message is displayed before input using print().

print("Enter any no ")
a=input()
print("a= ",a)

output:

Enter any no
25
a = 25

Very Important

Example:
When we take input for a number as given below:
>>> a=input(“Enter any no “)
It by default takes input for a string(text).

Note: We can use type() to find the data type of the value/variable.

>>> a=input(“Enter any no “)

>>> a=input("Enter any no ")

Output:

Enter any no 10
>>> a
'10'
>>> print(type(a))
<class 'str'>

When we display the value of “a” it is displayed in the form of a string
If we want to take input for a number in the numeric form we should use:

>>> a=int(input("Enter any no "))
Enter any no 10
>>> a
10
>>> print(type(a))
<class 'int'>
>>> 

Or for float values
>>> a=float(input(“Enter any no “))

>>> a=float(input("Enter any no "))
Enter any no 23.45
>>> a
23.45
>>> print(type(a))
<class 'float'>
>>> 

Example:
#sum of 2 nos (int)

a=float(input("Enter 1st no "))
b=float(input("Enter 2nd no "))
c=a+b
print("Sum = ",c)

Output:

Enter 1st no 10
Enter 2nd no 20
Sum =  30

Example:
#sum of 2 nos (float)

a=float(input("Enter 1st no "))
b=float(input("Enter 2nd no "))
c=a+b
print("Sum = ",c)

Output:

Enter 1st no 2.3
Enter 2nd no 63.325
Sum =  65.625
>>>

Number Of Visitors

0238229