[英]Python: How to end a program after user inputs 3 invalid values and prevent following functions from running without using system exit/break?
我目前正在上一门编程课,这位教授希望我们“逻辑地”结束所有程序,因此我们无法使用系统退出或中断。 我以前曾经成功完成过此任务,但是由于我不知道如何终止程序以致其他功能都无法运行,因此增加的功能因素使我停顿了下来。 我的程序只是吐出错误消息,但继续进行下一个计算,我需要它完全终止。
这是我的代码:
def main():
#miles to kilometers input
miles_km = float(input('Please enter how many miles you would like to convert.'))
#function call
milestoKm(miles_km)
#Fahrenheit to Celsius
fah_cel = float(input('Please enter how many degrees Farenheit you would like to convert.'))
#Function call
FahToCel(fah_cel)
gal_liters = float(input('Please enter how many gallons you would like to convert.'))
#Function call
GaltoLit(gal_liters)
#Pounds to Kilograms
pounds_kg = float(input('Please enter how many pounds you would like to convert.'))
#Function call
PoundsToKg(pounds_kg)
#Inches to Centimeters
inches_cm = float(input('Please enter how many inches you would like to convert.'))
#function call
InchesToCm(inches_cm)
def milestoKm(miles):
tries = 0
while miles <0 and tries <3:
print('Error: enter a valid value')
miles = float(input('Please enter how many miles you would like to convert.'))
tries+=1
if tries ==3 and miles <0:
print('Error: valid value not entered.')
return miles
if tries <=2:
km_miles = (miles *1.6)
return print(miles, 'miles is equal to', format(km_miles ,',.2f'), 'kilometers.')
def FahToCel(faren_deg):
tries = 0
while faren_deg <1000 and tries <3:
print('Error: enter a valid value')
faren_deg = float(input('Please enter how many degrees Farenheit you would like to convert.'))
tries+=1
if tries ==3:
print('Error: valid value not entered.')
return faren_deg
if tries <=2:
cels_deg = ((faren_deg -32) *(5/9))
return print(faren_deg, 'degrees Farenheit is equal to', format(cels_deg, ',.2f'), 'degrees Celsius.')
def GaltoLit(galtoLiters):
tries = 0
while galtoLiters <0 and tries <3:
print('Error: enter a valid value')
galtoLiters = float(input('Please enter how many gallons you would like to convert.'))
tries+=1
if tries ==3:
print('Error: valid value not entered.')
if tries <=2:
liters_gal = (galtoLiters * 3.9)
return print(galtoLiters, 'gallons is equal to', format(liters_gal, ',.2f'), 'liters,')
def PoundsToKg(poundstoKg):
tries = 0
while poundstoKg <0 and tries <3:
print('Error: enter a valid value')
poundstoKg = float(input('Please enter how many pounds you would like to convert..'))
tries+=1
if tries ==3:
print('Error: valid value not entered.')
if tries <=2:
kg_Pounds = (poundstoKg * .45)
return print(poundstoKg, 'pounds is equal to', kg_Pounds, 'kilograms.')
def InchesToCm(inchestoCm):
tries = 0
while inchestoCm <0 and tries <3:
print('Error: enter a valid value')
inchestoCm = float(input('Please enter how many inches you would like to convert.'))
tries+=1
if tries ==3:
print('Error: valid value not entered.')
if tries <=2:
cm_inch = (inchestoCm * 2.54)
return print(inchestoCm, 'inches is equal to', cm_inch, 'centimeters.')
main()
先感谢您!!
一种解决方案是添加一个全局布尔值,以跟踪用户是否已经失败3次
def main():
notFailedYet = True
#miles to kilometers input
miles_km = float(input('Please enter how many miles you would like to convert.'))
在每个函数中放置一个if语句,以检查它们是否失败
if notFailedYet:
tries = 0
while miles <0 and tries <3:
print('Error: enter a valid value')
miles = float(input('Please enter how many miles you would like to convert.'))
tries+=1
if tries ==3 and miles <0:
notFailedYet = False #Set this to false so that the other functions don't execute
print('Error: valid value not entered.')
return miles
if tries <=2:
km_miles = (miles *1.6)
return print(miles, 'miles is equal to', format(km_miles ,',.2f'), 'kilometers.')
虽然通常用break
语句进行无限循环是我所看到的方式,但肯定可以使用循环来完成:
def prompt_float(msg, max_retries=3):
for _ in range(max_retries):
resp = input(msg)
try:
resp = float(resp)
return resp # Only return if float() was successful
except ValueError:
pass # Do nothing
现在,当此函数返回时,它将以正确转换的浮点数返回,或者返回None(在超过max_retries的情况下)。
因此,在您的主程序逻辑中:
miles_km = prompt_float('Please enter how many miles you would like to convert.'))
if miles_km is not None:
milestoKm(miles_km)
fah_cel = prompt_float('Please enter how many degrees Farenheit you would like to convert.'))
if fah_cel is not None:
FahToCel(fah_cel)
# ... more code here, each time indented inside the previous `if`.
您最终会看到一个非常难看的嵌套if结构,但是它将起作用。
另一种方法可能是定义“阶段”:
stage = 1
while (stage <= 5) and (not err):
if stage == 1:
miles_km = prompt_float('Please enter how many miles you would like to convert.'))
if miles_km is not None:
milestoKm(miles_km)
else:
err = True
elif stage == 2:
fah_cel = prompt_float('Please enter how many degrees Farenheit you would like to convert.'))
if fah_cel is not None:
FahToCel(fah_cel)
else:
err = True
elif <...>:
# The rest of your question/processing each in its own `elif stage ==` block.
stage += 1 # Increment `stage` so that next iteration of the while loop
# will enter the next branch of the if/elif ladder.
这将循环并进入if / elif结构的另一个分支,直到(a)您完成了所有阶段,或者(b)其中一个阶段设置err=True
(因为prompt_float
的返回值为None
。是支持switch
语句的语言中常见的编程习惯,但Python不支持,因此我们使用if/elif
万一其他人以与我相同的限制来查看它,这是我编写的有效代码的一部分。 (对不起,这很难看,评论也不美观)
def main():
#miles to kilometers input
miles_km = float(input('Please enter how many miles you would like to convert.'))
#function call
milestoKm(miles_km)
if miles_km >0:
#Fahrenheit to Celsius
fah_cel = float(input('Please enter how many degrees Farenheit you would like to convert.'))
#Function call
FahToCel(fah_cel)
if fah_cel>0:
gal_liters = float(input('Please enter how many gallons you would like to convert.'))
#Function call
GaltoLit(gal_liters)
if gal_liters>0:
#Pounds to Kilograms
pounds_kg = float(input('Please enter how many pounds you would like to convert.'))
#Function call
PoundsToKg(pounds_kg)
我将函数嵌套在主函数的ifs中,并将转换函数内部确定的任何值返回给主函数,以评估返回的值是否大于0。如果是,则程序继续。 如果不是,则程序由于逻辑退出。 这也可以用做try
和except
但我走,我们只允许使用我们所学之类的目的。 所以我知道有更好或更简单的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.