简体   繁体   English

Python:如何在用户输入3个无效值后结束程序,并防止以下功能在不使用系统退出/中断的情况下运行?

[英]Python: How to end a program after user inputs 3 invalid values and prevent following functions from running without using system exit/break?

i'm currently taking a programming class and the professor would like us to end all of our programs "logically" so we are not able to use system exits or breaks. 我目前正在上一门编程课,这位教授希望我们“逻辑地”结束所有程序,因此我们无法使用系统退出或中断。 I did this successfully before but the added in factor of functions has halted me as I do not know how I could terminate the program so that the other functions do not run either. 我以前曾经成功完成过此任务,但是由于我不知道如何终止程序以致其他功能都无法运行,因此增加的功能因素使我停顿了下来。 My program just spits out error message but continues to the next calculation, I need it to terminate completely. 我的程序只是吐出错误消息,但继续进行下一个计算,我需要它完全终止。

here is my code: 这是我的代码:

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

thank you in advance!! 先感谢您!!

One solution is to add a global boolean to track whether the user has failed 3 times already or not 一种解决方案是添加一个全局布尔值,以跟踪用户是否已经失败3次

def main():

    notFailedYet = True

    #miles to kilometers input
    miles_km = float(input('Please enter how many miles you would like to convert.'))

Within each function place an if statement to check if they've failed or not 在每个函数中放置一个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.')

While an infinite loop with a break statement is usually the way I've seen this done, it could certainly be done with a loop: 虽然通常用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

Now, when this function returns it'll either return with a properly converted float, or None (in the case max_retries was exceeded). 现在,当此函数返回时,它将以正确转换的浮点数返回,或者返回None(在超过max_retries的情况下)。

So in your main program logic: 因此,在您的主程序逻辑中:

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`.

You will end up with a pretty ugly nested if structure, but it would work. 您最终会看到一个非常难看的嵌套if结构,但是它将起作用。

The other way might be to define "stages": 另一种方法可能是定义“阶段”:

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.

Which would loop and enter a different branch of the if/elif structure until either (a) you've finished all the stages, or (b) one of the stages set err=True (because the return value of prompt_float was None . This is a common programming idiom in languages that support the switch statement, but Python does not so we use if/elif 这将循环并进入if / elif结构的另一个分支,直到(a)您完成了所有阶段,或者(b)其中一个阶段设置err=True (因为prompt_float的返回值为None 。是支持switch语句的语言中常见的编程习惯,但Python不支持,因此我们使用if/elif

In case anyone else is looking at this with the same restrictions I had, here's a part of the updated code that I wrote that works. 万一其他人以与我相同的限制来查看它,这是我编写的有效代码的一部分。 (sorry it's kind of ugly and the comments are unsightly) (对不起,这很难看,评论也不美观)

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)

...and so on and so forth ...等等等等

I nested the functions in ifs in the main function and returned whatever value was determined inside of the conversion functions back to the main function to evaluate if the returned value was greater than 0. if so, the program goes on. 我将函数嵌套在主函数的ifs中,并将转换函数内部确定的任何值返回给主函数,以评估返回的值是否大于0。如果是,则程序继续。 if not, the program exits because of logic. 如果不是,则程序由于逻辑退出。 This can also be done with try and except but for the purpose of the class i'm taking we were only allowed to use what we learned. 这也可以用做tryexcept但我走,我们只允许使用我们所学之类的目的。 so I know there are better or easier ways. 所以我知道有更好或更简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用库和模块的情况下退出 python 程序 - How to exit from a python program without using libraries and modules 要求用户输入浮点值。 如果无效输入超过两次,请使用python退出程序 - Asks user to input floating-point values. If invalid inputs more than twice, quit the program using python 有没有办法在不使用break的情况下结束程序? - Is there anyway to end the program without using break? 如何在没有exit()的情况下脱离__main__ - How to break from `__main__` without exit() 如何在给定时间后终止程序在Python中的运行 - How to end program running after given time in Python 使用Python向正在运行的程序提供输入 - Give inputs to a running program using Python 如何在不使用最流行的函数的情况下跳出我的 while 循环?(sys.exit、break 等) - How do I break out of my while loop without using the most popular functions?(sys.exit,break,etc.) python 处理来自用户的无效输入 - python handling invalid inputs from a user 用户输入选择后如何重复程序 - How to repeat program after user inputs a choice 如何在python中将矩阵乘以向量而不使用任何内置函数,其中向量和矩阵都是来自用户的输入 - How do I multiply a matrix by a vector in python without any built in functions where both the vector and matrix are inputs from the user
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM