我有这个代码显示两个权力:
print ("How many powers of two would you like to see?")
number=int(input())
values=[2]
count=1
while count <= number:
length=len(values)
index=length-1
number=values[index]*2
values.append(number)
count=count+1
print (values)
我的代码正在更新count的值,但它不会突破while循环。
答案 0 :(得分:2)
您在每个while循环中比较count <= number
,但在循环内比number
增加count
。请勿触摸循环中的number
,如下所示:
print("How many powers of two would you like to see?")
number = int(input())
values = [2]
count = 1
while count <= number:
length = len(values)
index = length - 1
number_tmp = values[index]*2
values.append(number_tmp)
count += 1
print(values)
但是更加pythonic的方式是:
print("How many powers of two would you like to see?")
number = int(input())
values = [2**(n+1) for n in range(number)]
print(values)
答案 1 :(得分:1)
如果您在第40次迭代后查看数字的值,count = 40
但是
number = 2199023255552
在第1000次迭代之后,count = 1000
但是
number = 21430172143725346418968500981200036211228096234110672148875007767407021022498722449863967576313917162551893458351062936503742905713846280871969155149397149607869135549648461970842149210124742283755908364306092949967163882534797535118331087892154125829142392955373084335320859663305248773674411336138752
因此,计数永远不会超过number
,循环永远不会中断。您可以通过不更改循环内的number
值来更改此值。