Date:

Share:

Using raw_input() in Python 3

Related Articles

introduction

Interaction with users is an essential part of many programs. The sites and apps we use every day offer many ways to interact with them, and often allow users to provide their own information in different ways.

For programs that run on the command line, programming languages ​​usually offer a way to ask the user to provide typed input. You can then store the input provided by the user in the code variable and use the program flow. Python has included this functionality for many years.

However, when Python 2 was replaced by Python 3, major changes were made. These included changes to user input functions. This can confuse developers in finding the right method to use for user input in Python command line programs.

In this article we will review how to get user input in Python 2 and Python 3. We will look at what has changed in Python 3 and discuss why these changes have been made.

The raw_input () function in Python 2

Python 2 included the built-in function raw_input(), To reach command prompt users instructions for user input string. This function asks the user to type some text in the command line and returns that text as a string.

The most common way to use this function is to assign its result to a variable, and then perform some operations with this data:

>>> # Python 2
>>> fruit = raw_input()
apples
>>> print(fruit)
apples
>>>

In the third line of the code above, the raw_input () function asks the user to type a value and stores this value as a string in the variable fruit. The main thing to keep in mind is that raw_input () always returns a string, even if the user types other types of values, such as a number:

>>> # Python 2
>>> num = raw_input()
12
>>> num
'12'
>>> type(num)
<type 'str'>

If the user does not receive an instruction that the program is waiting for him to type input, he may think that the program is stuck or has crashed.

God print The statement can be used to inform the user that he must enter a value:

>>> # Python 2
>>> from __future__ import print_function # Access Python 3 print function in Python 2
>>> 
>>> def getInput():
...     print("Enter name of a fruit: ", end="")
...     fruit = raw_input()
...     return fruit
... 
>>> fruit = getInput()
Enter name of a fruit: apple
>>> fruit
'apple'

In the example above, we did this in Python 2 without adding a ‘ n’ (end character) to the printed message, by using print Function from Python 3. This is done by accessing future enhancements through the __future__ library. It writes your message to the user in the print function before the raw_input () function, as shown above.

However, it is actually unnecessary because you can perform this task much more easily with an argument in the raw_input () function in Python 2. This argument is a string displayed to the user to request user input so he is aware they need to enter some data. for example:

>>> # Python 2
>>> fruit = raw_input("Enter name of a fruit: ")
Enter name of a fruit: apples
>>> print(fruit)
apples
>>> 

However, if you have strict formatting requirements for multiple lines of prompt, it can be helpful to use both print statements and the raw_input () argument.

Input () function in Python 2

Python 2 has an additional built-in function to get user input, e input() function. The main difference between raw_input () and input () is the data type of the return value of the functions. The raw_input () function specifically returns the user’s input as a string, while the input () function can literally accept Python and return a variety of Python data types. It can even return the result of a Python code expression (which is one of the reasons it was removed from Python 3 for security reasons).

This may seem confusing at first. But, it is more or less that the input () function can get different types of data, such as integers, lists, dictionaries, etc. depending on the user’s input. Let’s look at an example to better understand it:

>>> # Python 2
>>> a = input("> ")
> 12
>>> type(a)
<type 'int'>
>>> b = input("> ")
> [1, 2, "abc", "xyz"]
>>> b
[1, 2, 'abc', 'xyz']
>>> type(b)
<type 'list'>

When the input () function requests input, if the user types the integer 12, the value 12 is stored as an integer in the variable a. This was converted to a string when using the raw_input () function, as we have seen before. Similarly, a list is stored in a variable b If the user enters it in his verbal python form, including the square brackets. This list can be used as a standard Python list.

>>> # Python 2
>>> b
[1, 2, 'abc', 'xyz']
>>> b[2]
'abc'
>>> 

Allowing users to enter arbitrary data structures may seem useful at first glance, but it has major issues and has been removed in Python 3. Let’s see why …

Why was the original input removed from Python?

First, we need to clarify that the input () function in Python 2 is completely different from the input () function in Python 3. As mentioned earlier, Python 2 also included raw_input () (which always converted user input to string datatype) and input ( ) Who received the type of data provided by the user.

Python 3, input() Is the only option that exists, but in a bit confusing way, it behaves like the raw_input () from Python 2 – that is – it converts all user input to the datatype string.

The main reason why the original functionality of the input () function was removed in Python 3 is for security reasons. The input () function from Python 2 actually allowed the user to execute raw code, giving the user the power to manipulate the code and the internal operation of a program.

For example, in Python 2, a user can perform a function from the input command ():

>>> # Python 2
>>> def func(x):
...     return x + 1
... 
>>> a = input("> ")
> func(1)
>>> print(a)
2
>>> 

Giving so much power to a user can be dangerous, and can be used with malicious intent, so it was removed in Python 3.

Input () function in Python 3

God input() The function in Python 3 is exactly the same as raw_input () in Python 2, only with a different name. You can use the input () function in Python 3 in the same way as raw_input () from Python 2:

>>> # Python 3
>>> a = input("Enter a fruit: ")
Enter a fruit: orange
>>> a
'orange'
>>> num = input("Enter a number: ")
Enter a number: 15
>>> num
'15'
>>>

Here you can see that input () always returns a string in Python 3 and gets a string (prompt) argument in the same way as raw_input ().

Multi-line user input

The input () function of Python 3 (and raw_input () of Python 2) can store only one row of user input at a time. Uses b n Character (end line) in input guidance also does not work:

>>> # Python 3
>>> twoLines = input("> ")
> line onen line two
>>> print(twoLines)
line onen line two
>>> twoLines
'line one\n line two'
>>> 

And it is also wrong to assume that the user knows what e n Character is. But with a simple while loop, we can create an intuitive prompt for a multi-line user:

>>> # Python 3
>>> allLines = []
>>> print("Type some multi-line input (type END when done):n")
>>> while True:
...     line = input("> ")
...     if line == "END":
...             break
...     else:
...             allLines.append(line)
... 
Type some multi-line input (type END when done):

> This is my first line
> This is my second line
> This is my third line
> This is my last line
> END
>>>

Here, you first create a list allLines To store all user lines. Next, you need to set up an infinite intra-loop, which asks the user to input repeatedly and stores the input in allLines list. The loop will end when the user enters the text “END”. It is also advisable to inform the user how to complete the user request through a print message.

Next, you need to format the user input correctly:

>>> # Python 3
>>> allLines
['This is my first line', 'This is my second line', 'This is my third line', 'This is my last line']
>>> userInput = "n".join(allLines)
>>> print(userInput)
This is my first line
This is my second line
This is my third line
This is my last line
>>> 

You can then join the rows at allLines List with e .join String method as shown above. This will allow you to store the multi-line user input in one variable.

Summary

In this article, we discussed the various functions that you can use in Python to get user input from the command line.

First, you’ve seen how to use the input functions that use Python 2: raw_input () and input (). Then you saw why the functionality of the input () function in Python 2 was removed in Python 3. Then, you saw how to use the input () function in Python 3, which is the same as raw_input () from Python 2. Finally. , You saw how you can get and format multi-line user input with a while loop.

Next steps

If you are interested in learning more about the basics of coding, programming, and software development, see the Developer Coding Basics Guide, where we cover the essential languages, concepts, and tools you will need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, please feel free to contact jacob@initialcommit.io.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles