我试图在Python中使用while循环来提供错误消息,同时用户输入中有反斜杠字符。输入分数并请求第二个输入时,代码提供错误消息。当第二个输入的长度与原始输入不同,我不知道如何解决这个问题,因为我的Python知识有限。任何帮助表示赞赏!
size = getInput('Size(in): ')
charcount = len(size)
for i in range(0,charcount):
if size[i] == '/':
while size[i] == '/':
getWarningReply('Please enter size as a decimal', 'OKAY')
size = getInput('Size(in): ')
elif size[i] == '.':
#Convert size input from string to list, then back to string because strings are immutable whereas lists are not
sizechars = list(size)
sizechars[i] = 'P'
size = "".join(sizechars)
答案 0 :(得分:0)
这不是一个好的方法去做你想要的事情,因为如果新size
的长度比原始长度charcount
短,那么你很容易超出范围。
我绝不是一个Python大师,但更容易做到这一点的方法是将整个事物包裹在while循环中,而不是在for循环中嵌套while循环:
not_decimal = True
while not_decimal:
found_slash = False
size = getInput('Size(in): ')
charcount = len(size)
for i in range(0, charcount):
if size[i] == '/':
print 'Please enter size as a decimal.'
found_slash = True
break
elif size[i] == '.':
#Convert size input from string to list, then back to string because strings are immutable whereas lists are not
sizechars = list(size)
sizechars[i] = 'P'
size = "".join(sizechars)
if not found_slash:
not_decimal = False