My code distinguishes whether the input is valid or not. It's not supposed to accept zero or words. If the user plugs zero in, it works and says "anything but zero", "try again" BUT when it asks again, it accepts anything. What do I do to make it continue to ask until there is a valid input??
So far I got:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
except ValueError:
print "HEY! that is not a float!"
A = raw_input("Try again")
Please help! Thank you all!
You need to use a loop:
while True:
A = raw_input('Enter A:')
try:
A = float(A)
except ValueError:
print "enter a float!"
else:
if A == 0:
print "Enter not 0"
else:
break
The simplest approach is use a while loop and to move all the logic inside the try breaking if the cast is successful and not equal to 0:
while True:
try:
A = float(raw_input('Enter A: '))
if A != 0:
break
print "anything but zero"
except ValueError:
print "HEY! that is not a float!"
If you actually only want integers you should be casting to int not float.
Use a while loop:
valid = false
while not valid:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
else:
valid = true
except ValueError:
print "HEY! that is not a float!"
A = raw_input("Try again")
Hope this helps :)
while 1==1:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
else:
#valid input
break
except ValueError:
print "HEY! that is not a float!"
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'
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)
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?
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
flag = True
while flag != False:
numInput = raw_input("Enter your first number: ")
if is_number(numInput):
numInput = float(numInput)
flag = True
break
else:
print "Error, only numbers are allowed"
I do not see the problem.
Why doesn't it enter a loop?
Doesn't print anything, just gets stuck.
flag = False is not required here:
else:
print "Error, only numbers are allowed"
flag = False <--- remove this
Simply use:
while True:
numInput = raw_input("Enter your first number: ")
if is_number(numInput):
numInput = float(numInput)
break
else:
print "Error, only numbers are allowed"
demo:
Enter your first number: foo
Error, only numbers are allowed
Enter your first number: bar
Error, only numbers are allowed
Enter your first number: 123
try this:
while True:
numInput = raw_input("Enter your first number: ")
try:
numInput = float(numInput)
break
except:
print "Error, only numbers are allowed"
I have a raw_function looks like:
number = raw_input('number (empty to finish): ')
if len(number) == 0:
print
print
print 'finished'
print
print
return def()
else:
pass
while True:
try:
column2 = int(raw_input('Enter column: '))
break
except ValueError:
print 'You did not supply an integer. Please try again. '
When i finish answering my second raw_input, I would like to return to first raw_input.
How can I do this?
Thanks in advance.
while True:
number = raw_input('number (empty to finish): ')
if not number:
print "\n\nfinished\n\n\n"
return def()
while True:
try:
column2 = int(raw_input('Enter column: '))
break
except ValueError:
print 'You did not supply an integer. Please try again. '