Specific Try and Except - python

continue = True
while continue:
try:
userInput = int(input("Please enter an integer: "))
except ValueError:
print("Sorry, wrong value.")
else:
continue = False
For the code above, how would I be able to catch a specific ValueError? What I mean by that is if the user inputs a non-integer, I would print out "Sorry, that is not an integer.". But if the user input is an empty input, I would print out "Empty Input.".

Move the call to input outside of the try: block and place only the call to int inside it. This will ensure that userInput is defined, allowing you to then check its value with an if-statement:
keepgoing = True
while keepgoing:
userInput = input("Please enter an integer: ") # Get the input.
try:
userInput = int(userInput) # Try to convert it into an integer.
except ValueError:
if userInput: # See if input is non-empty.
print("Sorry, that is not an integer.")
else: # If we get here, there was no input.
print("Empty input")
else:
keepgoing = False

Perhaps something like this:
keepgoing = True
while keepgoing:
try:
userInput = input("Please enter an integer: ")
if userInput == "":
print("Empty value")
raise ValueError
else:
userInput = int(userInput)
except ValueError:
print("Sorry, wrong value.")
else:
keepgoing = False

Related

How to find if the value contains characters

Right now am planning to add items into the database. The item name, price and all are all entered by the users. How do I find if theres any alphabets when entering the price? i tried using .isnumber() but it seems to be reading my decimal point as a character as well.
while True:
itemPrice = input("Please Enter Item Price: ")
if str(itemPrice).isnumeric() == False:
print("Please enter a value!")
else:
print(itemPrice)
break
For example, they allow if i enter 5 but not 5.5 and since this is item price it should have decimals.
You can catch exceptions,
while True:
itemPrice = input("Please Enter Item Price: ")
try:
itemPrice = float(itemPrice)
print(itemPrice)
break
except ValueError:
print("Please enter a value!")
you can use try/except block
a = 3.5345
a=str(a)
try: #if it can be converted to a float, it's true
float(a)
print(True)
except: # it it can't be converted to a float, it's false
print(False)
You could try using a for loop to check:
def containsAlpha(x):
if True in [char.isalpha() for char in x]:
return True
return False
while True:
itemPrice = input("Please Enter Item Price: ")
if containsAlpha(itemPrice):
print("Please enter a value!")
else:
print(itemPrice)
break

How can I add exception handling without skiping into the next input function?

valid_Total = 120
def get_num(n):
inp = -1
while input not in range(121):
try:
inp = int(input(f"Enter your total {n} credits : "))
if inp not in range(121):
print("Out of range")
else:
pass
except ValueError:
print("Please enter a integer")
return inp
while True:
x = get_num("PASS")
y = get_num("DEFER")
z = get_num("FAIL")
if x+y+z != valid_Total:
print("Incorrect Total")
else:
break
How can I fix the exception handling so when I input anything other than a integer it ask to enter the value again to the same variable without procceeding it onto the next variable?
You can simplify this with a "infinite" loop
def get_num(n):
while True:
inp = input(f"Enter your total {n} credits : ")
try:
inp = int(inp)
if inp in range(121):
return inp
print("Out of range")
except ValueError:
print("Please enter an integer")
The only way out of the loop is to reach the return statement, by both avoiding a ValueError and successfully passing the range check.
If you don't want to nest the range check inside the try statement (a reasonable request), you can use a continue statement to skip the range check in the event of an exception.
def get_num(n):
while True:
inp = input(f"Enter your total {n} credits : ")
try:
inp = int(inp)
except ValueError:
print("Please enter an integer")
continue
if inp in range(121):
return inp
print("Out of range")
You can also invert the range check by using an additional continue statement.
def get_num(n):
while True:
inp = input(f"Enter your total {n} credits : ")
try:
inp = int(inp)
except ValueError:
print("Please enter an integer")
continue
if inp not in range(121):
print("Out of range")
continue
return inp
Simply add continue at the end of your except clause:
except ValueError:
print("Please enter a integer")
continue
It will go back to the top of the while

Trying to control the user's input to strictly a positive number only

I am trying to control the user's input using exception handling. I need them to only input a positive number, and then I have to return and print out that number.
I have to send a message if the user puts in non-number and I have to send a message if the user puts in a number less than 1. Here is what I have:
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
boolChoice = False
except ValueError:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
elif l < 0:
print("Your number is not positive")
print("Try again")
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
My program works fine until a negative integer gets inputted. It doesn't print the message and then goes through the loop again, it just returns and prints back the negative number, which I don't want. How can I fix this? Thank you.
You can use try...except to check if its an integer or letters
def input_validation(prompt):
while True:
try:
l = int(input(prompt))
if l<0: #=== If value of l is < 0 like -1,-2
print("Not a positive number.")
else:
break
except ValueError:
print("Your input is invalid.")
print("Try again")
return l
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
try
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
if x < 0:
print ("Your input is a negative number\n Please enter a postive number")
elif x == 0:
print("Your input is zero\n Please enter a postive number ")
else:
boolChoice = False
except Exception as e:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
else:
print(f"Failed to accept input due to {e}")
print("Try again")
continue
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()

Continuously re-running a while loop until a certain input [duplicate]

This question already has answers here:
If an exception is raised ask again for input
(5 answers)
Closed 9 years ago.
What I'm trying to do with this is ask the user for two inputs and then call a function on the inputs. If it doesn't raise an exception then do the while loop again. If it does raise an exception than print something and do the while loop again. The problem I have is that I can't find a way to do the while loop again if it doesn't raise an exception. It works if it does raise an exception. The only way I can think of it is where I put #Rerun loop paste the entire while True loop again but that would be really horrible in this case.
class Illegal(Exception):
pass
def add_input(first_input, second_input):
if first_input + second_input >= 10:
print('legal')
else:
raise Illegal
def play():
inp = input("Ready? <yes/no>: ")
if inp == 'yes':
while True:
first_input = input("First number: ")
second_input = input("Second number: ")
try:
if first_input or second_input == 'quit':
break
else:
add_input(int(first_input), int(second_input))
#Rerun loop
except Illegal:
print("Illegal")
else:
break
else:
return
>>> play()
Ready? <yes/no>: yes
First number: 1
Second number: 2
Illegal
First number: 9
Second number: 6
legal
First number: 1
Second number: 2
Illegal
First number: quit
What I thought of doing:
def play():
inp = input("Ready? <yes/no>: ")
if inp == 'yes':
while True:
first_input = input("First number: ")
second_input = input("Second number: ")
try:
if first_input or second_input == 'quit':
break
else:
add_input(int(first_input), int(second_input))
while True:
first_input = input("First number: ")
except Illegal:
print("Illegal move")
else:
break
except Illegal:
print("Illegal move")
else:
break
else:
return second_input = input("Second number: ")
try:
if first_input or second_input == 'quit':
break
else:
add_input(int(first_input), int(second_input))
#Rerun loop
But this is a horrible idea because then I'd have to paste the same thing continuously.
The break in your else: causes the loop to exit. You can remove this entirely:
else:
break
You want to run the loop while the user doesn't quit it via typing quit. So you just have to remove this else: break:
def play():
inp = input("Ready? <yes/no>: ")
if inp.lower() == 'yes':
while True:
first_input = input("First number: ")
second_input = input("Second number: ")
# quit if the user wants
if first_input or second_input == 'quit':
break
try:
add_input(int(first_input), int(second_input))
except Illegal:
print("Illegal")
Also, take the habit to put the minimum of code in your try/except blocks. It makes the debugging easier after. Your last else: return is also useless, you can remove it.

try: statement fails

I have some python code that fails:
import sys
print ("MathCheats Times-Ed by jtl999")
numbermodechoice = raw_input ("Are you using a number with a decimal? yes/no ")
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
numberx2 = (float)(raw_input('Enter second number: '))
elif numbermodechoice == "no":
print ("Rember only numbers are allowed")
numberx1 = (int)(raw_input('Enter first number: '))
numberx2 = (int)(raw_input('Enter second number: '))
else:
print ("Oops you typed it wrong")
exit()
print ("The answer was")
print numberx1*numberx2
ostype = sys.platform
if ostype == 'win32':
raw_input ("Press enter to exit")
elif ostype == 'win64':
raw_input ("Press enter to exit")
(Full code here)
I want to wrap the float operations with try statements so if a ValueError happens, it gets caught. Here is the output:
File "./Timesed.py", line 23
try:
^
IndentationError: expected an indented block
What is wrong with it and how can I fix this?
Python is whitespace sensitive, with regards to the leading whitespace.
your code probably should be indented like
import sys
from sys import exit
print ("MathCheats Times-Ed by jtl999")
numbermodechoice = raw_input ("Are you using a number with a decimal? yes/no ")
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
numberx2 = float(raw_input('Enter second number: '))
except ValueError:
print ("Oops you typed it wrong")
exit()
elif numbermodechoice == "no":
print ("Remember only numbers are allowed")
try:
numberx1 = (int)(raw_input('Enter first number: '))
numberx2 = (int)(raw_input('Enter second number: '))
except ValueError:
print ("Oops you typed it wrong")
exit()
else:
print ("Oops you typed it wrong")
exit()
print ("The answer was")
print numberx1*numberx2
ostype = sys.platform
if ostype == 'win32':
raw_input ("Press enter to exit")
elif ostype == 'win64':
raw_input ("Press enter to exit")
In python, the indentation of your code is very important. The error you've shown us points here:
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
All code that is part of a block must be indented. By starting a try block, the following line is part of that block and must be indented. To fix it, indent it!
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
You had a wrong syntax. It should be except ValueError: and not except: ValueError. Correct it for you in the question too.
You need to indent the second print statement.
Indentation is important in Python. It's how you delimit blocks in that language.
The conversion to float is using an incorrect syntax. That syntax is valid for C/C++/Java, but not in Python. It should be:
numberx1 = float(raw_input('Enter first number: '))
Which will be interpreted like float("2.3"), which is a constructor for the float type being called with a string parameter. And, yes, the syntax is exactly the same for the function call, so you might even think the constructor is a function that returns an object.
import sys
class YesOrNo(object):
NO_VALUES = set(['n', 'no', 'f', 'fa', 'fal', 'fals', 'false', '0'])
YES_VALUES = set(['y', 'ye', 'yes', 't', 'tr', 'tru', 'true', '1'])
def __init__(self, val):
super(YesOrNo,self).__init__()
self.val = str(val).strip().lower()
if self.val in self.__class__.YES_VALUES:
self.val = True
elif val in self.__class__.NO_VALUES:
self.val = False
else:
raise ValueError('unrecognized YesOrNo value "{0}"'.format(self.val))
def __int__(self):
return int(self.val)
def typeGetter(dataType):
try:
inp = raw_input
except NameError:
inp = input
def getType(msg):
while True:
try:
return dataType(inp(msg))
except ValueError:
pass
return getType
getStr = typeGetter(str)
getInt = typeGetter(int)
getFloat = typeGetter(float)
getYesOrNo = typeGetter(YesOrNo)
def main():
print("MathCheats Times-Ed by jtl999")
isFloat = getYesOrNo("Are you using a number with a decimal? (yes/no) ")
get = (getInt, getFloat)[int(isFloat)]
firstNum = get('Enter first number: ')
secondNum = get('Enter second number: ')
print("The answer is {0}".format(firstNum*secondNum))
if __name__=="__main__":
main()
if sys.platform in ('win32','win64'):
getStr('Press enter to exit')

Categories

Resources