【问题标题】:How to take information from input out of a while loop?如何从while循环中获取输入信息?
【发布时间】:2016-12-16 15:38:39
【问题描述】:

我的解释很糟糕,所以我举个例子说明我的意思

s=5
while s >= 3:
    name= input("What is the name of your dog")
    s = s-1

这不是最好的代码,但可以说我想向用户询问一条信息,他们将输入 3 个不同的时间,所以我怎样才能将所有这 3 个值从 while 循环中取出,这样他们就不会得到覆盖?如果我不清楚,请告诉我,我会尝试更好地解释自己

【问题讨论】:

  • 使用list 存储输入
  • 将其包装在一个函数中,并在每次循环中“屈服”

标签: python input while-loop


【解决方案1】:

您可以在 while 循环开始之前创建一个列表,并在每次循环运行时附加一个条目:

s=5
names = []
while s >= 3:
    name= input("What is the name of your dog")
    names.append(name)
    s = s-1

【讨论】:

  • 非常感谢您的快速回复
【解决方案2】:

使用生成器:

names = [input("What is the name of your dog") for i in range(3)]
print(names)

使用列表:

names = []

s = 5
while s >= 3:
    name = input("What is the name of your dog")
    names.append(name)
    s = s - 1

使用产量:

def names():
    s = 5
    while s >= 3:
        yield input("What is the name of your dog")
        s = s - 1

for name in names():
    print(name)

# or

print(list(names()))

为您的任务提供不同的解决方案:

names = input('write all the names: ').split()
print(names)

【讨论】:

  • 鉴于发帖者显然是初学者,我想知道将他们介绍给生成器是否是最好的主意。对于这么小的循环,内存使用不会成为问题,因此创建列表似乎很好
  • 对不起,另一个快速问题继我的最后一个问题之后,我想知道是否有可能打印更改其在列表上打印的值,例如,因为我不知道如何在这里格式化是代码的截图 [link]{puu.sh/qwdu3.png) 'code'
  • 您可以使用lst[-1] 访问最后一个元素,其中lst 是变量的名称。阅读tutorial
  • 我猜第二个while应该是if
【解决方案3】:

使用列表

s=5
name = []
while s >= 3:
    name.append(input("What is the name of your dog"))
    s -= 1

【讨论】:

    【解决方案4】:

    您需要使用一个可以将名称附加到的列表。

    names = list()
    s=5
    while s >= 3:
        names.append(input("What is the name of your dog"))
        s = s-1
    
    print names[0]
    print names[1]
    print names[2]
    

    【讨论】:

    • 它给了我 raw_input 没有定义
    • @rauf543 啊,我只是使用旧版本的python。 input 应该没问题
    猜你喜欢
    • 2022-12-24
    • 2020-08-03
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多