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:
...
Related
Let's say I have the following code, that assign 1 and print it in case the value is None or not negative.
value = None
class NegativeNumber(Exception):
pass
class NotFound(Exception):
pass
try:
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NegativeNumber:
print("Error: negative number")
except NotFound:
value = 1
print(value)
else:
value = 1
print(value)
Is there a way to avoid repeat twice to assign value=1 and print it?
It would be ideal something like except NotFound or else, but I have not found anything similar in python.
There is no except ... or else: construct. Suppress the exception inside the try block to trigger the else block for the exception as well:
try:
try:
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NotFound:
pass # suppress exception
except NegativeNumber:
print("Error: negative number")
else:
value = 1
print(value)
Instead of using try/except to suppress the exception, contextlib.suppress can be used instead. This can make the intention clearer, as it explicitly names how the exception is handled.
try:
with suppress(NotFound):
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NegativeNumber:
print("Error: negative number")
else:
value = 1
print(value)
def enterNumber():
number = input("Please enter a number to convert to binary. ")
while True:
try:
int(number)
convertDenary()
except ValueError:
enterNumber()
def convertDenary():
binaryNumber = ['','','','','','','','']
print(enterNumber())
if enterNumber() > 128:
enterNumber() - 128
binaryNumber[0] == 1
enterNumber()
The Try- Except ValueError does loop as I intend it to however, it won't break. I've tried adding in break under the int(number), removing the while True: and added in the convertDenary() to see if it will force the subroutine to stop and start the other but it still doesn't work.
I get an infinite loop of "Please enter a number to convert to binary."
Any ideas?
def convertToBinary(number):
if number > 1:
convertToBinary(number//2)
elif number<1:
enterNumber()
print(number % 2,end = '')
def enterNumber():
number = (input("Please enter a number to convert to binary : "))
try:
convertToBinary(int(number))
except Exception as e:
print(e)
enterNumber()
fairly new to Python here. Have this code:
def someFunction( num ):
if num < 0:
raise Exception("Negative Number!")
elif num > 1000:
raise Exception("Big Number!")
else:
print "Tests passed"
try:
someFunction(10000)
except Exception:
print "This was a negative number but we didn't crash"
except Exception:
print "This was a big number but we didn't crash"
else:
print "All tests passed and we didn't crash"
I originally used raise "Negative Number!" etc but quickly discovered that this was the old way of doing things and you have to call the Exception class. Now it's working fine but how do I distinguish between my two exceptions? For the code below it's printing "This was a negative number but we didn't crash". Any pointers on this would be great. Thanks!
you need to create your own exception classes if you want to be able to distinguish the kind of exception that happened. example (i inherited from ValueError as i think this is the closest to what you want - it also allows you to just catch ValueError should the distinction not matter):
class NegativeError(ValueError):
pass
class BigNumberError(ValueError):
pass
def someFunction( num ):
if num < 0:
raise NegativeError("Negative Number!")
elif num > 1000:
raise BigNumberError("Big Number!")
else:
print "Tests passed"
try:
someFunction(10000)
except NegativeError as e:
print "This was a negative number but we didn't crash"
print e
except BigNumberError as e:
print "This was a big number but we didn't crash"
print e
else:
print "All tests passed and we didn't crash"
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 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))