【问题标题】:Python while-loop conditionsPython while循环条件
【发布时间】:2018-04-08 08:01:55
【问题描述】:

我有一个关于 while 循环中 Python 循环条件的快速问题。我希望以(分数/最高分数)的形式从用户那里获取输入,例如(13/15)。 我希望将其放入一个 while 循环中,该循环将不断要求用户以这种形式输入输入,直到他们做对为止。

到目前为止,我有这个

num1 = 0
while num1 !='?/?':
    num1 = raw_input("Please enter your score in the form socre/max(eg. 30/50)")

我知道如何使用单个数字检查条件是否为真,例如:while x > 18,或者条件是否为字符串,例如:while x != 'Start'。我不确定使用什么作为 15/20 条件的参数,这两个数字将以 15/20 的精确形式输入。任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 我怎样才能看到这个问题的位置。我使用了搜索功能,但找不到类似的东西?
  • 我发现了其他条件,例如单个数字,例如 while x >10 或其他东西。但是我无论如何都找不到检查输入的条件是否格式正确
  • 我已阅读此内容。在这种情况下,条件是简单的形式(x > 18)。所以用户只需要输入大于 18 的数字。我的问题是,如果用户在响应中输入 15/20,如何将条件设置为读取?我用过 while num1 != '?/?': 但这不起作用。 (我使用 ? 作为占位符)

标签: python while-loop conditional-statements


【解决方案1】:

您可以使用正则表达式进行匹配

import re

input_str = input("Please enter your score in the form socre/max(eg. 30/50)")

while re.match(r'[0-9]+/[0-9]+',input_str) == None:
    input_str = input("Please enter your score in the form socre/max(eg. 30/50)")

print('matched')

【讨论】:

  • 谢谢。昨晚我挖了很多东西,最后自己弄明白了。不过,我感谢您的建设性意见:)
【解决方案2】:

代码:

import re
score = input("enter score")
while re.match(r'([0-1][0-5])/15',score) == None:
    score = input("enter score")

这将只取 0 到 15 分(满分 15 分) 如果你想改变这个你可以改变这个条件

[0-1][0-5])/15
[0-1]=stand for first digit
[0-5]=stands for second digit
/15=stands for outof 15

例如,如果你想要超过 30 个

[0-3][0-9])/30

【讨论】:

    【解决方案3】:

    您可以通过以下方式做到这一点:

    while True:
        score_input = input("Please enter your score in the form socre/max(eg. 30/50)")
        try:
            score, max_score = score_input.split('/')
        except ValueError:
            continue
        if score > max_score:
            raise ValueError("Score cannot be greater than max. score")
        # Do whatever you wanto to do with score and max_score and remember to break out.
    

    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2022-12-07
      • 2011-11-02
      • 1970-01-01
      • 2023-01-11
      • 2021-11-25
      • 2019-11-07
      • 2011-12-08
      • 2016-03-15
      • 2016-03-30
      相关资源
      最近更新 更多