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

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup
Details
Project

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic
Details

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms