首页 > 解决方案 > 如何在循环中给出的最后一个值中添加一个确切的数量?

问题描述

我正在制作一个 Illustrator 机器人来执行特定任务,在这种情况下,用正方形填充字母大小的表格(用户输入正方形的 H 和 W)。例如,如果我输入一个 2 x 3 的矩形,宽度为 2 英寸,程序会不断增加矩形的宽度(2 英寸),并在达到极限之前停止。

示例:如果宽度为 2,它将添加 +2+2+2 = 8,它在 8 处停止,因为如果再添加 2,结果将是 10(超过 8.5 的限制)

我的问题是我想在循环完成后使用循环中给出的最后一个值(8.0)执行一项任务,但我不知道如何。

例如:如果循环中给出的最后一个值是 8.0,我想给它加上 0.25(记住这个值并不总是相同的)。无论循环中给出的最后一个值是什么,如何始终添加相同的数量(0.25)?

我的代码:

w = float(input("insert width: "))
h = float(input("insert height: "))

letter_w = 8.5
letter_h = 11

addition = (w + w)
while addition < letter_w:
    print(addition)
    print("under the limit")
    addition = addition + w

结果:

insert width: 2
insert height: 2
4.0
under the limit
6.0
under the limit
8.0
under the limit

Process finished with exit code 0

标签: pythonloops

解决方案


我认为关键是你需要将你想要最终得到的值存储在一个变量中,这样你就可以在完成循环后对它进行处理。也许你可以尝试这样的事情:

w = float(input("insert width: "))
h = float(input("insert height: "))

letter_w = 8.5
letter_h = 11

added_w = w
while (added_w + w) < letter_w:
    added_w += w
    print(added_w)
    print("under the limit")
    
print("Final size:")
print(added_w + 0.25)

哪个,按照你的例子应该产生:

insert width: 2
insert height: 2
4.0
under the limit
6.0
under the limit
8.0
under the limit
Final size:
8.25

推荐阅读