def Collatz(n):
i = 1 # for lables
while n != 1:
print(f'{i}. {n}')
if n & 1:
n = 3 * n + 1
else:
n = n // 2
i+=1
Collatz(777)
#1. 777
#2. 2332
#3. 1166
#4. 583
#5. 1750
#6. 875
#7. 2626
#8. 1313
#...
You can use an extra variable, here i, to print lables.
Also, I removed end parameter so that it print line by line. In addition, I used f-string for printing format. For more detail, please see https://realpython.com/python-f-strings/
def Collatz(n):
i = 1 # for lables
while n != 1:
print(f'{i}. {n}')
if n & 1:
n = 3 * n + 1
else:
n = n // 2
i+=1
Collatz(777)
#1. 777
#2. 2332
#3. 1166
#4. 583
#5. 1750
#6. 875
#7. 2626
#8. 1313
#...
发布评论
评论(1)
您可以使用额外的变量(此处为
i
)来打印标签。另外,我删除了
end
参数,以便它逐行打印。另外,我使用f-string
作为打印格式。有关更多详细信息,请参阅 https://realpython.com/python-f-strings/You can use an extra variable, here
i
, to print lables.Also, I removed
end
parameter so that it print line by line. In addition, I usedf-string
for printing format. For more detail, please see https://realpython.com/python-f-strings/