C the Great
C the Great

Reputation: 13

Interest Calculator looping issue Python

beginner here. I've made an interest calculator program to help me with my loans of different sorts. I'm having two issues to finalize my program. Here's the program. I tried looking up the problems but I wasn't sure how to word it so I thought I'd just ask a question in total.

x=1
while x==1:
    import math
    loan=input("Enter Loan amount: ")
    rate=input("Enter rate: ")
    if rate.isalpha() or loan.isalpha():
        print("Hey that's not a number!")
        break
    rate=rate.replace("%","")
    loan=float(loan)
    rate=float(rate)*0.01
    amount1y=round(loan*(math.e**(rate*1)),2)
    amount5y=round(loan*(math.e**(rate*5)),2)
    amount10y=round(loan*(math.e**(rate*10)),2)
    monthlypay=round(amount1y-loan,2)
    print("Year 1 without pay: " + str(amount1y))
    print("Year 5 without pay: " + str(amount5y))
    print("Year 10 without pay: " + str(amount10y))
    print("Amount to pay per year: " + str(monthlypay))
    print("Want to do another? Y/N?")
    ans=input('')
    ans=ans.lower()
    y=True
    while y==True:
        if ans=="n" or ans=="no":
            x=0
            break
        elif ans=="y" or ans=="yes":
            y=False
        else:
            print("You gotta tell me Yes or No fam...")
            print("I'll just assume that mean's yes.")
            break

My issue is in two locations. First during the

if rate.isalpha() or loan.isalpha():
        print("Hey that's not a number!")
        break

How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number. Also as a side just for fun and knowledge. Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also? Finally during this part of the code:

 while y==True:
        if ans=="n" or ans=="no":
            x=0
            break
        elif ans=="y" or ans=="yes":
            y=False
        else:
            print("You gotta tell me Yes or No fam...")
            print("I'll just assume that mean's yes.")
            break

the else at the end, without that break, will continue printing "You gotta tell me Yes or No fam..." forever. How do I make it so that instead of breaking the while statement, it'll just restart the while statement asking the question again?

Thanks for your help! P.S. This is python 3.4.2

Upvotes: 0

Views: 119

Answers (3)

Chris
Chris

Reputation: 22963

On both of your examples, I believe your looking for Python's continue statement. From the Python Docs:

(emphasis mine)

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or finally clause within that loop. It continues with the next cycle of the nearest enclosing loop. When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.

This basically means it will "restart" your for/while-loop.


To address your side note of breaking the loop if they get the input wrong after three tries, use a counter variable. increment the counter variable each time the user provides the wrong input, and then check and see if the counter variable is greater than 3. Example:

counter = 0
running = True:
while running:
    i = input("Enter number: ")
    if i.isalpha():
        print("Invalid input")
        counter+=1
    if counter >= 3:
        print("Exiting loop")
        break

Unrelated notes:

  • Why not use a boolean value for x as well?
  • I usually recommend putting any imports at the module level for the structure an readability of one's program.

Upvotes: 0

GIZ
GIZ

Reputation: 4633

Your problem is straightforward. You have to use continue or break wisely. These are called control flow statements. They control the normal flow of execution of your program. So continue will jump to the top-most line in your loop and break will simply jump out of your loop completely, be it a for or while loop.

Going back to your code:

How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number.

if rate.isalpha() or loan.isalpha():
    print("Hey that's not a number!")
    continue

This way, you jump back (you continue) in your loop to the first line: import math. Doing imports inside a loop isn't useful this way the import statement is useless as your imported module is already in sys.modules list as such the import statement won't bother to import it; if you're using reload from imp in 3.X or available in __builtin__ in Python 2.x, then this might sound more reasonable here.

Ditto:

if ans=="n" or ans=="no":
    x=0
    break
elif ans=="y" or ans=="yes":
        continue
else:
    print("You gotta tell me Yes or No fam...")
    print("I'll just assume that mean's yes.")
    continue

To state this snippet in English: if ans is equal to "n" or "no" then break the loop; else if ans is equal to "y" or "yes" then continue. If nothing of that happened, then (else) continue. The nested while loop isn't needed.

Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also?

Not sure if I understood your question, you can take input three times in different ways:

for line in range(3):
    in = input("Enter text for lineno", line)
    ...do something...

Upvotes: 0

James K
James K

Reputation: 3752

You make an infinite loop, that you break out of when all is well. Simplified:

while True:
    x_as_string = input("Value")
    try:
         x = float(x_as_string)
    except ValueError:
         print("I can't convert", x_as_string)
    else:
         break

It is easier to ask forgiveness than permission: You try to convert. If conversion fails you print a notice and continue looping else you break out of the loop.

Upvotes: 1

Related Questions