如果满足else条件,则循环if语句

时间:2020-07-21 02:45:08

标签: python loops if-statement

因此,我有一个If-elif语句,如果要满足else条件,我想打印一些文本并循环。这是代码:

print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for specific user data\n3. kwin - Search a keyword in a specific user\n4. allin - Search for all data by and mentioning a user")

search_mode = input("How would you like to search?: ")

if "s" in search_mode:
    kwsearch = input("What Keyword do you want to use?: ")
elif "u" in search_mode:
    username = input("What is the username?: ")
elif "kwin" in search_mode:
    kwinuser = input("What is the username?: ")
    kwinword = input("What is the keyword?: ")
elif "allin" in search_mode:
    allinuser = input("What is the username?: ")
else:
    print("Error. Please check spelling and capitalization")

当人们搞砸了并且没有正确放置其中一个选项时,我想循环回到if语句,以便当他们放置正确的选项时,循环将结束,其余代码将继续。

我尝试了一个for循环并将其包装为一个函数,但是最终将导致打印错误消息的无限循环。有没有一种方法可以使用while循环?我需要阻止它并重复执行该功能吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

在Python中,为此我看到的最惯用的东西是while True

while True:
    search_mode = input("How would you like to search?: ")
    if "s" in search_mode:
        kwsearch = input("What Keyword do you want to use?: ")
    elif "u" in search_mode:
        username = input("What is the username?: ")
    elif "kwin" in search_mode:
        kwinuser = input("What is the username?: ")
        kwinword = input("What is the keyword?: ")
    elif "allin" in search_mode:
        allinuser = input("What is the username?: ")
    else:
        print("Error. Please check spelling and capitalization")
        continue
    break

答案 1 :(得分:0)

您可以使用while循环和break语句。当我看到重复的代码时,还可以减少elif语句。

此外,您可以通过将search_mode转换为小写字母来减少用户错误。

print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for 
specific user data\n3. kwin - Search a keyword in a specific user\n4. allin - 
Search for all data by and mentioning a user")

search_mode = input("How would you like to search?: ")

while True:
    if "s" in search_mode.lower():
        kwsearch = input("What Keyword do you want to use?: ")
        break
    elif search_mode.lower() in ('u','kwin','allin'):
        username = input("What is the username?: ")
        if "kwin" in search_mode.lower():
            kwinword = input("What is the keyword?: ")
        break
    else:
        print("Error. Please check spelling and capitalization")
        search_mode = input("How would you like to search?: ")

代码在将值接受到变量search_mode中之后进入while循环。

如果值为“ s”,则会要求输入关键字并中断循环。

如果该值不是's',则它检查该值是'u'还是'kwin'或'allin'。如果其中任何一个,则要求输入用户名。如果值是kwin,它也会要求输入关键字。然后它打破了循环。

如果该值不是以上任何一项,它将打印错误语句并再次询问用户问题。它使用来自用户的新值再次进入循环,并再次检查条件。仅当if或elif语句为true时,它将退出。希望这会有所帮助。