我是Python的新手,想要知道如何使用if语句来结束一个程序来打印一条消息,因为当我的'stand'变量低于<时,它似乎不会发生。 5000. if语句加粗** **是我遇到问题的代码,它仍然打印出我想要的消息,但是,程序不会停止该消息,而是继续转到下一个代码(倒计时变量)。忽略'倒计时'。
这是我的代码的一部分。
while stand <= 0 or mission > 10000:
try:
stand = int(input("Enter a VALID distance in metres: "))
except ValueError:
print("Please enter a valid distance E.g 6000: ")
**if stand > 0 or stand < 5000:
print("ERROR, ERROR")
print("Launch cannot begin, the Mission Control and spectator stands are dangerously close at a distance of {}m.".format(mission))
print("This launch site sucks! It must be demolished and rebuilt!")
print("Launch delayed.")**
if stand >= 5000:
print("Fortunately the mission control and viewing stands are situated far enough.")
while countdown == 0 or countdown == "":
print("We need a person to countdown.")
try:
countdown = int(input("How many seconds would you like the countdown to be?: "))
except ValueError:
答案 0 :(得分:1)
使用break
退出循环。
if stand > 0 or stand < 5000:
print("ERROR, ERROR")
print("Launch cannot begin, the Mission Control and spectator stands are dangerously close at a distance of {}m.".format(mission))
break
使用exit
退出程序。
import sys
if stand > 0 or stand < 5000:
print("ERROR, ERROR")
print("Launch cannot begin, the Mission Control and spectator stands are dangerously close at a distance of {}m.".format(mission))
sys.exit(0)
答案 1 :(得分:0)
您可以将代码置于正常运行状态。一个函数,您可以返回不同的值。在调用函数时,您可以检查返回的函数。 您可以使用if
之类的条件def func1():
while stand <= 0 or mission > 10000:
try:
stand = int(input("Enter a VALID distance in metres: "))
except ValueError:
print("Please enter a valid distance E.g 6000: ")
**if stand > 0 or stand < 5000:
print("ERROR, ERROR")
print("Launch cannot begin, the Mission Control and spectator stands are dangerously close at a distance of {}m.".format(mission))
print("This launch site sucks! It must be demolished and rebuilt!")
print("Launch delayed.")
return 1**
if stand >= 5000:
print("Fortunately the mission control and viewing stands are situated far enough.")
while countdown == 0 or countdown == "":
print("We need a person to countdown.")
try:
countdown = int(input("How many seconds would you like the countdown to be?: "))
except ValueError:
r = func1()
if r == 1:
print 'Error'
答案 2 :(得分:0)
我们可以在if语句中使用break语句来终止。我们可以编写os.exit或sys.exit
而不是breakos._exit调用C函数_exit(),它立即终止程序。请注意声明“永远不会返回”。
sys.exit()与引发SystemExit()相同。它引发了一个Python异常,可能被调用者捕获。
import os
if stand > 0 or stand < 5000:
print("ERROR, ERROR")
print("Launch cannot begin, the Mission Control and spectator stands are dangerously close at a distance of {}m.".format(mission))
os.exit(0)