关于数字列表的Python助手
用python编写一个输入为正整数的程序,并按顺序显示接下来的十个整数 该函数应返回下一个数字作为给定前一个整数num的整数。如果num为偶数,则该函数应返回num/2。否则它应该返回3*num-1。数字应打印在单独的行上。我没有得到任何语法错误,所以我很困惑关于数字列表的Python助手,python,Python,用python编写一个输入为正整数的程序,并按顺序显示接下来的十个整数 该函数应返回下一个数字作为给定前一个整数num的整数。如果num为偶数,则该函数应返回num/2。否则它应该返回3*num-1。数字应打印在单独的行上。我没有得到任何语法错误,所以我很困惑 def f(x): numlist = [x] if x%2 == 0: numlist.append(int(x/2)) else:
def f(x):
numlist = [x]
if x%2 == 0:
numlist.append(int(x/2))
else:
numlist.append(int(x*3 - 1))
numlist.remove(x)
return numlist
number = int(input())
for i in f(number):
print(i)
这里有几件事值得一提:
错误。循环在您的案例中迭代iterable对象f(x)
返回一个iterable的列表,但它没有任何意义。因为列表中只有一个值
整数
,并在for循环中运行f(x)
10次def f(x):
# No need to use List here you just want to return one integer
if x%2 == 0:
x = int(x/2)
else:
x = int(x*3 - 1)
return x
number = int(input())
per = f(number)
# Your For loop was wrong. This is how it should be
for i in range(10):
print(per, end=' ') # print result
per = f(per) # calculate next result
输出:
97
290 145 434 217 650 325 974 487 1460 730
困惑什么?您是否得到不正确的输出?请粘贴您得到的输出。欢迎使用StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确指定问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您指定的问题。如果您想要像x、f(x)、f(f(x))、f(f(x))这样的序列,则需要某种递归或循环。目前,您正在循环f(x),这只是一个数字。