简体   繁体   中英

Try statement - multiple conditions - Python 2

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM