在Python中使用not关键字时遇到For循环问题

2024-10-01 09:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这方面做了很多研究,但我不知道我做错了什么。请帮忙!!!你知道吗

课程目标: 不断地问一个问题来为用户选择一个选项,直到用户在提供的列表中选择一个为止。 问题:我就是无法使用not关键字。你知道吗

代码语法:

items = {'1': '2', '3': '4', '5': '6'}
choice = input("Select your item: ")
print(choice)
for choice not in items:
    if choice in items:
        the_choice = items[choice]
        print("You chose",the_choice)
        break
    else:
        print("Uh oh, I don't know about that item")

来自eclipse的错误:

for not choice in items:
          ^
SyntaxError: invalid syntax

Tags: the代码用户in列表for选项not
3条回答
items = {'1': '2', '3': '4', '5': '6'}
choice = ''

while choice not in items:
    choice = input("Select your item: ")
    print(choice)
    if choice in items:
        the_choice = items[choice]
        print("You chose",the_choice)
    else:
        print("Uh oh, I don't know about that item")

只需忽略代码中的not关键字

items = {'1': '2', '3': '4', '5': '6'}
    choice = input("Select your item: ")
    print(choice)
    for choice  in items:
       if choice in items:
        the_choice = items[choice]
        print("You chose",the_choice)
        break
    else:
        print("Uh oh, I don't know about that item")

试试这个:

items = {'1': '2', '3': '4', '5': '6'}

while True:
    choice = input("Select your item: ")
    print(choice)
    if choice in items:
        the_choice = items[choice]
        print("You chose",the_choice)
        break

    print("Uh oh, I don't know about that item")

相关问题 更多 >