python - 程序卡在 while 循环不打印

标签 python string random input raw-input

import random

def usertype():
    randletter = random.choice('qwer')
    userinput = raw_input('Press '+str(randletter))
    if userinput == randletter:
        return 'Correct'
    else:
        return 'Incorrect'

def usertypetest(x,y,result):
    while x <= 9:
        result = usertype()
    if result == 'Correct':
        x = x+1
        y = y+5
    else:
        x = x+1
        y = y-2
    return str(y)+'is your score'

print usertypetest(0,0,usertype)

这是我的代码。我想让它要求用户按下一个按钮,从集合(Q、W、E、R)中随机选择,然后打印正确或不正确,具体取决于他们按下的按钮。我希望这种情况发生 10 次。十次尝试后,它将打印他们的分数:每个“正确”为 5,“不正确”为 -2。相反,我收到了这个。

Press e(e)
Press e(e)
Press w(e)
Press q(e)
Press q(e)
Press q(e)
Press r(e)
Press e(e)
Press w(e)
Press q(e)
Press e(e)
Press e(e)
Press e(e)
Press e(e)
Press q(e)
Press w(e)
Press r(e)
Press w(e)
Press r(e)
Press w(e)
Press r(e)
Press r(e)

无论我输入什么,它都不会返回“正确”或“不正确”。它也继续过去 10 并且不显示他们的分数。显然存在我没有发现的问题。

我的输入在括号中。

为了澄清,这就是我想要的:

Press q(q)
Correct
Press e(q)
Incorrect
Press w(w)
Correct
Press q(q)
Correct
Press e(eq)
Incorrect
Press e(e)
Correct
Press q(q)
Correct
Press q(r)
Incorrect
Press w(w)
Correct
Press r(r)
Correct
29 is your score

最佳答案

在 Python 中缩进非常重要

在这段代码中,while 循环的 x 永远不会改变,因为 if block 与 while 循环。所以唯一的循环指令是 result = usertype()

while x <= 9:
    result = usertype()
if result == 'Correct':
    x = x+1
    y = y+5

两个额外的批评:

您在两个地方递增 x,而它只需要完成一次。

while x <= 9:
    result = usertype()
    if result == 'Correct':
        y = y+5
    else:
        y = y-2
    x += 1

此外,由于您要循环固定次数,为什么不忽略递增的 x 并使用 for 循环,如下所示:

for x in range(10):
    result = usertype()
    if result == 'Correct':
        y = y+5
    else:
        y = y-2

关于python - 程序卡在 while 循环不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24443879/

相关文章:

python - 从函数返回并继续执行

python - 如何让 Kivy 1.9.1 或 1.9.2 在 OSX 10.12.2 上使用 SDL2 而不是 pygame?

c - strtol 未按预期运行,c

java - 随机数,非均匀分布

python - 使用opencv python检测到地平线的霍夫线后如何裁剪图像?

python - PIL : ValueError: unknown resampling filter, 如何调整上传到Flask的图片大小?

Javascript : Exclude an element from a random set - (curiosity)

random - sparql:为每个节点随机选择一个连接

java - 正则表达式在 2 位数字后分割字符串

C++如何将字符串中的所有 `\`变成 `/`?