【问题标题】:how to: while True in a function python 3如何:while True 在函数 python 3
【发布时间】:2020-08-06 16:15:14
【问题描述】:

当我使用这段代码时一切正常,但是如何将它放入函数中?

在函数内部时我无法中断部分,总是重复输入中的消息。

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)

【问题讨论】:

  • 请把你的功能代码放在这里。
  • 这很好用,你没有告诉我们什么。另外,更改您可能希望将最后 2 个 if 更改为 elif
  • @Nullman 或者删除最后的 else 以保持一致。这是风格问题。
  • 你尝试了什么输入?你怎么把它放在一个函数中?显示该功能和您的输入。你也可以通过写country in ['HR', 'RO', 'RS']来测试str是否在列表中,这样更清楚
  • @Booboo 这是一个小脚本,所以不是真正的问题,但从逻辑上讲,它会测试每个if,这是一个性能损失(这里可以忽略不计)

标签: python function while-loop


【解决方案1】:

解决方案如下:

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())


【讨论】:

  • Rohan,如果我用这个,就拿 None
  • @JeoBlast 你想说什么?
  • 当输入后打印功能我得到 None 而不是 HR , RO 或 RS
【解决方案2】:

这是 if 语句的有效组合,但如果 str 输入错误,则会重复打印 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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2020-08-10
    相关资源
    最近更新 更多