Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于数字列表的Python助手_Python - Fatal编程技术网

关于数字列表的Python助手

关于数字列表的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:

用python编写一个输入为正整数的程序,并按顺序显示接下来的十个整数

该函数应返回下一个数字作为给定前一个整数num的整数。如果num为偶数,则该函数应返回num/2。否则它应该返回3*num-1。数字应打印在单独的行上。我没有得到任何语法错误,所以我很困惑

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),这只是一个数字。