I would like to perform exception handling on the for statement at the bottom to perform similar exception handling as the function at the top. How would I go about implementing exception handling the for statement at the bottom? I would appreciate examples as I'm trying to learn to program. Regards:
def tested_values(user_input):
while True:
try:
user_input_int = int(input(user_input))
return user_input_int
except ValueError:
print("Please enter a number!")
def input_values(prompt="Please enter the number of stands you wish to enter the sales values for: "):
values = tested_values(prompt)
# user_input = int(input(prompt))
sales = []
for sales_values in range(1, values+1):
prompt = "Please enter the sales value for " + str(sales_values) + ": "
sales.append(int(input(prompt)))
print(sales)
input_values()
Similarly to how you did it above:
for sales_values in range(1, values+1):
while True:
try:
prompt = "Please enter the sales value for " + str(sales_values) + ": "
sales.append(int(input(prompt)))
break
except ValueError:
print("Please enter a number!")
Related
How to exit the program after max 3 attempts using Python, for exception program , if you dont get the desired output?
while True:
try:
x = int(input("Please enter a number: "))
break
#except Exception as e:
# print (e)
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
exit (1)
nothing = 0
while nothing < 3:
nothing += 1
try:
x = int(input("Please enter a number: "))
break
#except Exception as e:
# print (e)
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
break
Try:
c = 0
while c < 3:
c += 1
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
break
You want exit after 3 attemps. Try this and count that input is wrong:
num_err = 0
while num_err < 3:
try:
x = int(input("Please enter a number: "))
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
num_err += 1
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
break
Use sys.exit() for stopping the whole script
import sys
while True:
try:
x = int(input("Please enter a number: "))
#except Exception as e:
# print (e)
except ValueError:
print ("You have entered the non-numeric value. Enter the numerical value.")
except KeyboardInterrupt:
print ("\nYou have press Ctr+C.")
sys.exit()
I read all the code that is submitted above but one thing is missing, that if a user
enter two incorrect value then enter a correct value after that he has only one chance. That is if user enter any wrong input after entering two correct input the loop will break.
So I have tried to solve this problem. Look at my code...
count = 0
while True:
try:
x = int(input("Please enter a number: "))
count = 0
break
except ValueError:
count += 1
print("You have entered the non-numeric value.Only three invalid inputs are allowed. Enter the numerical value.")
except KeyboardInterrupt:
print("\nYou have press Ctr+C.")
exit(1)
if count == 3:
break
I am trying to explain what I have written in this code.
As you have mentioned that a user can enter only three invalid input so I have increased the variable count each time when user will enter an invalid input. But if a user will enter a valid input then the count will be 0. It means again the user can enter maximum three invalid input. After entering three invalid input continuously the count will be 3 and the loop break
I don't want to make the user be able to enter anything other than numbers as the input for the "number" variable, except for the string "done".
Is it possible to somehow make an exception to the rules of the try-except block, and make the user be able to write "done" to break the while loop, while still keeping the current functionality? Or should I just try something different to make that work?
while number != "done":
try:
number = float(input("Enter a number: ")) #The user should be able to write "done" here as well
except ValueError:
print("not a number!")
continue
Separate the two parts : ask the user and verify if it is done, then parse it in a try/except
number = None
while True:
number = input("Enter a number: ")
if number == "done":
break
try:
number = float(number)
except ValueError:
print("not a number!")
continue
print("Nice number", number)
Instead of trying to make exceptions to the rules, you can instead do something like,
while True:
try:
number=input("Enter a number: ")
number=float(number)
except:
if number=="done":
break
else:
print("Not a number")
Check if the error message contains 'done':
while True:
try:
number = float(input("Enter a number: "))
except ValueError as e:
if "'done'" in str(e):
break
print("not a number!")
continue
also in this case continue is not necessary here (for this example at least) so it can be removed
Maybe convert the number to float afterwards. You can check if number is not equal to done,then convert the number to float
number = 0
while number != "done":
try:
number = input("Enter a number: ") #The user should be able to write "done" here as well
if number=="done":
continue
else:
number = float(number )
except ValueError:
print("not a number!")
continue
There are various ways to approach this situation.
First one that came across my mind is by doing:
while True:
user_input = input("Enter a number: ")
if user_input == "done":
break
else:
try:
number = float(user_input)
except ValueError:
print("not a number!")
continue
while True:
try:
user_input = input("Enter a number: ")
if user_input == "done":
break
number = float(user_input)
except ValueError:
print("not a number!")
continue
You can cast the input to float after checking if the input is 'done'
I am error handling the customer name, distance travelled, virus protection and wof and tune for my program. What would I put in plce of 'something' or instead of using and if and else statement to run the enter_job function when there are no errors, so when none of the code inside the if something part is relevant to the data entered?
Thank you!
if something:
if self.name_entry_var.get() == "":
self.name_entry_error.configure(text = "Enter customer name")
if self.wof_var.get() == " ":
self.wof_entry_error.configure(text = "Check YES or NO")
try:
if float(self.time_entry.get()) <= 0:
self.time_entry_error.configure(text = "Enter a positive number")
except ValueError:
self.time_entry_error.configure(text = "Enter a number")
try:
if float(self.distance_entry.get()) <= 0:
self.distance_entry_error.configure(text = "Enter a positive number")
except ValueError:
self.distance_entry_error.configure(text = "Enter a number")
else:
self.enter_job()
Edit:
If I do this then it will go straight into the enter_job function without checking the entries.
try:
self.enter_job()
except:
if self.name_entry_var.get() == "":
self.name_entry_error.configure(text = "Enter customer name")
if self.wof_var.get() == " ":
self.wof_entry_error.configure(text = "Check YES or NO")
try:
if float(self.time_entry.get()) <= 0:
self.time_entry_error.configure(text = "Enter a positive number")
except ValueError:
self.time_entry_error.configure(text = "Enter a number")
try:
if float(self.distance_entry.get()) <= 0:
self.distance_entry_error.configure(text = "Enter a positive number")
except ValueError:
self.distance_entry_error.configure(text = "Enter a number")
The error handling should be done within the enter_job() function.
something like so:
def enter_job():
if self.name_entry_var.get() == "":
self.name_entry_error.configure(text = "Enter customer name")
raise(self.name_entry_error)
if self.wof_var.get() == " ":
self.wof_entry_error.configure(text = "Check YES or NO")
raise(self.wof_entry_error)
try:
if float(self.time_entry.get()) <= 0:
self.time_entry_error.configure(text = "Enter a positive number")
raise(self.time_entry_error)
except ValueError:
self.time_entry_error.configure(text = "Enter a number")
raise(self.time_entry_error)
try:
if float(self.distance_entry.get()) <= 0:
self.distance_entry_error.configure(text = "Enter a positive number")
raise(self.distance_entry_error)
except ValueError:
self.distance_entry_error.configure(text = "Enter a number")
raise(self.distance_entry_error)
then running this line:
self.enter_job()
would return exceptions on it's own.
like so:
try:
self.enter_job()
except Exception as e:
raise(e)
I tried exception handling and got stuck in my first program, in this program my first continue in while is working but 2nd one is not continuing the loop
print("hello to divide")
o = "y"
while o == "y":
try:
x = int(input("enter first no. = "))
y = int(input("enter second no. = "))
except:
print("please enter numeric value")
continue
try:
z = x/y
print(str(x) +"/"+str(y)+"="+str(z))
except:
print("please do not divide with 0(zero)")
continue
finally:
o = input("do you want to do it again (y/n)? = ")
The second except is working fine but after printing message it jumps to finally statement
please help ???
From the docs:
A finally clause is always executed before leaving the try
statement, whether an exception has occurred or not. When an exception
has occurred in the try clause and has not been handled by an
except clause (or it has occurred in an except or else clause),
it is re-raised after the finally clause has been executed. The
finally clause is also executed “on the way out” when any other
clause of the try statement is left via a break, continue or
return statement. A more complicated example:
I'm pretty sure you just want:
print("hello to divide")
o = "y"
while o == "y":
try:
x = int(input("enter first no. = "))
y = int(input("enter second no. = "))
except:
print("please enter numeric value")
continue
try:
z = x/y
print(str(x) +"/"+str(y)+"="+str(z))
except:
print("please do not divide with 0(zero)")
continue
o = input("do you want to do it again (y/n)? = ")
This is my code.
print("Welcome to the quiz")
print("Would you like to login with an existing account or register for a new account?")
class validation(Exception):
def __init__(self, error):
self.error = error
def printError(self):
print ("Error: {} ".format(self.error))
def mainError():
try:
raise validation('Please enter a valid input')
except validation as e:
e.printError()
def login():
print ("yet to be made")
def register():
print ("yet to be made")
while True:
options = ["Login", "Register"]
print("Please, choose one of the following options")
num_of_options = len(options)
for i in range(num_of_options):
print("press " + str(i + 1) + " to " + options[i])
uchoice = int(input("? "))
print("You chose to " + options[uchoice - 1])
if uchoice == 1:
login()
break
elif uchoice == 2:
register()
break
else:
mainError()
If I enter 'a', it comes up with this error:
line 35, in <module>
uchoice = int(input("? "))
ValueError: invalid literal for int() with base 10: 'a'
If I enter a number above 2 like '3':
line 36, in <module>
print("You chose to " + options[uchoice - 1])
IndexError: list index out of range
How can I make sure that if a user enters anything other than 1 or 2, it executes my else commands where it calls my mainError() method which contains my exception that the program would display to my user.
The exception is raising because you don't have the options element you're trying to print in the message
print("You chose to " + options[uchoice - 1])
Here you're trying to get options[a] or options [3], which doesn't exists.
Put this print only inside the if/else that has a related option, and another print in the else without one.
Something like this:
for i in range(num_of_options):
print("press " + str(i + 1) + " to " + options[i])
uchoice = int(input("? "))
if uchoice == 1:
print("You chose to " + options[uchoice - 1])
login()
break
elif uchoice == 2:
print("You chose to " + options[uchoice - 1])
register()
break
else:
mainError()
uchoice = int(input("? "))
Well here you have to do some error-checking code like:
try:
uchoice = int(input("? "))
except ValueError:
<handling for when the user doesn't input an integer [0-9]+>
Then to handle the overflow when a user enters an index which isn't within the list's range:
try:
options[uchoice - 1]
except IndexError:
<handling for when the user inputs out-of-range integer>
Of course this adds overhead due to the try: ... except <error>: ... statement so in the most optimal case you would use conditional checking per something like this:
if (uchoice - 1) > len(options):
<handling for when the user inputs out-of-range integer>