计算使用循环次数

时间:2015-10-26 02:08:06

标签: python

所以我建立一个简单的while循环来检查冷却茶所需的打击次数。一击将茶叶温度降低10℃。问题是我不知道如何继续这样做。我知道它简单但只是启动了python。感谢

tea = 100 #temperature of tea to start with
while tea >= 70:
    print (str(tea) + " C")
    tea = tea - 10
print (" It's ready now ... ")

3 个答案:

答案 0 :(得分:1)

tea = 100 #temperature of tea to start with
count = 0
while tea >= 70:
   print (str(tea) + " C")
   tea = tea - 10
   count += 1
print (" It's ready now ... ")

答案 1 :(得分:1)

执行此操作的一种方法是在循环外部使用变量,并在每次迭代中增加变量。所以:

tea = 100
count = 0
while tea >= 70:
    print(str(tea) + " C")
    tea -= 10   # shorthand for tea = tea-10
    count += 1
print("It's ready now")
print("It took {} blows to cool down".format(count))

答案 2 :(得分:0)

为什么需要循环?

def steps(current, target, step):
    return int(math.floor((current - target) / float(step)) + 1)

print("It took {} steps!".format(steps(100, 70, 10)))