Python限制在一个范围内

3

我正在处理一个问题,要求我创建一个程序根据旋钮的“点击”次数计算温度。温度从40开始,到90停止,一旦停止就回到40并重新开始。

clicks_str = input("By how many clicks has the dial been turned?")
clicks_str = int(clicks_str)

x = 40
x = int(x)

for i in range(1):
    if  clicks_str > 50:
        print("The temperature is",clicks_str -10)
    elif clicks_str < 0:
        print("The temperature is",clicks_str +90)
    else:
        print("The temperature is", x + clicks_str)

当我输入1000次点击时,温度自然会上升到990。我可以从代码中看出来,但是如何让“温度”成为介于40和90之间的数字呢?


3
你觉得 for i in range(1): 在你的代码中代表什么意思?我相信你可以轻松将它从你的代码中移除。 - Ozgur Vatansever
3个回答

4

如果你将温度表示为0到50(90-40)之间的数字,你可以使用取模运算,然后加上40来得到原始温度。

clicks_str = input("By how many clicks has the dial been turned?")
clicks_str = int(clicks_str)

temp = (clicks_str % 51) + 40
print("The temperature is {}".format(temp))

1
您的代码可以像这样,无需将数字转换为int,您可以在一行代码中将输入转换为int:
clicks_str = int(input("By how many clicks has the dial been turned?"))

x = 40

if  clicks_str > 50:
    print("The temperature is",clicks_str -10)
elif clicks_str < 0:
    print("The temperature is",clicks_str +90)
else:
    print("The temperature is", x + clicks_str)

当你输入 clicks_str == 1000 或任何大于50的值时,输出为:clicks_str - 10

1
问题似乎在于您在不知道需要修改 clicks_str 多少次才能得到介于温度 40 和 90 之间的值时使用了 range 函数。每次修改 clicks_str 时,您还会打印“temperature”,但它可能还不是正确的温度(直到您得到介于 0 和 50 之间的 clicks_str)。
更好的解决方法是使用 while 循环:
clicks_str = int(input("By how many clicks has the dial been turned?"))
x = 40

while True:
    if  clicks_str > 50:
        clicks_str -= 50
    elif clicks_str < 0:
        clicks_str += 50
    else:
        print("The temperature is", x + clicks_str)
        break # breaks while loop

甚至更简单的方法是使用模数,正如fedterzi在他的回复中所说:

clicks_str = int(input("By how many clicks has the dial been turned?"))
x = 40

temp = (clicks_str % 50) + x
print("The temperature is {}".format(temp))

所以 while 循环确保循环的数字是 40-90 吗? - Cato Savanah
在这种情况下,while循环将一直运行,直到遇到break。正如您所看到的,它只会在0 < clicks_str < 50时遇到一个break,这将为您提供正确的温度值。 - Jordan Pagni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接