У меня проблемы с циклами while, это, вероятно, очень простое решение глупого вопроса. Таким образом, я могу входить и выходить из первого цикла while без проблем с пользовательским вводом. Моя проблема заключается в циклах, которые вложены.
Я хочу, чтобы пользователь мог подтвердить свой ввод, если он допустил ошибку, и иметь возможность вернуться и исправить ее, если это необходимо. Что происходит, если вводится «n», а не ломается и возвращается к началу, как я хотел бы, ведет себя как «продолжить».
любая помощь или советы были бы замечательными
#Эта программа определяет, сколько времени потребуется, чтобы инвестиции удвоились при заданной процентной ставке.
import time
import math
company_name = ("DM Investments")
print("Welcome to",company_name,"your personal resource for all your investment needs.\n")
time.sleep(2)
print("The following will allow you to determine approximately how long it will take for\nyour investment to double at a given interest rate, utilizing the Rule of 72.\n")
time.sleep(2)
print("First, we will collect the initial value of your expected investment.\n")
time.sleep(2)
print("Secondly, we will collect the interest rate that your financial institution has provided you.\n")
time.sleep(2)
print("Lastly, we will calculate the time needed for your initial investment to double at the reported interest rate.\n")
time.sleep(2),print("The greater the interest rate; the more accurate the results")
print("NOTE: This is only a tool, no guarantee is made.\nSpeak with an investment professional here at",company_name,"\nINVEST AT YOUR OWN RISK")
time.sleep(2)
while True:
if input('\nDo You Wish To calculate the time needed to double your investment? (y/n): ') != 'y':
break
while True:#start a loop to be able to repeat the below lines of code
initial_invest = float(input("Please enter your initial investment dollar amount: $").replace(',',''))
#return to initial investment input or continue
answer = str(input("Was the correct amount input? (y/n): "))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
break
doubled_invest = float(initial_invest*2)
time.sleep(1)
print()
print("The dollar amount to reach, in order to double your investment will be ${:,.2f}".format(doubled_invest),"\n")
if answer == "n":
return(initial_invest)
while True:#return to initial interest input or continue
interest_rate = float(input("Please enter the interest rate or point value that your financial institution has provided you:\n %\r"))
answer = str(input("Was the correct rate input? (y/n): "))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue #move on to next section of code if statement is valid
irfix = float(interest_rate/100)#changes % to decimal for math function
T = (math.log(2) / math.log(1+irfix))#Rule of 72 math
print("In order to reach ${:,.2f}".format(doubled_invest),"you will need to keep your investment active for", T, " years at the interest rate of", interest_rate)
if input('\nDo You Wish To calculate again? (y/n): ') != 'y':
break
while True:#start of loop to be able to repeat the below lines of code
while True:#return to length input or finish the program to exit.
answer = str(input('Would you like to input a different interest rate? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
break #end program
'''
1 ответ
Пожалуйста, посмотрите несколько примеров функций ниже — должно помочь разобраться. По общему признанию, мой питон немного ржавый (не каламбур;))… но, надеюсь, это поможет..
return(initial_invest)
должно быть print(initial_invest)
вместо «возврата», если у вас нет его в функции. '''
внизу также кажется, что код не работает должным образом.
Я бы переместил вопросы к определениям функций. Например, вот пара, которая должна работать (я думаю) так, как вы хотите — обратите внимание, что я поменял пару вещей и скорректировал логику проверки ошибок. Это должно вам помочь — дайте мне знать, если вы застряли или вам нужна дополнительная помощь. Вы должны добавить некоторую проверку ошибок, чтобы убедиться, что суммы в долларах и процентные суммы являются действительными числами с плавающей точкой/целыми числами и т. д.
def inputInterestRate():
while True:#return to initial interest input or continue
interest_rate = float(input("Please enter the interest rate or point value that your financial institution has provided you:\n %\r"))
answer = str(input("Was the correct rate input? (y/n): "))
if answer not in ('y', 'n'):
print("invalid input.")
break
if answer == 'y':
irfix = float(interest_rate/100)#changes % to decimal for math function
T = (math.log(2) / math.log(1+irfix))#Rule of 72 math
print("In order to reach ${:,.2f}".format(doubled_invest),"you will need to keep your investment active for", T, " years at the interest rate of", interest_rate)
if input('\nDo You Wish To calculate again? (y/n): ') != 'y':
break
else:
continue
def inputDifferentInterestRate():
while True:#return to length input or finish the program to exit.
answer = str(input('Would you like to input a different interest rate? (y/n): '))
if answer not in ('y', 'n'):
print("invalid input.")
break
if answer == 'y':
inputInterestRate()
else:
print("okay then.. skipping.")
break #end program
inputDifferentInterestRate()
Пример выше:
Would you like to input a different interest rate? (y/n): y
Please enter the interest rate or point value that your financial institution has provided you:
%
3.5
Was the correct rate input? (y/n): y
In order to reach $20.00 you will need to keep your investment active for 20.148791684000713 years at the interest rate of 3.5
Do You Wish To calculate again? (y/n): y
Please enter the interest rate or point value that your financial institution has provided you:
%
10
Was the correct rate input? (y/n): y
In order to reach $20.00 you will need to keep your investment active for 7.272540897341713 years at the interest rate of 10.0
Do You Wish To calculate again? (y/n): y
Please enter the interest rate or point value that your financial institution has provided you:
%
2
Was the correct rate input? (y/n): n
Please enter the interest rate or point value that your financial institution has provided you:
%
3
Was the correct rate input? (y/n): n
Please enter the interest rate or point value that your financial institution has provided you:
%
4
Was the correct rate input? (y/n): y
In order to reach $20.00 you will need to keep your investment active for 17.672987685129698 years at the interest rate of 4.0
Do You Wish To calculate again? (y/n): n
Would you like to input a different interest rate? (y/n): n
okay then.. skipping.
Sᴀᴍ Heᴇᴌᴀ