将用户输入存储在列表中并编写循环以从该列表中查找有效值



编码新手...我是一名学生,任务是编写一个代码,要求用户输入一系列值,我将这些值存储在列表中,然后要求输入一个值(继续此操作直到用户键入完成(,然后检查以确定是否在有效值列表中找到它。

我假设

这可以通过一段时间的真循环来完成输入,直到输入"完成",我假设使用"if"和"in"进行搜索将完成第二部分。

我正在努力使用输入列表找到一段时间的真实情况。 我正在使用整数输入。 我将条件与继续循环的条件进行比较吗?

任何帮助不胜感激!下面的代码是我写的,我测试是否可以将输入存储在列表中,但 while true 是我正在努力比较什么的地方。

while True:
    if list_of_inputs
list_of_inputs = input("Write numbers: ").split()
list_of_inputs = list(map(int , list_of_inputs))
print (list_of_inputs)

下面是一些执行注释中描述的代码。

我们使用两个while循环。第一个逐行获取输入行,并将它们添加到list_of_inputs中。如果读取由字符串"done"组成的行,我们将脱离循环,并且我们不会将"done"添加到列表中。

第二个循环获取输入行并测试它们是否存在于list_of_inputs中,打印适当的消息。如果用户输入list_of_inputs中存在的行,我们将脱离循环,程序结束。

print('Please enter values for the list, one value per line')
print('Enter "done" (without the quotes) to end the list')
list_of_inputs = []
while True:
    s = input('value: ')
    if s == 'done':
        break
    list_of_inputs.append(s)
print('Here is the list:')
print(list_of_inputs)
while True:
    s = input('Please enter a test value: ')
    if s in list_of_inputs:
        print('Yes!', repr(s), 'is in the list')
        break
    else:
        print('No', repr(s), 'is NOT in the list')    

试运转

Please enter values for the list, one value per line
Enter "done" (without the quotes) to end the list
value: abc def
value: ghi
value: jkl
value: done
Here is the list:
['abc def', 'ghi', 'jkl']
Please enter a test value: def
No 'def' is NOT in the list
Please enter a test value: ghij
No 'ghij' is NOT in the list
Please enter a test value: jkl
Yes! 'jkl' is in the list

Python 3.x

list_of_inputs = list()
while True:
    var = input("Enter Number or type 'done' to exit :")
    if var.lower() == 'done':
        print(" Your inputs are: ",list_of_inputs)
        exit()
    else:
        list_of_inputs.append(int(var))

确保缩进在 python 代码中正确。

最新更新