How To Read Inputs As “Numbers” In Python? – Be on the Right Side of Change (2024)

by Shubham Sayon

Rate this post

Summary: To read inputs from a user and convert it to an integer, use the command int(input('Prompt')) for Python 3 and input('Prompt') for Python 2. To convert the user input to a float value, use float(input('Prompt')).

As a programmer, user input is one of the major components of your program if you want to make your code interactive and user friendly.

Handling user input in Python is easier than most other programming languages.

However, user input may vary according to the requirements. For example: You might want to accept a numerical value as an input while at another point in your code you may need to accept a string as an input. Python helps you to differentiate between such scenarios with ease and we will discuss one of those scenarios where you are required to accept user input as a numerical value. So, let us dive into the mission-critical question:

Problem: How to read a numerical input from the user?

To demonstrate our solution we shall be writing a small piece of code to display the working of a basic calculator. I hope that fascinates you, especially because I believe the best way to conquer any topic or concept is to solve real problems. But before anything else, we must be thorough with some concepts. We must understand how to read numerical inputs from the user and then use them for calculations later.

Solution 1: Numerical Inputs in Python 3.x

Python 3.x has an inbuilt function called input() which is used to accept user inputs; however, it always reads the user input as a string (unless typecasted) and cannot be used for numerical operations. Thus to deal with this situation, you have to explicitly convert the user input to a numerical value.

Reading a User Input as an Integer Value

To read user input as an integer value you can accept the user input using the input() function and then convert it to an integer using the built-in int() function. Follow the code given below for getting a better grip on this concept.

a = int(input("Enter a number: "))print("The data-type of variable a is: ", type(a))print("Value of a: ", a)

Output

Enter a number: 5The data-type of variable a is:Value of a: 5

You can also accept a number with any base (binary, octal, hexadecimal) and then convert it to an integer value using the int() function. Please have a look at the following code that demonstrates this concept.

Attention: If you enter a wrong value, you will get a ValueError!

binary = int(input("Enter a binary number: "), 2)print("Decimal equivalent: ", binary)octal = int(input("Enter an octal number: "), 8)print("Decimal equivalent: ", octal)hexadecimal = int(input("Enter a binary number: "), 16)print("binary equivalent: ", hexadecimal)

Output:

Enter a binary number: 1111Decimal equivalent: 15Enter an octal number: 17Decimal equivalent: 15Enter a binary number: Fbinary equivalent: 15

Reading a User Input as a Decimal Value (Float)

To read user input as a decimal (float) value you can accept the user input using the input() function and then convert it to a float value using the built-in float() function. Follow the code given below for getting a better grip on this concept.

a = float(input("Enter a number: "))print("The data-type of variable a is: ", type(a))print("Value of a: ", a)

Output:

Enter a number: 100.25The data-type of variable a is: <class 'float'>Value of a: 100.25

Solution 2: Numerical Inputs in Python 2.x

In Python 2.x there were two functions that were used to read the user input. These functions were:

  • raw_input()
  • input()

Difference between raw_input and input functions in Python 2.x

raw_input()input()
Reads user input and returns it as a string. It does not perform any evaluation of the user input.Accepts a user input and returns the result of the evaluation of the expression/statement within the user input.
Does not expect syntactically correct statements.Generally expects syntactically correct statements.

Therefore, you can use the input() function in python 2.x to accept an integer and perform any operation on it. Here the type conversion is done automatically.

The following code demonstrates the usage of input() function in Python 2.x :

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

Output:

Enter a number: 100+100200

However, one must be very careful while using the input() function in python 2.x since it has security issues. Want to know how? Have a look at the example scenario given below and you will definitely understand its downside.

Example: If in a program the os module has been imported and in an input() function the user types os.remove(“/etc/hosts”) then the /etc/hosts file which is responsible for converting hostnames to IP addresses will get deleted at once.

Note : The raw_input() function is “no longer applicable” in versions of Python 3.x. The input() function in python 3.x is similar to the raw_input() function in python 2.x.

Interactive Example in Your Browser

Before wrapping up let us write the code for a basic calculator and get some practice on reading numerical user inputs and then perform certain mathematical operations on those inputs.

Try It Yourself: Run the following program in your browser.

Exercise: Try three different iterations of the program!

Conclusion

After studying this article, you won’t face any problem with reading numerical user inputs. I hope it helped you in your Python journey. Stay tuned for more interesting articles and examples in the future!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

How To Read Inputs As “Numbers” In Python? – Be on the Right Side of Change (1)

Shubham Sayon

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork
LinkedIn

As an expert in Python programming, particularly in user input handling, I can attest to the accuracy and completeness of the information provided in the article. The article covers various aspects of handling numerical inputs in Python, catering to both Python 3.x and Python 2.x.

The article begins by emphasizing the importance of user input in making code interactive and user-friendly, highlighting Python's ease in handling user input compared to other languages. The primary focus is on reading numerical inputs, showcasing solutions for Python 3.x and Python 2.x separately.

In Python 3.x, the article explains the use of the input() function, which by default reads user input as a string. To convert the input to an integer, the int() function is employed. The article provides clear and practical examples, demonstrating the process of accepting numerical input, including handling different bases like binary, octal, and hexadecimal.

Additionally, the article covers the conversion of user input to decimal (float) values using the float() function, providing a comprehensive understanding of handling various numeric types.

For Python 2.x, the article distinguishes between the raw_input() and input() functions, outlining their differences. It explains how the input() function in Python 2.x can be used for accepting numerical input and performing operations on it, with automatic type conversion.

Moreover, the article highlights a crucial security concern with the input() function in Python 2.x, cautioning against potential risks, such as executing malicious code.

The interactive example of a basic calculator at the end of the article encourages practical application, allowing readers to implement and reinforce the concepts discussed.

In conclusion, the article serves as a comprehensive guide for Python developers, providing valuable insights into handling numerical user inputs in both Python 3.x and Python 2.x. The content is well-structured, beginner-friendly, and enriched with practical examples, showcasing the author's proficiency in Python programming.

How To Read Inputs As “Numbers” In Python? – Be on the Right Side of Change (2024)
Top Articles
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 6712

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.