将变量计数器设置为从零开始但不

时间:2017-03-23 18:55:10

标签: python python-3.x for-loop logical-operators

我正在使用更新的代码重新发布此问题。

当我运行此代码来计算多年来获得的简单兴趣时(以漂亮的表格形式),我的表格列多年来从5开始。此外,总计是从5开始计算的年份。只是为了澄清,当我被要求提供totYear时,我使用5作为用户输入的示例。

    #Declare the necessary variables.
princ = 0
interest = 0.0
totYear = 0
year = 1

#Get the amont of principal invested.
print("Enter the principal amount.")
princ = int(input())

#Get the interest rate being applied.
print("Enter the interest rate.")
interest = float(input())

#Get the total amount of years principal is invested.
print ("Enter the total number of years you're investing this amonut.")
totYear = int(input())

print("Year      Interest")
for year in range(totYear):
    total=totYear*interest*princ
    print (totYear,"      $",total)
    totYear+=1

if total<100:
    print("That is not too much interest!")
else:
    print("This interest really adds up!")

这是输出屏幕:

Enter the principal amount.
10
Enter the interest rate.
5
Enter the total number of years you're investing this amonut.
5
Year      Interest
5       $ 250.0
6       $ 300.0
7       $ 350.0
8       $ 400.0
9       $ 450.0
This interest really adds up!

感谢您的帮助!

4 个答案:

答案 0 :(得分:0)

这是你想要的输出吗?

Enter the principal amount.
10
Enter the interest rate.
5
Enter the total number of years you're investing this amonut.
5
Year      Interest
0       $ 250.0
1       $ 300.0
2       $ 350.0
3       $ 400.0
4       $ 450.0
This interest really adds up!

如果是,那么您需要将print (totYear," $",total)替换为:

print (year," $",total)

此外,您无需初始化year,因为它已在for中初始化。

答案 1 :(得分:0)

首先,您需要将循环中的totYear更改为年份,因为年份是计数器

for year in range(totYear):
    total=year*interest*princ
    print (year,"      $",total)
    #totYear+=1 //delete this line

然后删除最后一次增量

答案 2 :(得分:0)

这是我在上一个问题中给你的循环,更新了print语句以包含年份。我添加了&#34; + 1&#34;调整你已经想通了。格式如您所愿。

princ = 10000
interest = 0.10
totYears = 5

for year in range(1, totYears+1):
    total = year * interest * princ
    print (year, total)

输出:

1 1000.0
2 2000.0
3 3000.0
4 4000.0
5 5000.0

答案 3 :(得分:-1)

我相信你已经将totYear设置为等于int(input())以及计数器从用户输入的年数开始的原因。

您可能希望创建另一个等于int(input())的变量numYears,并且具有范围(numYears)而不是range(totYear)。

#variable that gets number of years user inputs
numYears = 0; 
#Get the total amount of years principal is invested.
print ("Enter the total number of years you're investing this amonut.")
numYears = int(input())

print("Year      Interest")
for year in range(numYears):
total=totYear*interest*princ
print (totYear,"      $",total)
totYear+=1