簡體   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?

我目前正在上一門編程課,這位教授希望我們“邏輯地”結束所有程序,因此我們無法使用系統退出或中斷。 我以前曾經成功完成過此任務,但是由於我不知道如何終止程序以致其他功能都無法運行,因此增加的功能因素使我停頓了下來。 我的程序只是吐出錯誤消息,但繼續進行下一個計算,我需要它完全終止。

這是我的代碼:

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。如果是,則程序繼續。 如果不是,則程序由於邏輯退出。 這也可以用做tryexcept但我走,我們只允許使用我們所學之類的目的。 所以我知道有更好或更簡單的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM