如何:在函数中使用while True,python 3

问题描述 投票:0回答:2

当我使用这段代码时,一切都很正常,但如何把它放在一个函数中?

当我在一个函数中时,我无法得到中断部分,总是重复输入的信息。

while True:
    country = input("Enter country of which you want to check pictures HR, RS, RO:  ").upper()
    if country == str("HR"): break
    if country == str("RO"): break
    if country == str("RS"):
        break
    else:
        print("Please enter HR or RO or RS: " + "you wrote: " + country)
python function while-loop
2个回答
0
投票

这是一个if语句的工作组合,但是如果输入了错误的字符串,就会重复打印出 else。

def test(cot):
    while True:
        country = cot
        if country in ['HR', 'RO', 'RS']:
             return country
        else:
            print("Please enter HR or RO or RS: " + "you wrote: " + country)


test1 = test(input("Enter country of which you want to check pictures HR, RS, RO:  ").upper())

0
投票

这就是解决方案。

def Function(cot):
    while True:
        country = cot
        if country == str("HR"): return print("HR")
        if country == str("RO"): return print("RO")
        if country == str("RS"):
            return print("RS")
        else:
            print("Please enter HR or RO or RS: " + "you wrote: " + country)

函数调用

Function(input("Enter country of which you want to check pictures HR, RS, RO:  ").upper())


© www.soinside.com 2019 - 2024. All rights reserved.