从用户输入创建列表{使用无限用户输入}

时间:2015-12-01 21:34:09

标签: python string list

我试图创建一个函数定义,要求用户输入要添加到空列表中的int或float值,但继续询问用户输入,直到用户输入-1左右为止(小于0)。

这是我到目前为止所做的,但它所做的只是取用户的输入并在新列表中将其复制5次[范围(5)],并且不允许用户使用再输入值......

即使我觉得它应该很容易,我也很困难:

def main():
    salesList = []
    salesValue = float(input('Please enter total sales in your department: '))
    while salesValue < 0:
        salesValue = float(input('Please enter a value greater than or equal to zero: '))
        if salesValue == -1:
            break
    else:
        for values in range(5):
            salesList.append(salesValue)
    print(salesList)



main()

任何指导都将非常感谢,因为我是编程新手。

:::简单的解决方案:::

    def makeList():
        salesList = []
        while True:
            salesValue = float(input('Please enter total sales in your department: '))
            if salesValue == -1:
                break        
            salesList.append(salesValue)
        return salesList

3 个答案:

答案 0 :(得分:0)

# here you are saying, for 5 iterations do the following
for values in range(5):
    # append the single float value salesValue to salesList
    # naturally this will happen 5 times
    salesList.append(salesValue)

所以你最终得到一个包含的列表是完全合理的 salesValue五次结束。

想一想:

while True: # will loop until a break
    salesValue = float(input('Please enter a value greater than or equal to zero (-1 to end): '))
    if salesValue < 0:
        break
    else:
        salesList.append(salesValue)

答案 1 :(得分:0)

您当前的代码有错误。基本上,当流程最终到达for语句时,salesValue的值不会更改,因此程序会将相同的值追加5次。试试这个:

def main():
    salesList = []
    salesValue = float(input())
    while salesValue < 0:
        salesvalue = float(input())
        if salesValue == -1:
            break
    for values in range (5):
        salesList.append(salesValue)
        salesValue = float(input("yourmessage"))
    print salesList

main()

答案 2 :(得分:0)

你想要

while salesValue > 0:

而不是

while salesValue < 0:

正如你现在所写的那样,用户输入一个大于0的值,它会自动将其踢入else块。您将能够删除

if salesValue == -1:
        break