How do you read numbers in python?

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?
  • Solution 1: Numerical Inputs in Python 3.x
    • Reading a User Input as an Integer Value
    • Reading a User Input as a Decimal Value [Float]
  • Solution 2: Numerical Inputs in Python 2.x
  • Interactive Example in Your Browser
  • Conclusion
  • Where to Go From Here?

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: 5
The 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: 1111
Decimal equivalent:  15
Enter an octal number: 17
Decimal equivalent:  15
Enter a binary number: F
binary 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.25
The data-type of variable a is:  
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+100
200

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!

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

How does Python read numeric inputs?

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']] .

How do numbers work in Python?

Variables of numeric types are created when you assign a value to them:.
x = 1 # int. y = 2.8 # float. ... .
print[type[x]] print[type[y]] ... .
Integers: x = 1. ... .
Floats: x = 1.10. ... .
Floats: x = 35e3. ... .
Complex: x = 3+5j. ... .
Convert from one type to another: x = 1 # int. ... .
Import the random module, and display a random number between 1 and 9:.

How do you input real numbers in Python?

As we know that Python's built-in input[] function always returns a str[string] class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int[] function.

Chủ Đề