Python while 循环反混淆
Python counter confusion for while loop
import random, string
goal='methinks it is like a weasel'
def simulation(length):
return ''.join(random.choice('abcdefghijklmnopqrstuvwxyz ') for i in range(length))
def score(stri):
if stri==goal:
print(100)
else:
print(0)
n=0
stri='abcd'
while score(stri) != 100:
n += 1
stri = simulation(28)
print(n)
最后的while循环,只要score(stri)不等于100,就会迭代累加n,对吗?然后我将打印出累积的 n ,当 score(stri) 恰好等于 100.
但我得到的结果如下:
0
0
0
0
0
0
...
显然它总是输出'n=0';因为这是全局变量?
但我随后尝试了非常简单的 while 循环:
n=0
while n <= 5:
n += 1
print(n)
成功输出6
我不知道为什么我的第一个代码出错了,猜测 while 循环出错是因为 def()
?
您需要从 score
return 而不是打印:
def score(stri):
if stri == goal:
return 100
else:
return 0
这里失败了while score(stri) != 100:
因为当你调用函数score
时它只是打印(显示输出)而不是return在while循环中使用一个值健康)状况。
import random, string
goal='methinks it is like a weasel'
def simulation(length):
return ''.join(random.choice('abcdefghijklmnopqrstuvwxyz ') for i in range(length))
def score(stri):
if stri==goal:
print(100)
else:
print(0)
n=0
stri='abcd'
while score(stri) != 100:
n += 1
stri = simulation(28)
print(n)
最后的while循环,只要score(stri)不等于100,就会迭代累加n,对吗?然后我将打印出累积的 n ,当 score(stri) 恰好等于 100.
但我得到的结果如下:
0
0
0
0
0
0
...
显然它总是输出'n=0';因为这是全局变量?
但我随后尝试了非常简单的 while 循环:
n=0
while n <= 5:
n += 1
print(n)
成功输出6
我不知道为什么我的第一个代码出错了,猜测 while 循环出错是因为 def()
?
您需要从 score
return 而不是打印:
def score(stri):
if stri == goal:
return 100
else:
return 0
这里失败了while score(stri) != 100:
因为当你调用函数score
时它只是打印(显示输出)而不是return在while循环中使用一个值健康)状况。