raw_input function in Python - python

What is the raw_input function? Is it a user interface? When do we use it?

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

raw_input() was renamed to input() in Python 3.
From http://docs.python.org/dev/py3k/whatsnew/3.0.html

raw_input is a form of input that takes the argument in the form of a string whereas the input function takes the value depending upon your input.
Say, a=input(5) returns a as an integer with value 5 whereas
a=raw_input(5) returns a as a string of "5"

The "input" function converts the input you enter as if it were python code. "raw_input" doesn't convert the input and takes the input as it is given. Its advisable to use raw_input for everything.
Usage:
>>a = raw_input()
>>5
>>a
>>'5'

The raw_input() function reads a line from input (i.e. the user) and returns a string
Python v3.x as raw_input() was renamed to input()
PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).
Ref: Docs Python 3

Another example method, to mix the prompt using print, if you need to make your code simpler.
Format:-
x = raw_input () -- This will return the user input as a string
x= int(raw_input()) -- Gets the input number as a string from raw_input() and then converts it to an integer using int().
print '\nWhat\'s your name ?',
name = raw_input('--> ')
print '\nHow old are you, %s?' % name,
age = int(raw_input())
print '\nHow tall are you (in cms), %s?' % name,
height = int(raw_input())
print '\nHow much do you weigh (in kgs), %s?' % name,
weight = int(raw_input())
print '\nSo, %s is %d years old, %d cms tall and weighs %d kgs.\n' %(
name, age, height, weight)

If I let raw_input like that, no Josh or anything else.
It's a variable,I think,but I don't understand her roll :-(
The raw_input function prompts you for input and
returns that as a string. This certainly worked for
me. You don't need idle. Just open a "DOS prompt"
and run the program.
This is what it looked like for me:
C:\temp>type test.py
print "Halt!"
s = raw_input("Who Goes there? ")
print "You may pass,", s
C:\temp>python test.py
Halt!
Who Goes there? Magnus
You may pass, Magnus
I types my name and pressed [Enter] after the program
had printed "Who Goes there?"

Related

Python get input from user - error "name not defined" [duplicate]

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 1 year ago.
I am fairly new to python. I am trying to get an input from the user running the script. Below is my script:
print("This is the program to test if we can get the user's input")
users_input = input("Please enter your name. Please note that it should be a single word >>> ")
print("Is this your name? ", users_input)
Going through a few websites, this seems to be enough. But when i run this script and am asked to enter the name, I type the name and as soon as I press enter, I get the below error:
Traceback (most recent call last):
File "test_input.py", line 3, in <module>
users_input = input("Please enter your name. Please note that it should be a single word >>> ")
File "<string>", line 1, in <module>
NameError: name 'John' is not defined
I was expecting it to print the name but rather I get this error. Not sure why.
Use raw_input() instead, since you're using Python 2.7.
raw_input gets the input as text (i.e. the characters that are typed), but it makes no attempt to translate them to anything else; i.e. it always returns a string.
input gets the input value as text, but then attempts to automatically convert the value into a sensible data type; so if the user types ‘1’ then Python 2 input will return the integer 1, and if the user types ‘2.3’ then Python 2 input will return a floating point number approximately equal to 2.3
input is generally considered unsafe; it is always far better for the developer to make decisions about how the data is interpreted/converted, rather than have some magic happen which the developer has zero control over.
It is the reason why that automatic conversion has been dropped in Python 3 - essentially; - raw_input in Python 2 has been renamed to input in Python 3; and there is no equivalent to the Python 2 input magic type conversion functionality.
Use raw_input() instead of input, check this page for more info
print("Is this your name? ", users_input) is not how you concatenate a literal string and a variable.
print("Is this your name? " + users_input) is probably what you are trying to do.
Python provides us with two inbuilt functions to read the input from the keyboard.
1 . raw_input ( prompt )
2 . input ( prompt )
raw_input ( ) : This function works in older version (like Python 2.x). This function takes exactly what is typed from the keyboard, convert it to string and then return it to the variable in which we want to store. For example –
g = raw_input("Enter your name : ")
print g
Output :
Enter your name : John Wick
John Wick
g is a variable which will get the string value, typed by user during the execution of program. Typing of data for the raw_input() function is terminated by enter key. We can use raw_input() to enter numeric data also. In that case we use typecasting.
input ( ) : This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list. If the input provided is not correct then either syntax error or exception is raised by python. For example –
val = input("Enter your value: ")
print(val)
Output :
Enter your value: 345
345
When input() function executes program flow will be stopped until the user has given an input. The text or message display on the output screen to ask a user to enter input value is optional i.e. the prompt, will be printed on the screen is optional. A notable thing is that whatever you enter as input, input function convert it into a string.

Take input without changing the line

print("Please Enter:")
x = input()
print(x)
In the console after "Please Enter:" is printed the line changes. I want that I should be able to provide input in the same line of "Please Enter:". Is there any method to prevent the change of line?
Instead of print(), use input() to produce the prompt:
x = input("Please Enter: ")
From the input() function documentation:
input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline.

Print type(example) always returns string

UserInput = raw_input('Enter something: ')
print type(UserInput)
print (UserInput)
This is a very simple piece of code that is supposed to tell me what type the enter input is. e.g int or bool. For some reason It always come up as string. Lets say I enter "1" (no quotes) when I am prompted to "Enter Something". That should return as type int. The problem I think lies in the fact that UserInput is a string "raw_input('Enter something: ')". How do I fix my script to return the type the input that the user gave me? I am using python 2.7
The raw_input() function always returns a string, it is documented as such:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Emphasis mine.
Perhaps you were looking for input() instead? It evaluates the input given as a Python expression and is the equivalent of eval(raw_input()):
Equivalent to eval(raw_input(prompt)).
This function does not catch user errors. If the input is not
syntactically valid, a SyntaxError will be raised. Other exceptions
may be raised if there is an error during evaluation.
If you entered 1, it'd be interpreted as an integer literal and type(UserInput) would print <type 'int'>.
You are missing a bracket here in the second line. To solve the problem try this:
UserInput = raw_input('Enter something: ')
print(type(UserInput))
print(UserInput)

setting "if" to make sure variable is a number and not a letter/symbol

How do I create an "if" statement to make sure the input variable is a number and not a letter?
radius = input ('What is the radius of the circle? ')
#need if statement here following the input above in case user
#presses a wrong key
Thanks for your help.
Assuming you're using python2.x: I think a better way to do this is to get the input as raw_input. Then you know it's a string:
r = raw_input("enter radius:") #raw_input always returns a string
The python3.x equivalent of the above statement is:
r = input("enter radius:") #input on python3.x always returns a string
Now, construct a float from that (or try to):
try:
radius = float(r)
except ValueError:
print "bad input"
Some further notes on python version compatibility
In python2.x, input(...) is equivalent to eval(raw_input(...)) which means that you never know what you're going to get returned from it -- You could even get a SyntaxError raised inside input!
Warning about using input on python2.x
As a side note, My proposed procedure makes your program safe from all sorts of attacks. Consider how bad a day it would be if a user put in:
__import__('os').remove('some/important/file')
instead of a number when prompted! If you're evaling that previous statement by using input on python2.x, or by using eval explicitly, you've just had some/important/file deleted. Oops.
Try this:
if isinstance(radius, (int, float)):
#do stuff
else:
raise TypeError #or whatever you wanna do

How do I get user input from the keyboard in Python 2? [duplicate]

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 22 days ago.
I wrote a function in Python which prompts the user to give two numbers and adds them.
It also prompts the user to enter a city and prints it. For some reason, when I run it in a shell, I get "name is not defined" after I enter the city.
def func_add(num1, num2):
a = input("your city")
print a
return num1 + num2
If you're on Python 2, you need to use raw_input:
def func_add(num1, num2):
a = raw_input("your city")
print a
return num1 + num2
input causes whatever you type to be evaluated as a Python expression, so you end up with
a = whatever_you_typed
So if there isn't a variable named whatever_you_typed you'll get a NameError.
With raw_input it just saves whatever you type in a string, so you end up with
a = 'whatever_you_typed'
which points a at that string, which is what you want.
input()
executes (actually, evaluates) the expression like it was a code snippet, looking for an object with the name you typed, you should use
raw_input()
This is a security hazard, and since Python 3.x, input() behaves like raw_input(), which has been removed.
you want to use raw_input. input is like eval
You want to use raw_input() instead. input() expects Python, which then gets evaled.
You want raw_input, not input.
input(...)
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
As opposed to...
raw_input(...)
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.
In Python 2.x, input asks for a Python expression (like num1 + 2) which is then evaluated. You want raw_input which allows one to ask for arbitrary strings.

Categories

Resources