我已经开始写"Automate The Boring Stuff" by 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
循环只运行一次?
例如,使用return
语句将整数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)
发布于 2015-10-25 07:30:33
return
退出函数,因此终止您的while
循环。
也许您的意思是使用yield
:
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
yield(n)
else:
n = n * 3 + 1
yield(n)
print(list(collatz(user)))
输出:
This is The Collatz Sequence
Enter a number: 3
3
[10, 5, 16, 8, 4, 2, 1]
Yield在逻辑上类似于return
,但是直到到达定义的return
或函数的结尾时,函数才会终止。当yield statement被执行时,生成器函数被挂起,yield expression的值返回给调用者。一旦调用者完成(假设使用了发送的值),执行就会紧跟在yield
语句之后返回生成器函数。
发布于 2017-01-16 10:32:53
在您的代码中,您不会将新值重新反馈到您的方程式中。尝试将while循环与collatz模块分开。我有一个这样的例子:
def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
chosenInt = int(input('Enter an integer greater than 1: '))
print(chosenInt)
while chosenInt != 1:
chosenInt = collatz(chosenInt)
print(chosenInt)
发布于 2020-03-24 03:17:16
def collatz(number):
if (number%2 == 0):
return print(number//2);
else:
return (print(number*3+1));
inputNumber = input("Enter a number greater than 1:");
result = collatz(int(inputNumber));
while result != 1:
result = collatz(result);
我正在用它得到一个typeError!不知道为什么?
https://stackoverflow.com/questions/33324432
复制相似问题