Input number from keyboard python

Get user input with Python using the input[] function. The user can enter keyboard input in the console. In this article you’ll learn how to get keyboard input.

Old versions of Python used the now deprecated raw_input[] function.

The goals of this article are:

  • Learn how to take input from a user and system In Python.
  • Accept any type of keyboard input from the user [integer, float and string]
  • Learn fancier output formatting.

Related Course: Complete Python Programming Course & Exercises

Syntax of input[] function

The syntax of the input[] function is:

input["Your name: "]

As parameter it takes a string, that is printed in the terminal.
This is an optional parameter, sometimes called prompt.

The parameter is a text printed to the screen. If we speak about text we say string.

You can print information to the user, i.e. what value they should enter.

The input[] function:

  • Use the input[] function to get Python user input from keyboard
  • Press the enter key after entering the value.
  • The program waits for user input indefinetly, there is no timeout.
  • The input function returns a string, that you can store in a variable
  • Terminate with Ctrl-D [Unix] or Ctrl-Z+Return [Windows]

Get User Input in Python

Here is a simple example that gets user input and prints it in the terminal.

name = input["Enter a name: "]
print[name]

The input[] function gets user input [keyboard] and stores it into variable name.

Here name is a variable. The print[] function shows it to the screen.

The user must press the enter key in the command line. Then the entered string is send to your application.

So, to get a text value you can use the function input[] which takes as input a string to be printed.

Note: don’t forget to assign the input to a variable, var = input[].

You can use fancy output named formatted strings or f-strings.
To do that, put an f before the string and use curly brackets to output your variable:

name = input["Enter your name: "]
print[f"Your name is {name}"]

In summary:

  • The function input[] returns a string. This can be stored in a variable [name]
  • The variable is then shown to the screen using the print[] function.
  • By using formatted strings [the f in front], you can mix variables with text

You can now give keyboard input, it will be stored in the variable name.

Related Course: Complete Python Programming Course & Exercises

Return type

Any value you enter to input[] is stored as a string str.
You can confirm this by calling type[]

See the example below in the Python shell:

>>> name = input["Enter name: "]
Enter name: Alice
>>> city = input["Enter city: "]
Enter city: Wellington
>>> type[name]

>>> type[city]

>>>

Numbers do not have the type str. So they need to be explicitly converted to a numeric type like int or float. You can check the type of numeric variables too:

>>> x = 3
>>> y = 2.5
>>> type[x]

>>> type[y]

>>>

How to get an Integer as the User Input?

If you call the input[] function, it returns plain text [string]. So if you want to use integers, you have to convert the string to an int.

To get an integer [whole number], you can do this:


inputText = input["What is x?"]


x = int[inputText]

Get integer user input on a single line:

x = int[input["What is x? "]]

You can get multiple variables from the user, and use them in your program.
The program below gets variable x and variable y, and then sums and outputs them.

x = int[input["Enter x: "]]
y = int[input["Enter y: "]]

sum = x + y
print[f"Addition of {x} and {y} is {sum}"]

Take into account that if the user doesn’t actually enter an integer, this code will throw an exception.

>>> x = int[input["What is x? "]]
What is x? a
Traceback [most recent call last]:
File "", line 1, in
ValueError: invalid literal for int[] with base 10: 'a'
>>>

So make sure to enter a number. If you want to prevent exceptions, see the section below Input Exception Handling.

Read input as float

To get a number [non-integer], like a floating point number, you can call the float[] method to convert the string.

A float [floating point] is a number like 1.5, 3.123, 1.75, 1.01 etc.

x = float[input["Write a number"]]

The input must be a floating point, any other input will throw an exception. See Input Exception Handling.

Python user input and EOFError Example

The program can have an EOFError. This exception is raised if the input[] function did not read any data.
This will not be thrown by a simple enter key, but by interrupting the program with Ctrl+D.

If you have a program like this:

val = input["Enter a value: "]
print[f"You entered {val}"]

You can interrupt the program by pressing Ctlr+D [EOF]. That raises an EOFError and terminates the script.

$ python3 example.py
Enter a value: Traceback [most recent call last]:
File "example.py", line 1, in
val = input["Enter a value: "]
EOFError

Python User Input Choice Example

You can build a multiple choice input system.
First get the keyboard input by calling the input[] function.

Then you can evaluate the choice by using the if-elif-else structure.

Note: The == symbol tests for equality. Python is case-sensitive.

choice = input["Enter A, B or C: "]

if choice == 'A':
print["You chose A"]
elif choice == 'B':
print["You chose B"]
elif choice == 'C':
print["You chose C"]
else:
print["Invalid choice"]

It’s important to use 4 spaces with every indent, not tabs and not a different amount of spaces.

Input Exception Handling

If the user enters invalid input or invalid input, Python can throw an exception. To handle this, you can use the code below:

x = 0
try:
x = int[input["What is x? "]]
except:
print["Invalid number."]

raw_input[] - old versions

In Python 3 and newer you can use the input[] function.
Older versions of Python used the raw_input[] function.


name = raw_input["Enter name: "]

The difference between this functions is zero, only the version name. While it’s the same functionality but you should use the input[] function.

So instead:

name = input["Enter name: "]

The raw_input[] function has been deprecated and removed from Python 3.
If you are still on a Python 2.x version, you should upgrade now.

Conclusion

You can take user input with the input[] function. This waits for keyboard input indefinetly. If you add a parameter, it will print that text before the user input.

You also saw how to handle invalid input and know about the difference between Python 2 and Python 3 [and newer].

If you are new to Python, I recommend the course below.

Related Course: Complete Python Programming Course & Exercises

Download exercises

How do you input inputs in Python?

join[...] creates a new string that you do nothing with, if you want to change the Name variable to the result of Name. join[...] then do Name = Name. join[input["..."]] but I imagine you will be surprised with the result.

How do you take input as numbers?

Use the following attributes to specify restrictions:.
max - specifies the maximum value allowed..
min - specifies the minimum value allowed..
step - specifies the legal number intervals..
value - Specifies the default value..

Chủ Đề