【问题标题】:i am working to create a function but this code appears TypeError: 'int' object does not support item assignment我正在创建一个函数,但出现此代码 TypeError: 'int' object does not support item assignment
【发布时间】:2022-01-23 21:55:02
【问题描述】:
def num():
    while True:
        n= int(input("donnez le num"))
        if n > 0:
            break

    T=([int]*n)
    for i in range (0,n):
        n[i]=i
num()
print(T)

代码主要是询问用户一个数字后创建一个表 在这个表中,我想用数字和降序填充它:用户输入 10 个期望的结果:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

this is the code

this is the outpout

【问题讨论】:

    标签: python list function


    【解决方案1】:

    你的代码中有几个问题

    1. 您的代码没有返回任何值,因此 T 没有在函数之外定义
    2. n[i]T[i]
    3. 您需要将范围更改为 n+1
    4. 您可以按如下方式缩短/优化您的代码

    所以:

    def num():
        while True:
            n= int(input("donnez le num"))
            if n > 0:
                break
        return [i for i in range(0,n+1)]
    
    print(num())
    

    等等,输出:

    donnez le num 10
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2015-03-23
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 2018-01-23
      相关资源
      最近更新 更多