3

I have little problem with try statement along with multiple conditions. When there is error at 2nd condition, it asks for 1st condition. What I want from it to do is to repeat the same condition, not the whole cycle. I hope you understand me, since my English isn't very good and also I'm newbie to Python so I also don't know how to describe it in my native language.

I hope the following example will help you to better understand my thought.

while True:
    try:
        zacatek = float(raw_input("Zacatek: "))
        konec = float(raw_input("Konec: "))
    except Exception:
        pass
    else:
        break

it does following:

Zacatek: 1
Konec: a
Zacatek:  

but I want it to do this:

Zacatek: 1
Konec: a
Konec: 

Thanks in advance for any help.

3 Answers 3

5

Write a function to query for a single float, and call it twice:

def input_float(msg):
    while True:
        try:
            return float(raw_input(msg))
        except ValueError:
            pass
zacatek = input_float("Zacatek: ")
konec = input_float("Konec: ")
Sign up to request clarification or add additional context in comments.

Comments

0

What's happening is that your except clause is catching a ValueError exception on your answer to Konec and returning to the top of the loop.

Your float function is trying to cast a non-numeric response "a" to a float and it throwing the exception.

Comments

0

Alternatively, you could write a different loop for each input:

zacatek = None
while not zacatek:
    try:
        zacatek = float(raw_input("Zacatek: "))
    except Exception:
        continue

konec = None
while not konec:
    try:
        konec = float(raw_input("Konec: "))
    except Exception:
        continue

1 Comment

@delnan: No, it isn't. This version will ask again if I enter '0', mine doesn't.

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.