How to Use Raw_Input in Python 3

How do I use raw_input in Python 3?

Starting with Python 3, raw_input() was renamed to input().

From What’s New In Python 3.0, Builtins section second item.

(python 3) When using raw_input(), why does the function add \n to the input?

In Python3.x, raw_input() and input() are integrated, raw_input() is removed, only the input() function is retained, which receives any input, defaults all input to string processing, and returns the string type.

When use Python2.7:

Sample Image

When use Python3.8:

Sample Image

In addition, if you use extensions for debugging other than the python extension in VS Code, please try to disable it to avoid affecting the results.

My environment:

VS Code: 1.52.1 (user setup);
OS: Windows_NT x64;
VS Code extension: Python; Pylance;

Reference: What's new in Python3.

raw_input function in Python

It presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user and returns the data input by the user in a string. See the docs for raw_input().

Example:

name = raw_input("What is your name? ")
print "Hello, %s." % name

This differs from input() in that the latter tries to interpret the input given by the user; it is usually best to avoid input() and to stick with raw_input() and custom parsing/conversion code.

Note: This is for Python 2.x

how to use a raw_input as argument in a function in python 3

It depends on what you are trying to do. Most likely you want to pass the user input to the function call rather than the definition:

def function(a, b):
print(a, b)

a = input('give me a ')
b = input('give me b ')

function(a, b)

However, if you want to pass a given user input as the default argument to a function, you could do it like this:

def function(a=input('give me a '), b=input('give me b ')):
print(a, b)

function() # prints whatever the user inputted when the file was initially run

The reason your code raises an exception is because the content in the () in a function definition (as opposed to a function call, i.e., function()) is the names of the parameters rather than the arguments passed to the function. You can use input() in this part of the function signature only if you assign it as a default value to be associated with a parameter name, as I did above. This second use case seems pretty strange though, and every time function() is called it will be passed the same arguments as defaults that the user initially entered. Even if that is what you want to do, you should probably do this instead:

input_a = input('give me a ')
input_b = input('give me b ')

def function(a=input_a, b=input_b:
print(a, b)

function()

Alternatively, if you want to get a different pair of inputs every time the function is called (this actually seems most likely now that I think about it):

def function():
a = input('give me a ')
b = input('give me b ')
print(a, b)


Related Topics



Leave a reply



Submit