如何使 collatz 的输出看起来像一个列表并带有标签?
How do I make the output of the collatz look like a list and labled?
#I want this code to output....
def Collatz(n):
while n != 1:
print(n, end = ', ')
if n & 1:
n = 3 * n + 1
else:
n = n // 2
print(n)
Collatz(777)
I want it to look like:
- 777
- 2332
- 1166
- 583
您可以在此处 i
使用一个额外的变量来打印标签。
此外,我删除了 end
参数,以便逐行打印。此外,我使用 f-string
作为打印格式。详情请见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
#...
#I want this code to output....
def Collatz(n):
while n != 1:
print(n, end = ', ')
if n & 1:
n = 3 * n + 1
else:
n = n // 2
print(n)
Collatz(777)
I want it to look like:
- 777
- 2332
- 1166
- 583
您可以在此处 i
使用一个额外的变量来打印标签。
此外,我删除了 end
参数,以便逐行打印。此外,我使用 f-string
作为打印格式。详情请见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
#...