How To Read Python Input As Number

How To Read Python Input As Number

Python's input() function reads any input as a string by default. Therefore you need to manually convert it to the actual data type you'd like to use. Here is how to read input as an integer:

number = int(input("Enter a number:"))
print(number)

Pretty simple, right? All we did is to wrap the usual input() function in the int() constructor. Running this command will prompt us with the message "Enter a number:". After the user inputs a number, input() will read it as a string, and the int() will convert that string to a base-10 integer. In the end, we'll have the integer value of the input stored in the number variable:

>>> number = int(input("Enter a number:"))
Enter a number:6
>>> print(number)
6

Alternatively, you can also read different base numbers by passing one additional argument into the int() constructor:

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

number = int(input("Enter a number:"), 2)

This will read a base-2 value from the input, convert it to the base-10 number and assign that value to the number variable.

Additionally, you can read float numbers in the same manner as previously shown:

number = float(input("Enter a number:"))

Advice: For more in-depth overview of how to get the user input in Python, read our "Getting User Input in Python" article.

Last Updated: July 22nd, 2022
Was this helpful?
Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

Ā© 2013-2023 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms