我已经开始阅读Al Sweigart的"自动化无聊的事情"。
在第3章末,作者建议用Python创建Collatz序列作为练习。 (练习建议使用print函数和return语句)
当我在我的代码中使用print()函数时,它很好地工作,并且我可以在屏幕上看到所有评估过的值:
print("This is The Collatz Sequence")
user = int(input("Enter a number: "))
def collatz(n):
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
print(n)
else:
n = n * 3 + 1
print(n)
collatz(user)
问题:
为什么当我想使用return
语句时,while
循环只运行一次?
例如,将整数3传递到我的函数中并使用return
语句只会给我返回值3和10:
print("This is The Collatz Sequence")
user = int(input("Enter a number: "))
def collatz(n):
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
return n
else:
n = n * 3 + 1
return n
result = collatz(user)
print(result)