Как ограничить итерации цикла внутри функции? - PullRequest
0 голосов
/ 11 октября 2018

Поскольку мой код в настоящий момент выполняется, ограничения на количество неправильных записей не работают должным образом.

Я попытался запустить его без перерывов, который правильно ограничил итерации, но затемКажется, не распознает, когда после неверного введен действительный ввод (он продолжает цикл «Ввести действительный номер».

При нынешнем разрыве недопустимые записи не ограничиваются какони должны быть. Беглый поиск не дал мне ответа, и я был бы признателен за рекомендации о том, как улучшить функцию моего кода, чтобы я мог использовать эти ограничения (до трех неправильных записей, а затем выход на четвертом).

До того, как я разбил его на функции, он работал правильно.

max = 3
#conversion factors
MILES_TO_KM = 1.6
GALLONS_TO_LITERS = 3.9
POUNDS_TO_KG = .45
INCHES_TO_CM = 2.54

#main conversion function
def main():
    miles = int(input('Enter the number of miles: '))
    miles_to_kms(miles)
    fahrenheit = int(input('Enter the degrees in Fahrenheit: '))
    fahrenheit_to_celsius(fahrenheit)
    gallons = int(input('Enter the number of gallons: '))
    gallons_to_liters(gallons)
    pounds = int(input('Enter the number of pounds: '))
    pounds_to_kgs(pounds)
    inches = int(input('Enter the number of inches: '))
    inches_to_cms(inches)

#define conversion for miles
def miles_to_kms(miles):
    while miles <0:
        for counter in range(4):
            miles = int(input('Enter a valid number of miles: '))
            break
        else:
            print ('Too many invalid entries submitted.')
            exit()
            #I have an issue here (and in the others) where after one invalid entry is given it loops in invalid entries.
    kilometers = miles * MILES_TO_KM
    print(miles, 'mile(s) is equal to', kilometers, 'kilometers.')

#define conversion for fahrenheit
def fahrenheit_to_celsius(fahrenheit):
    while fahrenheit < 0 or fahrenheit >1000:
        for counter in range(max+1):
            fahrenheit = int(input('Enter a valid temperature: '))
            break
        else:
            print ('Too many invalid entries submitted.')
            exit()
    celsius = ((fahrenheit-32)*5/9)
    print(fahrenheit, 'degree(s) Fahrenheit is equal to', celsius, 'degree(s) Celsius.')

#define conversion for gallons
def gallons_to_liters(gallons):
    while gallons <0:
        for counter in range(max+1):
            gallons = int(input('Enter a valid number of gallons: '))
            break
        else:
            print ('Too many invalid entries submitted.')
            exit()
    liters = gallons * GALLONS_TO_LITERS
    print(gallons, 'gallon(s) is equal to', liters, 'liter(s).')

#define conversion for pounds
def pounds_to_kgs(pounds):
    while pounds <0:
        for counter in range(max+1):
            pounds = int(input('Enter a valid number of pounds: '))
            break
        else:
            print ('Too many invalid entries submitted.')
            exit()
    kilograms = pounds * POUNDS_TO_KG
    print(pounds, 'pounds is equal to', kilograms, 'kilograms.')

#define conversion for inches
def inches_to_cms(inches):
    while inches <0:
        for counter in range(max+1):
            inches = int(input('Enter a valid number of inches: '))
            break
        else:
            print ('Too many invalid entries submitted.')
            exit()
    centimeters = inches * INCHES_TO_CM
    print(inches, 'inch(es) is equal to', centimeters, 'centimeter(s).')

main()

1 Ответ

0 голосов
/ 11 октября 2018

Вы сразу прерываете первый цикл, так что я не думаю, что вы этого хотите.

Тогда ваши циклы while будут бесконечными, пока вы вводите недопустимые значения

Попробуйте вместо этого использовать эту структуру.По сути, для большинства «попозже» проще понять, чем для «другого», только для Python

unit = "miles"
conversion_rate = MILES_TO_KM
input_limit = 4 

units = None
for _ in range(input_limit):
    try:
        units = int(input('Enter a valid number of ' + unit +': '))
        if units < 0:
            continue # can't be negative 
        break # exit the loop if input can be made an integer 
    except ValueError:
        continue  # repeat the loop if it can't 
if units is None:
    exit() # out of inputs

return units * conversion_rate
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...