【问题标题】:writing (for and while) loop program in python?在python中编写(for和while)循环程序?
【发布时间】:2016-01-04 03:57:25
【问题描述】:

我必须用python写一个程序来解决这个问题:

向用户询问其度假俱乐部储蓄的初始余额 帐户。将提示用户输入 11 笔存款金额。输出 帐户中的最终金额。

这是我到目前为止所拥有的,我迷路了。我不知道要添加什么才能获得最终金额。我也不知道如何制作 11 存款显示的数字。

balance = int(input("Enter initial balance: $"))
count = 1
numDep = 11
finalAmount = balance+numDep
while count <= 11:
    n = int(input("Enter deposit #:")) # this needs to show deposits numbers up to 11
    count += 1

print("Original price: $", balance)
print("Final Amount: $", finalAmount)

这就是我使用while-loop 编写程序的全部内容。我仍然需要使用for-loop 编写它。

【问题讨论】:

  • 为什么要将 11 添加到 numDep ?
  • finalAmount=12 将与您拥有的完全相同...因为您永远不会更改它,我确定它总是 orints 12

标签: python for-loop while-loop


【解决方案1】:

您需要找到总数。

balance = int(input("Enter initial balance: $ "))
count = 1
total =0
while count <= 11:
    n = int(input("Enter deposit %s #: " %(count))) 
    count += 1
    total += n #keep on adding deposit amounts.


print("Original price: $ %d" %balance)
print("Final Amount: $ %d" %(total + balance) )

使用 For 循环:

balance = int(input("Enter initial balance: $ "))
for i in range(11):
    n = int(input("Enter deposit #: %s " %(i)))
    total +=n

print("Original price: $ %d" %balance)
print("Final Amount: $ %d" %(total + balance) )

【讨论】:

  • 他要求它作为一个 for 循环。而且,for i in range(11) 将迭代 11 次。
  • 但对我来说,他的 while 循环实现似乎是错误的。他最初确实要求两者。
  • while 循环实现错误。这是对 while 循环的不好使用(一般问题)。
  • "Enter deposit #%s: " %str(count)
  • @intboolstring 他确实想要 11 笔存款。所以 range(11) 对我来说似乎不错。
【解决方案2】:

这里是使用 for 循环

balance = int(input("Enter the initial balance"))
beginning = balance
for i in range(1,11):
    n = int(input(("Deposit"+str(i))))
    balance += n
print("You had", beginning, "at the beginning")
print("Now, you have", balance)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-28
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    相关资源
    最近更新 更多