Python input from keyboard

How to Get User Input in Python from Keyboard?

We already know, Programming is all about processing data. To process the data program needs information as input. It can come in many ways.

  • input from the database
  • information from external resources like machine/device/website
  • by typing on the keyboard
  • hovering or clicking by mouse

In this post, we are only interested in getting keyboard input from the user.

Here in this post, we check out, how to receive input from the keyboard. And what is the difference between ‘raw_input()’ and input() function?

Python 2: Getting command line input using ‘raw_input()’

There is function raw_input(). The name itself depicts as it read raw data. It read user data as a string. It does not have the intelligence to interpret the type of data; the user has entered.

name = raw_input('Enter your keyboard input:')

All the data until you press the return key, will be read by this function.

By default, raw_input reads the input data and gives it in the form of a string.

Note: It is an in-built function, so you don’t need to import any external library.

Python 3: Keyboard input from the user using ‘input()’

It provides in build function ‘input()’ to read the input from the user.

name = input("What's your Good name? ")

Function input() reads the data from the user as a string and interprets data according to the type of data entered by the user.

If the user enters an integer/float value, Python reads it as an integer/float, unlike the raw_input() function from Python 2.

Note: You can also use input() method in Python 2. If you use the input() function in Python 2, it always read the data as a string and you have to convert it according to your need.

Let’s start exploring it further.

Difference between input and raw_input function

If you want to get input as integer or float in Python 2, you need to convert data into int or float after reading data using raw_input().

mode=int(raw_input('How old are you?:'))

As we are taking input from the user, we can not ensure if the given user input value type is a numeric data type (float or int) or not.

So it is good practice to catch the error using try and except.

try: mode=int(raw_input('Keyboard Input:')) except ValueError: print("This is not a number.")

Another way is you can check the data type of the input using isdigit() .

mode = raw_input('Keyboard Input:') if(mode.isdigit()): print("Number is an integer.") else: print("Number is not an integer.")

Handling error is good practice to prevent the code from crashing at runtime.

Читайте также:  Horizontal scroll style css

How to Get User Input in Python for Both Python versions?

But now real confusion starts from here.

What about if you do not know the python version to whom you are going to run your code? Or do you want the code to run on both Python versions?

It’s simple. Just check the version of the python and then put the if-else statement to distinguish the Python input function as per the Python version.

Suppose if you are running code on Python 2.x, it should use the raw_input() function to read user value. If the same is going to run on Python 3.x environment, it should use the input() function.

So the first task is to find the Python version number.

To get the Python version, you need to import sys module.

Use the following code snippet to read user input for both Python versions.

from sys import version_info python_3 = version_info[0] #creates Boolean value #for a test that Python major version if python_3==3: response = input("Please enter your Good Name: ") else: response = raw_input("Please enter your Good Name: ")
  • Python 2.x has raw_input() function to get keyboard input. Likewise, Python 3.x has function input().
  • The input() the function has more intelligence to interpret the user input datatype than raw_input() function.
  • You can use the input() in both Python 2 and Python 3 versions.
  • The input() function in Python 2 takes every input as a string. Whereas same function in Python 3, convert the input into the appropriate data type.
  • If you want your code to work on both Python versions, use condition by checking its python version.

Hope you got the solution, how to Get User Input in Python for both Python 2 and Python 3 version. If you have any questions, feel free to ask me in a comment.

Источник

Get User Input from Keyboard — input() function

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.

Syntax of input() function

The syntax of the input() function is:

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.

Читайте также:  Angular and bootstrap javascript

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.

keyboard input from user

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}«)

formatted strings, f-strings

  • 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.

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)
classstr‘>
>>> type(city)
classstr‘>
>>>

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)
classint‘>
>>> type(y)
classfloat‘>
>>>

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:

# get text input
inputText = input(«What is x?»)

# convert text to number
x = int(inputText)

Get integer user input on a single line:

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}«)

user input integer

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

Читайте также:  Typing python dict keys

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

user input choice

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.

# Old Python 2.x, deprecated
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.

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.

Источник

Оцените статью