[英]Python while-loop conditions
我只是对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输入。 任何帮助将不胜感激。
谢谢
您可以使用正则表达式进行匹配,例如
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')
编码 :
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
您可以通过以下方式进行操作:
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.
我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.