Skip to content

Python input number | Example code

  • by

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

Convert input number example in Python

A simple example code is the input() function parses user input as a string even if it contains 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

You can use a similar approach if you want to input a floating-point number:

num = float(input("Enter a number: "))
print("The number you entered is:", num)

In this case, the float() function is used to convert the input into a float.

Keep in mind that if the user enters something that cannot be converted into a number (e.g., a string or a character), a ValueError will occur. To handle such cases, you can use exception handling using a try-except block.

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading