Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Python input() function

It often happens that the developers/programmers need to accept the input from the user to process further with the application.

Python provides a built-in-method to accept the input from the user.

Python input() function accepts the input from the user. Python’s builtins.py contains the Python input() function.

Syntax:

input(prompt)

The prompt is optional in the input() function. Prompt is basically a String i.e a message displayed before the input.

Whatever string is placed as an argument in the input function, gets printed as it is on the output screen.


1. Working of Python input() function

  • As soon as the interpreter encounters the input() function, it halts/stops the program execution until and unless the user provides an input to the program.
  • The input entered by the user is automatically converted into a String. Whether the user enters an integer or float type data, still the input() functions converts it into a string.
  • Thus, it needs to be explicitly converted to another data type in the program using typecasting.

2. Example 1: Basic working of Python input() function

x = input () 
print("The entered value is:", x)

Output:

10
The entered value is: 10

3. Python input() function with String as an argument

name = input('Enter your name: ')
print("Name of the candidate is:", name)

Output:

Enter your name: Safa Mulani
Name of the candidate is: Safa Mulani

4. Multiply two numbers by accepting input from the user

x = input()

y = input()

z = x * y
print("Result is: ", z)

Output:

Input Function
Python input() Function

The above code snippet results in an error because the python input() function converts the input from the user into a string. Thus, in order to convert it into an integer, we need to explicitly typecast the input provided by the user.

x = input("Enter the number1: ")


y = input("Enter the number2: ")

z = int(x) * int(y)
print("Result is: ", z)

Output:

Enter the number1: 10
Enter the number2: 20
Result is:  200

Conclusion

Thus, in this article, we have understood the working of Python input() function.


References

Leave a Reply

Your email address will not be published. Required fields are marked *