This question already has answers here:
Receive a string, convert to calculate and display response, but.. Can't split
(2 answers)
Closed 9 years ago.
I am a python newbie.I am getting familiar with loops and tried this example from a book
while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
However the output is as follows
Enter something : ljsdf
Traceback (most recent call last):
File "trial_2.py", line 2, in <module>
s = input('Enter something : ')
File "<string>", line 1, in <module>
NameError: name 'ljsdf' is not defined
You have to use raw_input() instead (Python 2.x), because input() is equivalent to eval(raw_input()), so it parses and evaluates your input as a valid Python expression.
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
Note:
input() doesn't catch user errors (e.g. if user inputs some invalid Python expression). raw_input() can do this, because it converts the input to a string. For futher information, read Python docs.
you want raw_input() in python2
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
input() tries to evaluate (dangerously!) what you give it
Your code will work fine in python 3.x
But if you are using python 2 you will have to input string using raw_input()
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
It seems like you're using Python 2.x, while the code is expected to be run in Python 3.x.
input in Python 2.x evaluates the input string unlike input in Python 3.x.
In Python 2.x input() is designed to return numbers, int or float depending on the input from the user, you can also enter variable names.
you need to use:
raw_input('Enter something: ')
The error is caused because Python thinks that "ljsdf" is the name of a variable, and that's why it raises this exception:
NameError: name 'ljsdf' is not defined
becuase "ljsdf" is not defined as a variable. :D
raw_input() is safer to use, and then convert the input to whatever other type after :D
Related
im wondering why is
File "<string>", line 1
.
^
SyntaxError: unexpected EOF while parsing
coming when i execute following script and including dot in input.
answer = input('enter 1: ')
if answer == 1:
print('nice')
else:
print('please enter "1"')
return
I have been wondering this pretty long, and now im trying to ask here if someone could help me.
So i can't include dots or anything else that basic letters and numbers my input.
I thought there could be easy way to find this thing out.
There is other code i need to fix below, with same error.
email = str(input('required* Your mail: '))
print('your mail is : ' + email)
now, it needs to include dot and at mark.
The code here seems ok, except for the fact you're using return without a function.
And the code wouldn't work when I put I type 1, because you need to cast the var "aswer".
The code should be like this:
answer = int(input('enter 1: '))
if answer == 1:
print('nice')
else:
print('please enter "1"')
You are putting a string and you are checking if is this a number, that is your error, so if you want to ask every time if the answer is wrong you could do this:
while True:
answer = input('enter 1: ')
if answer == "1":
print('nice')
break
else:
print('please enter "1"')
Im writing a program for Uni to find all the palindromic primes, i have written out the program already but when i run it, my first input gets an error while trying to assign values to the variable.
please could someone tell me why this is the case!
start =input("Enter the start point N:")
starteval= eval(start)
endval = eval(input("Enter the end point M:"))
reverse=""
x=starteval+1
while x<endval:
reverse+=start[::-1]
evalreverse=eval(reverse)
if evalreverse==starteval:
if starteval==2 or starteval==3:
print(starteval)
elif starteval%2==0 or starteval%3==0:
pass
i=5
w=2
a=0
while i<=starteval:
if starteval%i==0:
break
else:
a=True
i+=2
if a==True:
print (starteval)
else:
pass
x+=x+1
the ouput i recieve is
"Enter the start point N:200
Enter the end point M:800
Traceback (most recent call last):
File "", line 1, in <module>
start =input("Enter the start point N:")
Syntax Error: 002: <string>, line 1, pos 3"
please and thank you!
Try instead of the first 3 lines to use:
starteval = int(raw_input("Enter the start point N:"))
endval = int(raw_input("Enter the end point M:"))
In Python 3 integer literals cannot begin with a zero:
>>> i = 002
File "<stdin>", line 1
i = 002
^
SyntaxError: invalid token
Because you are applying the eval function to your string input, Python attempts to parse your input as a valid Python expression, whcih is why you see the error you see.
It would make more sense to use int(input(...)) to get the integer (though you would still have to handle any exceptions raised when the user types a non-integer into your code). This has the advantage that it will accept the input that is causing you trouble in eval.
You could write a small intParsing function, that handles simple input parsing for you, then basically replace every "eval()" function of your code with intParsing().
Here is your edited code:
def intParsing(input_str):
str = ""
# Delete all chars, that are no digits (you could use a regex for that too)
for char in input_str.strip():
if char.isdigit():
str += char
# Now you only got digits in your string, cast your string to int now
r = int( str )
print "result of parsing input_str '", input_str, "': ", r
return r
start =raw_input("Enter the start point N:")
starteval= intParsing(start) # I edited this line
end = raw_input("Enter the end point M:") # I edited this line
endval =intParsing(end) # I edited this line
reverse=""
x=starteval+1
while x<endval:
reverse+=start[::-1]
evalreverse= intParsing(reverse) # I edited this line
I'm using python 3.5.1 and running my file through command prompt on windows. The arguments are being passed after the program is run; ie the program prompts for input based on a previously generated list.
I'm looking to read in multiple numbers on the same line separated by spaces. Python 2.X it wouldn't have been an issue with raw_input but this is proving to be a challenge.
selection = list(map(int,input("Enter items to archive (1 2 etc):").split(",")))
If I enter two different numbers on the same line:
Enter items to archive (1 2 etc):29 30 Traceback (most recent call
last): File "G:\Learning\Python\need_to_watch.py", line 15, in
selection = list(map(int,input("Enter items to archive (1 2 etc):").split(","))) File "", line 1
29 30
^ SyntaxError: unexpected EOF while parsing
I gave up on a single line and tried just doing it in a loop but I get a different error
data=[]
while True:
entry = int(input('Item number : '))
data.append(entry)
if entry == 'q':
break
It tries to evaluate 'q' as a variable even though I haven't eval()'d anything.
This question says to just use input().split() but it would appear that this no longer works....
accepting multiple user inputs separated by a space in python and append them to a list
I could try and catch the EOF exception, but that doesn't seem like the right way to do it, nor should it be necessary.
entry = input('Enter items: ')
entry = entry.split()
entry = list(map(int, entry))
print(entry)
Or more concisely:
entry = list(map(int, input('Enter items: ').split()))
print(entry)
If you want to pass arguments to a python script, you may want to take a look at argparse instead: https://docs.python.org/3/library/argparse.html
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('integers', type=int, nargs='+')
args = parser.parse_args()
print(args.integers)
python script.py 1 2 3 4
[1, 2, 3, 4]
You try to evaluate everything as an int which is obviously not going to work. Try this instead:
data = []
while True:
entry = input('Item number : ')
if entry == 'q':
break
try:
data.append(int(entry))
except:
print("Not a valid number")
I'm trying to make the following code work:
try:
x = int(input())
except ValueError as var:
#print the input of the user
If I try to print(var) it would print the error line and not the original input of the user.
For example, if the user would insert bla instead of an integer I would like to print bla
P.S I must not change the line x = int(input()), else I would've solved it easily
I would change the x = int(input()) line, but since you ask, here is an ugly hack wich exploits the format of a ValueError message:
invalid literal for int() with base 10: 'foobar'
by splitting it at first : and removing surrounding ':
try:
x = int(input())
except ValueError as e:
original_input = str(e).split(":")[1].strip()[1:-1]
print(original_input)
by the way, if you are still using Python 2.x, you should use raw_input instead of input. In fact old input will automatically attempt a conversion to int if possible:
try:
x = int(raw_input())
except ValueError as e:
original_input = str(e).split(":")[1].strip()[1:-1]
print original_input
What appears when you print var?
Until you provide that information, here is a possible hackish solution:
try:
x = int(input())
except NameError as var:
e = str(var)
print e[6:-16]
This is assuming var is equal to
NameError: name 'user_input' is not defined
where user_input is the user's input.
EDIT: This post assumed the code was running in Python 2.x whereas it seems to be running with Python 3. Leaving this up in case people are wondering for Python 2
This is hack that reads the input from the passed error message. It handles quotes in the input string and backslashes correctly.
#We get input from the user
try:
x = int(input())
except ValueError as var:
#we need to find the text between the quotes in the error message
#but we don't know what kind of quote it will be. We will look for
#the first quote which will be the kind of quotes.
#get the location or existence of each kind of quote
first_dquote = str(var).find('"')
first_squote = str(var).find("'")
used_quote = 0
#if double quotes don't exist then it must be a single quote
if -1 == first_dquote:
used_quote = first_squote
#if single quotes don't exist then it must be a dubble quote
elif -1 == first_squote:
used_quote = first_dquote
#if they both exist then the first one is the outside quote
else: used_quote = min(first_squote,first_dquote)
#the output is what is between the quotes. We leave of the end
#because there is the end quote.
output = str(var)[used_quote+1:-1]
#but the error message is escaped so we need to unescape it
output = bytes(output,"utf_8").decode("unicode_escape")
#print the output
print(output)
This question already has answers here:
Turn a variable from string to integer in python [duplicate]
(3 answers)
Closed 4 years ago.
I wrote this program up a few hours ago:
while True:
print 'What would you like me to double?'
line = raw_input('> ')
if line == 'done':
break
else:
float(line) #doesn't seem to work. Why?
result = line*2
print type(line) #prints as string?
print type(result) #prints as string?
print " Entered value times two is ", result
print 'Done! Enter to close'
As far as I can tell, it should be working fine.The issue is that when I input a value, for example 6, I receive 66 instead of 12. It seems like this portion of code:
float(line)
is not working and is treating line as a string instead of a floating point number. I've only been doing python for a day, so its probably a rookie mistake. Thanks for your help!
float() returns a float, not converts it. Try:
line = float(line)
float(line) does not convert in-place. It returns the float value. You need to assign it back to a float variable.
float_line = float(line)
UPDATE: Actually a better way is to first check if the input is a digit or not. In case it is not a digit float(line) would crash. So this is better -
float_line = None
if line.isdigit():
float_line = float(line)
else:
print 'ERROR: Input needs to be a DIGIT or FLOAT.'
Note that you can also do this by catching ValueError exception by first forcefully converting line and in except handle it.
try:
float_line = float(line)
except ValueError:
float_line = None
Any of the above 2 methods would lead to a more robust program.
float(line) doesn't change line at all, so it is still a string. You'll want to use line = float(line) instead.