【问题标题】:Can I make a changing input message from a list in a for loop我可以从 for 循环中的列表中更改输入消息吗
【发布时间】:2019-04-04 13:25:25
【问题描述】:

我正在创建一个代码,其中有一个包含姓名的列表,并且代码询问每个人的年龄。是否可以创建一个 for 循环输入,消息始终根据名称更改?

我尝试了打印语法,但它似乎不起作用:

ages = [0] * 3

names = ["Julia", "Benjamin", "George"]

for i in range (0, 3):
    ages[i] = int(input("How old is", names[i]))

print(ages)

预期的输出将是一个包含年龄的列表,例如:

[23, 19, 34]

但我只收到一条错误消息:

TypeError: raw_input() takes from 1 to 2 positional arguments but 3 were given.

感谢您的帮助!

【问题讨论】:

  • 使用字符串格式或连接。

标签: python list for-loop input


【解决方案1】:

inputprint使用的语法不同,所以不能写:

input("How old is", names[i]) # doesn't work!!

但你必须输入一个完整的字符串,比如:

input("How old is {}?".format(names[i]))

请注意,您可以(并且应该)在循环时避免使用索引:

names = ["Julia", "Benjamin", "George"]
ages = []

for name in names:
    ages.append(int(input("How old is {}?".format(name)))

print(ages)

【讨论】:

    【解决方案2】:

    只需换行:

    ages[i] = int(input("How old is", names[i]))
    

    作者:

    ages[i] = int(input("How old is" + names[i]))
    

    原因是你用“+”创建了一个新字符串, 所以它只算作 1 个参数。

    【讨论】:

      【解决方案3】:

      只需使用字符串格式:

      input(f"How old is {names[i]}?")
      

      【讨论】:

        【解决方案4】:

        试试这个:

        for i in range (0, 3):
            ages[i] = int(input("How old is "+names[i]))
        

        输出

        How old is Julia20
        How old is Benjamin50
        How old is George8
        >>> ages
        [20, 50, 8]
        

        【讨论】:

          【解决方案5】:

          试试这个:

          ages[i] = int(input("How old is " + names[i]))
          

          【讨论】:

            【解决方案6】:

            您通过用逗号分隔两个参数给 input()。试试

            for i in range (0, 3):
                ages[i] = int(input("How old is " + names[i]))
            

            for i in range (0, 3):
                ages[i] = int(input("How old is {}".format(names[i])))
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-02-05
              • 2013-08-03
              • 2012-04-15
              • 2015-01-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-03-10
              相关资源
              最近更新 更多