Python Noob: Input returning as none - python

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

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

While loop is not breaking even after the condition is satisfied

I've provided the code below.
What is want to do is run the first input box where it will check the condition if true it will go for next input(), but if not it will run the code again. The problem is first input() is running fine, but second one is not getting out of the loop where I'm checking if the input is integer or not
class AC ():
def __init__(self):
self.owner=input("Enter The Name: ")
while True:
if self.owner.isalpha():
self.balance=(input("Enter The Amount: "))
def lol():
while True:
if self.balance.isdigit():
break
else:
print("Enter The Amount: ")
lol()
break
else:
AC()
break
The problem is that your lol() function is never being called for, so it will stay in the first while-loop indefinitely.
lol() function is never being called as Tim said
input() function return string value you can change str to float
try this:
`
def __init__(self):
self.owner = input("Enter The Name: ")
while True:
if self.owner.isalpha():
self.balance = input("Enter The Amount: ")
def lol():
while True:
try:
self.balance = float(self.balance)
except ValueError:
break
if self.balance.isdigit():
break
else:
lol()
else:
AC()
break

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

How to check is an input that is meant to be an integer is empty(in python)?

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)

Categories