Taking Input From Users In Python


Gaming Laptop Series

Computer programs often need to interact with users to get some kind of data from them. Later this data is processed and output is displayed on the console.

For example, a program that calculates summation can ask the user to enter two numbers so that it can perform the addition operation and display the result to the user.

Python 3.x provides an input() function to take input from the user. Another function called raw_input() was used in Python 2. So let’s take how to take input from a user in Python.

Python input() function

Python input() function takes a single optional argument which is a string that is to be written on standard output without trailing a newline. It takes the input and converts it to the string by removing the trailing newline.

Syntax of input()

The syntax of the input() function is given below.

input()

or

input(prompt)

For example –

num1=input("Enter first number: ")
num2= input("Enter second number: ")
# Convert the numbers to integer and add them
sum=int(num1)+int(num2)
print(f"Sum of two number is {sum}")

You can see the output in the given image –

Taking multiple inputs using single input() function

You can take multiple inputs using a single input() function in Python. The following example shows how to take multiple inputs in Python.

num1, num2 = input("Enter two numbers for addition ").split()
sum =int(num1)+int(num2)
print("The sum of two number is ", +sum)

You need to enter two numbers that are separated by space. Now see the output of this program in the given image –

Python raw_input() function

The raw_input() was a function in Python 2.x it is removed from the Python 3.x. The working of this function was similar to the input() function, It takes input exactly what typed by the user and returns it to the variable as a string.

For example –

# Run this code in Python 2
name= raw_input("Enter your name: ")
print name

When a built-in function like input() or raw_input() does not read any data before encountering the end of their input stream, an EOFError is raised.

Conclusion

By using the input() function you can take input from the user. Now if you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.