1

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!

4
  • Did you try Googling your question's title? Commented Aug 23, 2015 at 21:50
  • I did! I've been trying but none worked.. That's where I got what I have already.. Commented Aug 23, 2015 at 21:53
  • That dupe is actually terrible Commented Aug 23, 2015 at 22:08
  • The dupe question is terrible but the answer is good. Commented Aug 23, 2015 at 22:15

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.