Python input number | Example code

To take input as a number in Python, Simple use the input() function to get input from the user and convert it into a number type.

Convert input number example in Python

Simple example code the input() function parse user input as a string even if it contains an only number.

inp = int(input("Enter a Number: "))

print(inp)

Output: If the user inputs non-numeric data, ValueError is raised.

Python input number

The following code keeps on asking for user input till an integer number is given. Using exception handling technique.

while True:
    try:
        data = int(input("Enter a Number: "))
        print("You entered: ", data)
        break;
    except ValueError:
        print("Invalid input")

Output:

Enter a Number: Hello
Invalid input
Enter a Number: 1
You entered: 1

Do comment if you have any doubts or suggestions on this Python input topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

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