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.
Related
This question already has answers here:
How can I limit the user input to only integers in Python
(7 answers)
Closed 9 months ago.
I'm trying to teach myself how to code in Python and this is my first time posting to Stack Overflow, so please excuse any improprieties in this post. But let's get right to it.
I'm trying to use the input command to return an integer. I've done my research, too, so below are my multiple attempts in Python 3.4 and the results that follow:
Attempt #1
guess_row = int(input("Guess Row: "))
I get back the following:
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Guess Row: 2`
Attempt #2
guess_row = float(input("Guess Row: "))
I get back the following:
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: could not convert string to float: "Guess Row: 2""
Attempt #3
try:
guess_row=int(input("Guess Row: "))
except ValueError:
print("Not an integer")
Here, I get back the following:
Guess Row: 2
Not an integer
Although it returns something, I know this is wrong because, for one, the input returns as a string and it also returns the print command.
Point being, I've tried int, float, and try, and so far nothing has worked. Any suggestions? I just want to be able to input an integer and have it returned as one.
Your third attempt is correct - but what is happening to guess_row before/after this code? For example, consider the following:
a = "Hello"
try:
a = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(a))
If you enter a valid number, the final line will print out the value you entered. If not, an exception will be raised (showing the error message in the except block) and a will remain unchanged, so the final line will print "Hello" instead.
You can refine this so that an invalid number will prompt the user to re-enter the value:
a = None
while a is None:
try:
a = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(a))
To illustrate the comments, from 3.4.2 Idle Shell on Windows, python.org (PSF) installer
>>> n = int(input('Guess1: '))
Guess1: 2
>>> n2 = float(input('Guess2: '))
Guess2: 3.1
>>> n, n2
(2, 3.1)
What system are you using and how did you install Python?
However, I noticed something odd. The code works if I run it just by using the traditional run (i.e., the green button) that runs the entire code, rather than trying to execute individuals lines of code by pressing F2. Does anyone know why this may be the case?
This seems to be a problem in Eclipse, from the PyDev FAQ:
Why raw_input() / input() does not work correctly in PyDev?
The eclipse console is not an exact copy of a shell... one of the changes is that when you press in a shell, it may give you a \r, \n or \r\n as an end-line char, depending on your platform. Python does not expect this -- from the docs it says that it will remove the last \n (checked in version 2.4), but, in some platforms that will leave a \r there. This means that the raw_input() should usually be used as raw_input().replace('\r', ''), and input() should be changed for: eval(raw_input().replace('\r', '')).
Also see:
PyDev 3.7.1 in Eclipse 4 — input() prepends prompt string to input variable?,
Unable to provide user input in PyDev console on Eclipse with Jython.
This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
Closed 6 years ago.
I was trying to make a simple Python program which gets a user input through the variable "user_input" and then it determines the variable type through the function "type()." Here is a sample of the code:
user_input = raw_input('Enter something: ')
if type(user_input) == 'int':
print "integer"
elif type(user_input) == 'str':
print "string"
So you see, the code prompts the user to type down something, and if what they type down is an integer, it will print "integer" and if the input is a string type, it will print "string". The code does execute without an error message, but when I type down either a string value or an integer, it prints nothing, no spaces, no messages, N-O-T-H-I-N-G. Here is an example:
>>>
Enter something: hello
>>>
So since it is not working, I have to ask, is it possible for Python to even compare variable types of a user input and then go through an if / else statement?
You have two issues.
Firstly, type returns actual types, not string descriptions of types.
Secondly, the type of the return value of raw_input is always a string.
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.
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?"
Whenever I use input and raw_imput in Python, it gives me an error report. Such as in the simple number guessing game. This is what happens:
>>> import random
>>> number= random.randint(1,100)
>>> guess= input("guess a number. ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'input' is not defined
The same thing happens when I use raw_input. Does anyone know what's going on?
"imput" is not a standard function in Python. Spell it like "input".
You've misspelled input. It should be input and raw_input, not imput and raw_imput.
Note that the meaning and purpose of both input() and raw_input() have changed between Python 2 and Python 3.
Python 2
input() reads keyboard input and parses it as a Python expression (possibly returning a string, number, or something else)
raw_input() reads keyboard input and returns a string (without parsing)
Python 3
input() reads keyboard input and returns a string
raw_input() does not exist
To get similar behaviour in Python 3 as Python 2's input(), use eval(input()).