【问题标题】:How to get For loops to communicate with a While loop如何让 For 循环与 While 循环通信
【发布时间】:2016-10-03 09:21:40
【问题描述】:

我需要编写一个程序,从 for 循环中获取最后一个数字(如果它超过某个数字)并将其放在 while 循环中。我在下面留下了未完成的代码。

t=0
num=int(input("How many presents do you want to buy?: "))

for i in range(num):
   t=t+int(input("Please enter the price of a present")



while t>'200':
        print("Limit Exceeded.")
        print("You need to get rid of the " #price from the previous loop

【问题讨论】:

  • 您有很多不匹配的括号,并且您无法将 int 与字符串进行比较:t>200 将优于 t>'200'。我真的无法进一步帮助您,因为我不确定您要使用此代码实现什么目标。

标签: python for-loop while-loop


【解决方案1】:

你需要使用一个列表。

t = 0
num=int(input("How many presents do you want to buy?: "))
prices = []
for i in range(num):
    prices.append(int(input("Please enter the price of a present")))
    t += prices[-1]
    while t > 200:
        print("Limit Exceeded.")
        print("You need to get rid of the: {}".format(prices[-1]))
        t -= prices.pop()

与 你比较错误:

if t > '200'

t 是一个 'int' 类型,你正在将它与一个字符串进行比较。 请改正。

希望这会有所帮助。

【讨论】:

  • 按照你的方式,while 循环永远不会循环超过一次。您可以将其替换为 if 并立即继续删除,或者将其放在 for 之外并在添加所有价格后进行删除。
  • 好吧,如果有人问价格时只输入201,这个程序肯定会陷入死循环。我不完全知道他想做什么......
  • 我猜他正在学习用python编码,让他开始吧。他会进步的。
  • 将价格添加到t确认您不会超过 200。
猜你喜欢
  • 1970-01-01
  • 2014-03-23
  • 2016-03-25
  • 2011-05-11
  • 2015-09-18
  • 1970-01-01
  • 2021-07-27
  • 2019-11-10
  • 1970-01-01
相关资源
最近更新 更多