I have this problem in one of my programs, where the try/excepting of an error to make the program better in case the user accidentally enters something they aren't supposed to, isn't working. It still gives me the error and I'm stumped as to why. Here is the error if it really matters to my issue:
ValueError: invalid literal for int() with base 10: 's'
Here is the snippet of code where I except the error:
apple_num = int(raw_input(prompt))
try:
if apple_num == 3 or apple_num == 2 or apple_num == 1:
global apples
apples = apples + apple_num
time.sleep(0.5)
pick()
elif apple_num >= 4:
print "\nYou can't haul that many apples!"
time.sleep(0.5)
pick()
elif apple_num == 0:
main()
except ValueError:
pick()
Once again, I'm stumped as to why I still get the error, as always, any help is appreciated!
The first line is not in the try-except-block.
Change this:
apple_num = int(raw_input(prompt))
try:
To this:
try:
apple_num = int(raw_input(prompt))
Related
So I have the following code where chalnum (short for challenge number) is a randomly generated number. You have to try to get that number through a sequence of inputs (finalnum2). But for some reason, it always thinks the numbers aren't equal even when they are.
chal = input('Would you like a challenge number? (y/n) ')
if 'ye' in chal or chal == 'y':
str = 'Try to get %s \n'
chalnum = round(uniform(5, 5000))
print(str % colored(chalnum, attrs=['underline']))
else:
chalnum = 0
print('\n')
some more code where you make your number, then:
finalnum2 = round(num/ex_num2)
(chalnum, finalnum2)
if finalnum2 == chalnum:
chalcomp = (colored('Congrats! You completed the challenge!', 'green'))
for i in range(chalcomp):
print(chalcomp[i], sep='', end='', flush=True); sleep(0.14)
elif chalnum == 0:
pass
elif finalnum2 > chalnum or finalnum2 < chalnum:
chalfail = (colored('Oh no! It looks like you failed the challenge!', 'red'))
for i in range(chalfail):
print(chalfail[i], sep='', end='', flush=True); sleep(0.14)
else:
raise Exception
Please keep in mind that I am a beginner so if it's a stupid mistake please don't be harsh.
possible that they both in different types like 24!='24'
Use typecasting and convert into say
if int(finalnum2) == int(chalnum):
Comparison would go well in this case.
I am new to Python, after I managed to learn Java at an advanced level.
In Java input validation with exception handling was never a problem to me but somehow in python i get a little confused:
Here an example of a simple FizzBuzz programm which can only read numbers in between 0 and 99, if otherwise, an exception has to be thrown:
if __name__ == '__main__':
def fizzbuzz(n):
try:
if(0<= n <= 99):
for i in range(n):
if i==0:
print("0")
elif (i%3==0 and i%7==0) :
print("fizzbuzz")
elif i%3==0:
print("fizz")
elif i%7==0:
print("buzz")
else:
print(i)
except Exception:
print("/// ATTENTION:The number you entered was not in between 0 and 99///")
try:
enteredNumber = int(input("Please enter a number in between 0 and 99: "))
fizzbuzz(enteredNumber)
except Exception:
print("/// ATTENTION: Something went wrong here. Next time, try to enter a valid Integer ////")
If i run that and enter e.g. 123 the code just terminates and nothing happens.
You need to raise an exception from fizzbuzz() when your condition is not met. Try below:
if __name__ == '__main__':
def fizzbuzz(n):
try:
if(0<= n <= 99):
for i in range(n):
if i==0:
print("0")
elif (i%3==0 and i%7==0) :
print("fizzbuzz")
elif i%3==0:
print("fizz")
elif i%7==0:
print("buzz")
else:
print(i)
else:
raise ValueError("Your exception message")
except Exception:
print("/// ATTENTION:The number you entered was not in between 0 and 99///")
try:
enteredNumber = int(input("Please enter a number in between 0 and 99: "))
fizzbuzz(enteredNumber)
except Exception:
print("/// ATTENTION: Something went wrong here. Next time, try to enter a valid Integer ////")
Also, you must catch specific exceptions instead of catching the generic exception.
If you want to catch an exception you need to make sure it will get raised if the desired scenario occurs.
Since the code block between try and except does not raise an exception by itself, you need to raise one by yourself:
try:
if(0<= n <= 99):
...
else:
raise Exception()
except Exception:
...
I have a small code which is just for me to get more used to python and I have encountered a problem with try and except.
I am trying to get the code below to ask a question and receive an answer using raw_input. If you know what the syntax error in line 22 is? (except ValueError)
Thank you very much.
def start():
print("Type start")
prompt_sta()
def prompt_sta():
prompt_0 = raw_input ("Enter command start")
try:
if prompt_0 == "start":
prompt_sta()
elif prompt_0 == "begin":
print ("You must learn to follow commands")
prompt_sta()
elif promt_0 == "help":
print ("Commands:")
print ("Help")
print ("start")
print ("begin")
prompt_sta()
else:
print ("Please enter a valid command.")
prompt_sta()
print ("Type start")
**except ValueError:**
def outside_house():
print("There is a strange man outside.")
Just in case the error that IDEL is showing has ** on both sides and if you know any better ways for doing what I am trying to do please tell me. Thanks
You need to provide a body for except: statements:
try:
a = "something"
except ValueError:
pass # empty body
My error-handling code is not working. I'm trying to do following: if user enters any input other than 1, 2 or 3, then the user should get error message and the while-loop should start again.
However my code is not working. Any suggestion why?
def main():
print("")
while True:
try:
number=int(input())
if number==1:
print("hei")
if number==2:
print("bye")
if number==3:
print("hei bye")
else:
raise ValueError
except ValueError:
print("Please press 1 for hei, 2 for bye and 3 for hei bye")
main()
You can also use exception handling a bit more nicely here to handle this case, eg:
def main():
# use a dict, so we can lookup the int->message to print
outputs = {1: 'hei', 2: 'bye', 3: 'hei bye'}
print() # print a blank line for some reason
while True:
try:
number = int(input()) # take input and attempt conversion to int
print(outputs[number]) # attempt to take that int and print the related message
except ValueError: # handle where we couldn't make an int
print('You did not enter an integer')
except KeyError: # we got an int, but couldn't find a message
print('You entered an integer, but not, 1, 2 or 3')
else: # no exceptions occurred, so all's okay, we can break the `while` now
break
main()
I am working on a program that will extract a text from a file like so:
NAME OF PROGRAM: text.txt
CONTENTS OF FILE:
1: 101010100101010101 1010010101010101 101010101010101
2: 0101010101 1010011010 10101010 10101010 10101010
3: 0001000101010 10101010 10101010 1010101010 10101
START LINE: 1
END LINE: 2
results.txt generated.
I am at the part where the program will ask for the name of the program and I plan to use exceptions when the name of the program has the length of zero.
The program should have ran like:
NAME OF PROGRAM:
THE NAME OF THE PROGRAM SHOULD NOT BE LESS THAN 1! [LEN_ERROR]
But the program run like so:
NAME OF PROGRAM:
THERE'S SOMETHING WRONG WITH YOUR INPUT! [INP_ERROR]
Here's the code:
class Program:
"""
Author : Alexander B. Falgui (alexbfalgui.github.io)
Program Name : Text Extractor
Description : Takes an integer or string as an input and generates a
text file with the extracted data.
Note: This program can be used, shared, modified by anyone.
"""
def __init__(self):
self.menu_file_loc = "menu"
return self.load_files()
def load_files(self):
#self.menu_file = open(self.menu_file_loc)
#self.read_mf = self.menu_file.read()
return self.main_menu()
def main_menu(self):
#print(self.read_mf)
print(""" [1] Extract Data\n [2] Exit""")
while (True):
try:
self.menu_input = input("CHOOSE AN OPTION> ")
if (self.menu_input == 1):
try:
self.program_name = raw_input("\nNAME OF THE PROGRAM: ")
self.program_name = open(self.program_name)
except IOError:
if (len(program_name) == 0):
print("THE NAME OF THE PROGRAM SHOULD NOT BE LESS THAN"),
print(" 1! [LEN_ERROR]")
print("%s does not exist" % self.program_name)
elif (self.menu_input == 0):
print("\n")
break
except SyntaxError:
continue
except NameError:
print("SOMETHING'S WRONG WITH YOUR INPUT. [INP_ERROR]\n")
# Run the program
Program()
Why did the program print the wrong exception and what can I do to fix that?
Please don't do except SyntaxError: continue, because you will silently go over any kind of syntax error.
To get more information about what's going wrong, you should except NameError as e to investigate further. See also https://docs.python.org/2/tutorial/errors.html
You should change the except NameError-part to the following:
except NameError as e:
print e
print("SOMETHING'S WRONG WITH YOUR INPUT. [INP_ERROR]\n")
and you will see what really goes wrong.
I'm not sure why you added those two exception handler at the end but you are getting a Name Exception because your refer to the program_name variable instead of self.program_name
Change your line if (len(program_name) == 0): to if (len(self.program_name) == 0): and it should work.