【问题标题】:Python | IF statment stop script after user input has been made蟒蛇 |用户输入后的 IF 语句停止脚本
【发布时间】:2017-02-22 13:57:15
【问题描述】:

我目前正在使用 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 

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

【问题讨论】:

  • 这是在函数中吗? return?
  • 在循环中立即返回是没有意义的,一般来说,永远不要在 if 语句中定义函数。你的问题还不清楚……你想循环什么?
  • 请不要转发
  • 你能更清楚地解释你想要什么吗?您的问题似乎不清楚。

标签: python loops if-statement


【解决方案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,您可以执行以下操作: 导入系统

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

【讨论】:

  • 如果不是yes/no,我会重复输入
  • @cricket_007 可能是个好电话!让我改变我的答案:)
【解决方案2】:

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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    相关资源
    最近更新 更多