Неизбежный цикл while в калькуляторе простых процентов

Я пытался решить задачу № 2 /r/DailyProgrammer, легко https://www.reddit.com/r/dailyprogrammer/comments/pjbj8/easy_challenge_2/ Я пытаюсь сделать это в python, используя функции и серию вложенных if-elif-else, вот мой код:

def interest(initial, rate, years):
    if (type(initial) == int or type(initial) == float) and (type(rate) == int or type(rate) == float) and (type(years) == int or type(years) == float):
        return initial * rate * years
    else:
        return 'Incorrect input type'

def initialAmount(interest, rate, years):
    if (type(interest) == int or type(interest) == float) and (type(rate) == int or type(rate) == float) and (type(years) == int or type(years) == float):
        return interest/(rate * years)
    else:
        return 'Incorrect input type'

def rate(interest, initial, years):
    if (type(initial) == int or type(initial) == float) and (type(interest) == int or type(interest) == float) and (type(years) == int or type(years) == float):
        return interest/(initial * years)
    else:
        return 'Incorrect input type'

def years(interest, initial, rate):
    if (type(initial) == int or type(initial) == float) and (type(rate) == int or type(rate) == float) and (type(interest) == int or type(interest) == float):
        return interest/(initial * rate)
    else:
        return 'Incorrect input type'


I = raw_input("Do you know the amount after interest? If yes, enter it, if not enter 'n':  ")

print I

if I.lower == 'n':
    i = raw_input("Enter your initial amount:  ")
    r = raw_input("Enter your interest rate in decimals:  ")
    t = raw_input("Enter amount of years after initial deposit:  ")
    print "the initial amount is " + i
    print "the interest rate is " + r
    print "the amount of years since the initial deposit is " + t
    while not((type(i) == int) or (type(i) == float)):
        i = raw_input("Enter a valid initial amount:  ")
    while not((type(r) == int) or (type(r) == float)):
        r = raw_input("Enter a valid interest rate in decimals:  ")
    while not((type(t) == int) or (type(t) == float)):
        t = raw_input("Enter a valid amount of years after initial deposit:  ")
    print interest(i, r, t)
elif type(I) == int or type(I) == float:
    i = raw_input("Do you know the amount before interest? If yes, enter it, if not enter 'n':  ")
    if i.lower() == 'n':
        r = raw_input("Enter your interest rate in decimals:  ")
        t = raw_input("Enter amount of years after initial deposit:  ")
        print "the interest rate is " + r
        print "the amount of years since the initial deposit is " + t
        while not(type(r) == int or type(r) == float):
            r = raw_input("Enter a valid interest rate in decimals:  ")
        while not(type(t) == int or type(t) == float):
            t = raw_input("Enter a valid amount of years after initial deposit:  ")
        print initialAmount(I, r, t)
    elif type(i) == int or type(i) == float:
        r = raw_input("Do you know the interest rate? If yes, enter it in decimals, if not enter 'n':  ")
        if r.lower() == 'n':
            t = raw_input("Enter amount of years after initial deposit:  ")
            print "the amount of years since the initial deposit is " + t
            while not(type(t) == int or type(t) == float):
                t = raw_input("Enter a valid amount of years after initial deposit:  ")
            print rate(I, i, t)
        elif type(r) == int or type(r) == float:
            t = raw_input("Do you know the amount of years after the initial deposit? If yes, enter it in decimals, if not enter 'n':  ")
            if t.lower == 'n':
                print years(I, i, r)
            elif type(t) == int or type(t) == float:
                print "I don't know why you needed me then."
            else:
                while not (type(t) == int or type(t) == float):
                    t = raw_input("Enter a valid amount of years after initial deposit:  ")
        else:
            while not (type(r) == int or type(r) == float):
                r = raw_input("Enter a valid interest rate in decimals:  ")
    else:
        while not(type(i) == int or type(i) == float):
            i = raw_input("Enter a valid initial amount:  ")
else:
    while not(type(I) == int or type(I) == float):
        I = raw_input("Enter a valid final amount:  ")

Проблема в том, что как только он попросит вас ввести значение окончательной суммы, независимо от того, вводите ли вы действительное число или введите «n», он всегда помещает вас в бесконечный цикл, запрашивающий у вас действительную окончательную сумму. Я хочу знать, почему он не входит в if или elif, но напрямую входит в неизбежный цикл while.


person Zunon    schedule 02.02.2015    source источник


Ответы (1)


Это логическая ошибка. В цикле while замените «или» на «и».

while not((type(i) == int) and (type(i) == float))

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

person radsine    schedule 02.02.2015
comment
Вы внесли исправление во все экземпляры цикла while? - person radsine; 02.02.2015