Python with 2 continue in a while - python

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)? = ")

Related

How to exit the program after max 3 attempts using Python, for exception program , if you dont get the desired output?

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

How to make a specific string work in a try-except block?

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'

How do I move back to try block after catching exception

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..

Better way to ask user input in integer form in Python?

So I'm kind of very beginner to programming and just learning yet the basics. Now I would like to have my python program to ask the user to give a number and keep asking with a loop if string or something else is given instead.
So this is the best I came out with:
value = False
while value == False:
a = input("Give a number: ")
b = 0
c = b
try:
int(a)
except ValueError:
print("No way")
b += 1
if c == b:
value = True
So is there easier and better way to do this?
You can use this:
while True:
try:
a = int(input("Give a number: "))
break
except ValueError:
print("No way")
or this:
while True:
a = input("Give a number: ")
if a.isdigit():
break
print("No way")
while True:
try:
a = int(input("Give a number: "))
break
except ValueError:
print("No way")
continue
This will continue to prompt the user for an integer till they give one.
value = True
while value == True:
a = input("Give a number: ")
try:
int(a)
except ValueError:
print("No way")
continue
print("Yay a Number:", a)
value = False
Is this what you need?

how to come to try: block from except: block in python?

summ=0
average=0
count=0
try:
while True:
enterNumber=raw_input("Enter a number:")
if enterNumber=='done':
print summ
print average
print count
break
else:
summ=summ+int(enterNumber)
count=count+1
average=float(summ/count)
except:
print "Invalid number!" #when this block is reached the program ends,
#I want the program to continue till I enter
#'done'
The try: ... except: ... block does not control the flow of the program in an arbitrary way - it just ensures the except (or the other counterparts like the else and finally blocks) is run whenever an exceptions occurs.
To "go back" to another part of the program you have to use another contrso stucture. One that could be usefull here is a while block
while True:
try:
# code goes here
...
except:
# handle exception
...
else:
# The else block of a `try` is
# only entered when no exceptions occur
break # this gets out of the while block
summ=0
average=0
count=0
while True:
# add try/except under while's scope
try:
enterNumber=raw_input("Enter a number:")
if enterNumber=='done':
print (summ)
print (average)
print (count)
break
else:
summ=summ+int(enterNumber)
count=count+1
average=float(summ/count)
except Exception as e:
print (e)
print ("Invalid number!") #when this block is reached the program ends,
#I want the program to continue till I enter
#'done'
Enter a number: hey
invalid literal for int() with base 10: 'hey'
Invalid number!
Enter a number: 10
Enter a number: done
10
10.0
1
this might be a version of what you want:
enterNumber = None
summ = 0
average = 0
count = 0
while enterNumber != 'done':
enterNumber = raw_input("Enter a number:")
try:
enterInt = int(enterNumber)
except ValueError:
print("Invalid number!")
continue
summ += enterInt
count += 1
# average = summ/count # this works in python 3
average = summ / float(count) # the safe way for python 2
print(summ)
print(average)
print(count)
note:
you need not calculate the average within the input loop.
try/catch only wraps the part of the code that might raise an exception.
float(summ/count) (in your version) does the division in the integers (at least in python 2); summ / float(count) may be what you want.
this code prints Invalid number! when you enter done. this could be improved.

Categories