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.")
Related
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'
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." )
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = int(input(output_message))
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
As you can see here the code is supposed to check if an input is an integer and it is above a certain value which by default is 0, but could be changed.
When the user inputs random letters and symbols it see that there is a value error and returns "Integers only!(Please do not leave this blank)".
I want to be able to check if the user inputs nothing, and in that case only it should output "This is blank/empty", the current way of dealing with this is to not check at all and just say "Integers only!(Please do not leave this blank)", in case there us a value error. I want to be able to be more specific and not just spit all the reasons at once. Can anyone please help me?
Thanks in advance.
You could do something like this :
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!", above=0, error_3="Please do not leave this blank"):
while True:
user_input = input(output_message)
try:
user_input = int(user_input)
if user_input >= above:
return user_input
break
else:
print(error_1.format(above))
except ValueError:
if(not user_input):
print(error_3)
else:
print(error_2)
I moved the input outside the try/except block to be able to use it in the except ! This worked fine for me, I hope this is what you needed.
You could just break the input and the conversion to int into two steps, like this:
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = input(output_message)
if not user_input:
print("Please do not leave this blank")
continue
user_input = int(user_input)
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
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")
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().