Input() function in Python

Input() function is one of the most popular function for accepting inputs from keyboard.

Accepting input from keyboard and assigning to variable str

>> str = input()
This is Python
>>> type(str)
<class ‘str’>

In the above code, we have use input() function to accept values from keyboard and stored in str variable and then using type() function to determine the type value stored in str variable. input() function always returns string values unless we specify to accept  int or float values. Below is the one more example. str variable accepting numbers but type() function returns string.

>> str = input()
12345676
>>> type(str)
<class ‘str’>

We can also provide message to user informing what to enter.

>> fname = input(‘Please enter your first name’)
Please enter your first name
>>> fname = input(‘Please enter your first name: ‘)
Please enter your first name: Rohan
>>> lname = input(‘Please enter your last name: ‘)
Please enter your last name: Jadhav

We can use int() function with input() function to accept integer values.

>> num = int(input(‘Please enter any number: ‘))
Please enter any number: 22

If we enter characters other than numbers, python will give error. Below is the error output

>> num = int(input(‘Please enter any number: ‘))
Please enter any number: sdlkfskd
Traceback (most recent call last):
File “<pyshell#16>”, line 1, in <module>
num = int(input(‘Please enter any number: ‘))
ValueError: invalid literal for int() with base 10: ‘sdlkfskd’

In the same way, float() function can be used with input() function to accept floating numbers.

>> time= float(input(‘Please enter time in hh.mm: ‘))
Please enter time in hh.mm: 12.50

If we don’t provide floating values, python will automatically convert values into float

>> time= float(input(‘Please enter time in hh.mm: ‘))
Please enter time in hh.mm: 12
>>> time
12.0

 

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s