input() function in python

Spread the love

To accept input from keyboard, Python provides the input() function. This function takes a value from the keyboard and return it as a string.

Let’s say you are writing a program and you need to know the user name. You can ask for user name using the input() function.

In [1]: name = input("Enter your name: ") # this will wait till we enter the name

Enter your name: Life With Data

In [2]: print(name)
Life With Data

When asking for numbers, we need to do type casting as the input() function only accepts string.

In [3]: num_str = input("Enter a number: ")

Enter a number: 5

In [4]: num = int(num_str)

In [5]: print(num)
5

This can also be written as

In [6]: num = int(input("Enter a number: "))

Enter a number: 5

In [7]: print(num)
5

similarly to accept a float value, we can use the float() function along with the input() function.

In [8]: num = float(input("Enter a number: "))

Enter a number: 12.50

In [9]: print(num)
12.5

Let’s write a python program that adds does addition of two numbers. We will ask the user to provide two values, then do the addition and display the result to the user.

print("A program for adding two numbers.")
a = int(input("Enter the 1st number: "))
b = int(input("Enter the 2nd number: "))
# add both the numbers
c = a + b
# display the result
print("The result of addition is =", c)5
A program for adding two numbers.

Enter the 1st number: 5

Enter the 2nd number: 10
The result of addition is = 15

Rating: 1 out of 5.

Leave a Reply