简体   繁体   English

try语句-多个条件-Python 2

[英]Try statement - multiple conditions - Python 2

I have little problem with try statement along with multiple conditions. 我对try语句以及多个条件没有什么疑问。 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. 我希望你能理解我,因为我的英语不是很好,而且我还是Python的新手,所以我也不知道如何用母语描述它。

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: 编写一个查询单个float的函数,然后调用两次:

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. 发生的情况是您的except子句在您对Konec的答复中捕获了ValueError异常,并返回到循环的顶部。

Your float function is trying to cast a non-numeric response "a" to a float and it throwing the exception. 您的float函数试图将非数字响应“ a”转换为float并抛出异常。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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