简体   繁体   English

兴趣计算器循环问题Python

[英]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? 我如何做到这一点,而不是破坏while语句,而只是重新启动while语句再次询问问题?

Thanks for your help! 谢谢你的帮助! PS This is python 3.4.2 PS这是python 3.4.2

You make an infinite loop, that you break out of when all is well. 你做一个无限循环,当break的时候就会break 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. 如果转换失败,您将打印一条通知并继续循环, elsebreak退出循环。

On both of your examples, I believe your looking for Python's continue statement . 在您的两个示例中,我相信您都在寻找Python的continue 语句 From the Python Docs: 从Python文档中:

(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. Continue可能仅在语法上嵌套在for或while循环中,而不能嵌套在该循环内的函数或类定义或finally子句中。 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. 当continue将控制权从带有finally子句的try语句中移出时,将在真正开始下一个循环周期之前执行finally子句。

This basically means it will "restart" your for/while -loop. 这基本上意味着它将“重新启动” 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: 每次用户输入错误时递增计数器变量,然后检查计数器变量是否大于3。示例:

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? 为什么不也为x使用布尔值?
  • I usually recommend putting any imports at the module level for the structure an readability of one's program. 我通常建议将任何导入都放在模块级别,以使结构具有程序可读性。

Your problem is straightforward. 您的问题很简单。 You have to use continue or break wisely. 您必须明智地使用continuebreak 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. 因此, continue将跳转到最上面的线在你的循环和break只会跳出你的循环完全,无论是forwhile循环。

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 . 这样,您就可以在循环中跳回(继续)第一行: 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; 在循环中执行导入对这种方式没有用,因为导入的语句已经无用,因为导入的模块已经在sys.modules列表中,因此import语句不会麻烦导入它。 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. 如果您正在使用3.X中的imp reload ,或者在Python 2.x中的__builtin__中可用,那么这里听起来更合理。

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; 用英语声明该片段:如果ans等于"n""no"则打破循环; else if ans is equal to "y" or "yes" then continue. 否则,如果ans等于"y""yes"则继续。 If nothing of that happened, then ( else ) continue . 如果那什么都没发生,那么( elsecontinue The nested while loop isn't needed. 不需要嵌套的while循环。

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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM