Python retrieve string input from int(input()) exception - python

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)

Related

how do I differentiate between str and int and is this what ValueError: invalid literal for int() with base 10: error means?

choice = input (" ")
choice = int(choice)
if choice == 2:
print ("What class are you in? Please choose (class) 1, 2 or 3.")
Class = int(input ())
#class 1 file
if Class == 1:
c1 = open('class1.csv', 'a+')
ScoreCount = str(ScoreCount)
c1.write(myName + "-" + ScoreCount)
c1.write("\n")
c1.close()
read_c1 = open('class1.csv', 'r')
print (read_c1)
if choice == 3:
row[1]=int(row[1]) #converts the values into int.
row[2]=int(row[2])
row[3]=int(row[3])
row[4]=int(row[4])
if choice == 4:
WMCI= 1
print ("Thank You. Bye!")
So when this code is actually run it outputs an error which I don't understand:
ValueError: invalid literal for int() with base 10:#(myName-score)
How to fix this and what does this error mean in simple terms?
You've got 2 bugs.
The first is when you store your score into the csv, you're converting ScoreCount into a string, and keeping it that way. You need to let the conversion be temporary for just the job:
#class 1 file
if Class == 1:
c1 = open('class1.csv', 'a+')
c1.write(myName + "-" + str(ScoreCount))
c1.write("\n")
c1.close()
read_c1 = open('class1.csv', 'r')
print (read_c1)
That'll fix it with Class 1, you'll need to do 2 & 3. Your second bug is when you're reading the scores from the file, you've stored them as: "Name-5" if the person called Name had scored 5. That means you can't convert them as a whole entity into a number. You'll need to split the number part off. So in min max, where you've got:
row[0] = int (row[0])
It needs to become:
row[0] = int(row[0].split("-")[1])
But from there I can't figure out your logic or what you're trying to achieve in that section of code. It'll get rid of the current error, but that part of your code needs more work.
Explaining the right hand side of the above line of code by building it up:
row[0] # For our example, this will return 'Guido-9'
row[0].split("-") # Splits the string to return ['Guido','9']
row[0].split("-")[1] # Takes the second item and returns '9'
int(row[0].split("-")[1]) # Turns it into a number and returns 9
split("-") is the part you're likely to not have met, it breaks a string up into a list, splitting it at the point of the "-" in our example, but would be at the spaces if the brackets were left empty: split() or any other character you put in the brackets.
You are probably trying to convert something that can't be converted to an int for example
int("h")
This would give the base 10 error which you are getting

Syntax error: 002: on assigning values to variables python

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

loop prints a error message multiple times

edited for clarity. When a loop prints an error message multiple times, it is usually caused by poor control flow. In this case, adding a Breakafter print solved the problem.
Following a simple loop structure with some control flow, is generally a good starting point.
for ...:
if ...:
print ...
break
input_seq = "";
#raw_input() reads every input as a string
input_seq = raw_input("\nPlease input the last 12 nucleotide of the target sequence
before the PAM site.\n\(The PAM site is by default \"NGG\"\):\n12 nt = ")
#print "raw_input =", input_seq
for bases in input_seq:
if not (bases in "ACTGactg"):
print "\nYour input is wrong. Only A.T.C.G.a.t.c.g are allowed for
the input!\n\n";
break
Use break. I am using regular expressions to avoid using a for loop.
input_seq = ""
import re
while True:
#raw_input() reads every input as a string
input_seq = raw_input("\nPlease input the last 12 nucleotide of the target sequence
before the PAM site.\n\(The PAM site is by default \"NGG\"\):\n12 nt = ")
#print "raw_input =", input_seq
if len(input_seq)==12:
match=re.match(r'[ATCGatcg]{12}',input_seq)
if match:
break
else:
print "\nYour input is wrong. Only A.T.C.G.a.t.c.g are allowed for the input!\n\n"
continue
else:
print "\nYour input should be of 12 character"
Add a break after your print statement. That will terminate your loop.
Using a flag to check if there were atleast one wrong input is one way to do it. Like this:
invalid = False
for bases in input_seq:
if not (bases in "ACTGactg"):
invalid = True
if invalid:
print "\nYour input is wrong. Only A.T.C.G.a.t.c.g are allowed for the input!\n\n";
You could alternately use a break statement as soon as you find the first wrong input.
Place a break after the print:
for ...:
if ...:
print ...
break

python input() not working as expected [duplicate]

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

Python: String will not convert to float [duplicate]

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.

Categories

Resources