python handling invalid inputs from a user - python

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

Related

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'

python docstrings - while loop containing try, break and except

How would I write my docstrings for a method that uses try and except in a while loop. the loop breaks if input is correct. Also is this proper/ good practice code or should I define a variable and set it to true, implement a Raise and and write an if else statement?
def validate_num():
while True:
try:
pick_num = input("enter a number")
break
except ValueError:
print("Not a valid number re-enter.")
I was going to write the following doc string:
def validate_num():
''' Requests user to enter number
except:
ValueError if a non int is entered.
'''
while True:
try:
pick_num = input("enter a number")
break
except ValueError:
print("Not a valid number re-enter.")
Thank you
Since the function doesn't raise ValueError, the docstring shouldn't mention it. The idea of the docstring is that it says what the caller of the function should expect its result to be, and not what happens inside the function.
If I were documenting exactly what the function does as you've written it, I would write:
def validate_num() -> None:
"""Promps the user to enter a number.
Does not validate or return the result."""
while True:
try:
pick_num = input("enter a number")
break
except ValueError:
print("Not a valid number re-enter.")
If I were to fix the function to do what I think you meant it to do, and document that, it would look like this:
def validate_num() -> int:
"""Returns an integer entered by the user,
re-prompting on invalid input."""
while True:
try:
return int(input("enter a number"))
except ValueError:
print("Not a valid number re-enter.")

Is there a way to check if the try statement was successful or not? [duplicate]

This question already has answers here:
What is the intended use of the optional "else" clause of the "try" statement in Python?
(22 answers)
Closed 1 year ago.
Just started learning python and wanted to make a calculator. I currently have some code that tries to turn what the user inputs into an integer, but what I want to do is be able to check if the attempt was successful or not.
Here is the part i'm having trouble with.
import sys
first_number = input('Enter a number: ')
try:
int(first_number)
except:
print("Sorry, that's not a number.")
exit()
You can just do:
try:
int(first_number)
print("try successful!")
except ValueError:
print("Sorry, that's not a number.")
print("try unsuccessful!")
exit()
You can set a flag after int that is only set on success:
success=False
nums=iter(['abc','123'])
while not success:
try:
x=int(next(nums))
success=True
except ValueError as e:
print(e, 'Try Again!')
print(x)
Prints:
invalid literal for int() with base 10: 'abc' Try Again!
123
First time with 'abc' is an error, second time a success.
Since nums first try is an error, that will not set success to True. Second time is not an error, success is set to True and the while loop terminates. You can use the same method with user input. The iterator is just simulating that...
So for your example:
success=False
while not success:
try:
n_string = input('Enter a number: ')
int(n_string)
success=True
except ValueError as e:
print(f'"{n_string}" is not a number. Try again')
Which is commonly simplified into this common idiom in Python for user input:
while True:
try:
n_string = input('Enter a number: ')
int(n_string)
break
except ValueError as e:
print(f'"{n_string}" is not a number. Try again')
To have this make more sense, make it a function:
def getNumber():
while True:
number = input('Enter a number: ')
if number.isnumeric():
return int(number)
print( "Not a number, please try again." )

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

Errors and Exceptions looping

Hi I want to loop my program so that as soon as it hits Exceptions it restarts from the beginning !
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
How can I do this
You want to remove the break in your try statement. It's telling python to exit the while loop.
try:
x = int(raw_input("Please enter a number: "))
except ValueError:
print "Oops! That was no valid number. Try again..."

Categories