How do I move back to my try block after catching the exception? Below is the code:
def main():
while True:
try:
a = int(input("Enter first value"))
except ValueError:
print("Please enter a number")
main()
try:
b= int(input("enter second value"))
except ValueError:
print("Please enter a number")
main()
So if I enter a letter instead of number the exception is caught, but how do I go back to printing the statement in try block to allow to add a number. I added the main() command but it works only for the first variable cause if the exception is in the second variable it goes back to taking input of first value.
Below is the output of the above code:
Enter first value: a
Please enter a number
Enter first value 5
Enter second value a
Please enter a number
Enter first value 5
The last statement should go back to second try instead of first.
I would do it like this:
def getn(s):
while True:
try:
a = int(input(f"Enter {s} value"))
break
except ValueError:
print("Please enter a number")
return a
def main():
while True:
a= getn("first")
b= getn("second")
main()
of course you can put the logic in main as well..
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 stuck with this homework:
rewrite the following program so that it can handle any invalid inputs from user.
def example():
for i in range(3)
x=eval(input('Enter a number: '))
y=eval(input('enter another one: '))
print(x/y)
l tried tried the try... except ValueError, but the program is still failing to run.
That's because you probably didn't consider the ZeroDivisionError that you get when y = 0!
What about
def example():
for i in range(3):
correct_inputs = False
while not correct_inputs:
try:
x=eval(input('Enter a number: '))
y=eval(input('enter another one: '))
print(x/y)
correct_inputs = True
except:
print("bad input received")
continue
This function computes exactly 3 correct divisions x/y!
If you need a good reference on continue operator, please have a look here
def example():
for i in range(3)
try:
x=eval(input('Enter a number: '))
except ValueError:
print("Sorry, value error")
try:
y=eval(input('enter another one: '))
except ValueError:
print("Sorry, value error")`enter code here`
try:
print(x/y)
except ValueError:
print("Sorry, cant divide zero")
I am new to Python.Trying to learn it.
This is my Code:
import sys
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
except ValueError:
("You must enter an integer")
ints=list()
count=0
while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
The code is executing but the loop is always repeating and is not allowing me to enter 2nd integer.
Output:
How many integers?3
Please enter integer1:1
Please enter integer1:2
Please enter integer1:3
Please enter integer1:
Can i know what is wrong with my code?
Thank you
The problem of your code is that isint is never changed and is always False, thus count is never changed. I guess your intention is that when the input is a valid integer, increase the count;otherwise, do nothing to count.
Here is the code, isint flag is not need:
import sys
while True:
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
break
except ValueError:
print("You must enter an integer")
ints=list()
count=0
while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
try:
new_int=int(new_int)
ints.append(new_int)
count += 1
except:
print("You must enter an integer")
isint needs to be updated after asserting that the input was int
UPDATE:
There is another problem on the first try-except. If the input wasn't integer, the program should be able to exit or take you back to the begining. The following will keep on looping until you enter an integer first
ints=list()
proceed = False
while not proceed:
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
proceed=True
except:
print ("You must enter an integer")
count=0
while count<my_int:
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
isint=True
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
count+=1
A better code:
import sys
my_int=raw_input("How many integers?")
try:
my_int=int(my_int)
except ValueError:
("You must enter an integer")
ints = []
for count in range(0, my_int):
new_int=raw_input("Please enter integer{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
isint = True
except:
print("You must enter an integer")
if isint==True:
ints.append(new_int)
Im still very new when it comes to python so be easy on me. Whenever I test this code it comes back with "None" instead of the input entered. Any idea why it could be happening?
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
break
except:
print('Please enter a whole number (10000)')
return value
def main():
while(1):
landValue = inputLandValue()
print(landValue)
doMoreStuff = input('Do you want to continue? y/n ')
if(doMoreStuff.lower() != 'y'):
break
main()
input()
You indented your return value line too far. It is part of the except: handler, so it is only executed when you have no value! It should be outside the while loop:
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
break
except:
print('Please enter a whole number (10000)')
return value
or replace the break with return value:
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
return value
except:
print('Please enter a whole number (10000)')
You should really only catch ValueError however; this isn't Pokemon, don't try to catch'm all:
except ValueError:
You can fix your problem by just putting 'return value' in place of the break in main().