Range-limited Python
I'm working on a problem that prompts me to create a program that calculates the temperature based on the number of clicks on the watch face. Temperature starts at 40 and stops, and 90 and when it stops, it goes back to 40 and starts.
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)
When I put an input of 1000 clicks, the temperature naturally goes up to 990. I can see this from the code, but how would I do this so that the "temperature" is a number between 40 and 90.
source to share
The problem is that you use the range function when you don't know how many times you need to change clicks_str
until you get a value between 40 and 90. You also print 'temperature' every time you change clicks_str
, but may not be correct yet temperature (until you get clicks_str
between 0 and 50)
The best way to solve this problem would be to use a while loop:
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
or even simpler, as fedterzi said in his answer, using a module:
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))
source to share
If you represent the temperature as a number between 0 and 50 (90-40), you can use modulo operation and then add 40 to get the original temperature.
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))
source to share
Your code could be like this, you didn't need to convert numbers to int, and you can do int input into one line code:
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)
when you enter clicks_str == 1000 or any value> greater than 50 you get: clicks_str -10
source to share