Python |用户输入完成后,IF语句停止脚本

时间:2017-02-22 13:57:15

标签: python loops if-statement

我目前正在使用Python进行自动故障排除。下面是我需要帮助的一段脚本。

s1 = input("Is your phone freezing/stuttering? ")
if s1 == "Yes" or s1 == "yes":
    print("Try deleting some apps and this might help with your problem.") 
if s1 == "No" or s1 == "no":
    def foo():
        while True:
            return False 

所以我想要发生的是我的脚本在用户键入YES时以及修复解决方案出现时停止。是否存在类似的循环?此外,如果用户输入NO,那么我希望脚本继续下一个问题。

2 个答案:

答案 0 :(得分:1)

所以你可以做的一件事就是利用sys

因此,您可以将程序修改为如下所示:

import sys

s1 = input("Is your phone freezing or stuttering (yes/no)? ")

if s1.lower() == "yes":
    print("Deleting some apps and this might help!")

elif s1.lower() == "no":
    print("Your phone is working fine! Program is terminating.")
    sys.exit(0) # this exits your program with exit code 0

sys包非常适合程序控制并且还可以与解释器进行交互。请详细了解here

如果您不希望程序退出,而您只想检查用户是否输入了no,则可以执行以下操作:     import sys

s1 = input("Is your phone freezing or stuttering (yes/no)? ")

if s1.lower() == "yes":
    print("Deleting some apps and this might help!")

elif s1.lower() == "no":
    pass

else:
    # if the user printed anything else besides yes or no
    print("Your phone is working fine! Program is terminating.")
    sys.exit(0) # this exits your program with exit code 0

如果我能以任何其他方式提供帮助,请告诉我!

修改

crickt_007的评论表明,重复输入并不断查询用户可能会有所帮助。你可以将整个函数包装在while循环中。

import sys

while True:
    s1 = input("Is your phone freezing or stuttering (yes/no)? ")

    if s1.lower() == "yes":
        print("Deleting some apps and this might help!")
        # solve their issue

    elif s1.lower() == "no":
        # supposedly move on to the rest of the problem
        pass

    else:
        # if the user printed anything else besides yes or no
        # maybe we want to just boot out of the program
        print("An answer that is not yes or no has been specified. Program is terminating.")
        sys.exit(0) # this exits your program with exit code 0

答案 1 :(得分:0)

while循环听起来像你在寻找什么?

import sys

s1 = "no"
while s1.lower() != 'yes':
    input("Is your phone freezing/stuttering? ")
    if s1.lower() == 'yes':
        print("Try deleting some apps and this might help with your problem.")
        sys.exit(0)
    elif s1.lower() == 'no':
        print("something")
    else:
        print("invalid input")