Python限制在一个范围内

时间:2017-04-07 22:28:14

标签: python range

我正在研究一个问题,它告诉我创建一个根据表盘上的“点击次数”来计算温度的程序。温度从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 个答案:

答案 0 :(得分: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 :(得分: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的值&gt;时,您输出的内容为:clicks_str -10

答案 2 :(得分:1)

问题似乎是因为当你不知道需要修改clicks_str的次数直到得到温度在40到90之间的值时你使用范围功能。你还打印了&#39;温度&#39;每次修改clicks_str但它可能不是正确的温度(直到你得到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))
相关问题