Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try statement - multiple conditions - Python 2

Tags:

python

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.

like image 806
Martin Eliáš Avatar asked Feb 07 '26 08:02

Martin Eliáš


1 Answers

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: ")
like image 56
Sven Marnach Avatar answered Feb 08 '26 21:02

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!