如何在循环中使用“if”?

2024-06-29 01:08:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解决一个问题,但是我觉得我的循环在某个地方缺失了一个环节。。。在

给我的简报- “现在编写一个程序,计算在12个月内还清信用卡余额所需的最低每月固定付款。”

本质上,我所做的是,编写一些代码,将取一个基本值(例如10),从信用卡余额中扣除(考虑利息),如果将余额设为负数(如已还清)所需的总月数超过12个月,则将其添加到“minmonth”(每月要偿还的金额)中直到月数等于或小于12。在

提前道歉,我只学了两天Python!在

我哪里出错了?在

balance = float(raw_input('Enter the outstanding balance on your creditcard: '))
interest = float(raw_input('Enter the annual credit card interest rate as a decimal:     '))

minmonth = 10
months = 0
monthlyinterest =  interest / 12

while(balance > 0):
    balance = balance * (1 + monthlyinterest) - minmonth
    months = months + 1

    if(months > 12):
        months = 0
        minmonth = minmonth + 10

else:
    print 'RESULT!'
    print 'Total amount to pay per month would be'
    print minmonth
    print 'Total amounts to pay'
    print months

Tags: thetoinputrawfloat信用卡余额total
2条回答

缩进在Python中很重要。您需要使else与代码中的if语句保持一致。在

你的“else”和你的“if”不一致。Python需要完美的缩进来识别循环和语句的作用域。在

编辑在下面添加蒂姆的评论,我没有明确指出: “值得一提的是,它需要缩进,因为它使用缩进来代替显式的begin/end语句或大括号{},这些语句可以在其他语言中将代码组合在一起。”

相关问题 更多 >