程序在while循环中卡住不打印
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
7 个回答
除了其他人提到的缩进问题,这段代码在Python的写法上也不是特别标准。usertypetest()
这个函数可以这样写:
def usertypetest(x,y,result):
for x in range(10):
if usertype() == 'Correct':
y = y + 5
else:
y = y - 2
return '%d is your score' % y
当然可能还有更好的写法,但这样写会简单一些,也更符合Python的风格。
我还想说的是,我没有看到示例中提到的输入周围的括号。
如果你想看到每个字母的判断结果,那你需要在最后保存usertype()
的返回值:
def usertypetest(x,y,result):
for x in range(10):
result = usertype()
print result
if result == 'Correct':
y = y + 5
else:
y = y - 2
return '%d is your score' % y
你的主要问题是把if/else的代码放错地方了。你需要把它放在while
的代码块里面。这样做可以确保每次运行usertype()
的时候,都能检查用户输入的是否正确。
import random
moves = 0
score = 0
def usertype():
randletter = random.choice('qwer')
userinput = raw_input('Press '+str(randletter))
if userinput == randletter:
return True
else:
return False
def usertypetest(moves, score):
while moves < 10:
result = usertype()
moves = moves + 1
if result:
score = score + 5
else:
score = score - 2
return str(score) + ' is your score'
print usertypetest(moves, score)
另外,你没有输出变量 result 的值。在计算完 result 之后,添加以下代码:
print result
你需要把 if result == 'Correct':
这段代码放在 while x <= 9:
这个循环里面,也就是你获取用户输入的地方,这样每次都会进行判断。你还可以加上 print(result)
,这样就能像你例子里那样得到正确或错误的反馈:
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
print(result)
return str(y)+'is your score'
在Python中,缩进是非常重要的。
在这段代码中,while
循环里的x
从来没有改变,因为if
块和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