Search code examples
pythonloopsraspberry-pitemptemperature

Python Looping for Store Data


I want to ask about looping. This my Code I'm using Python. Please Help me to get the looping.

temp = 0 # temperature
valve = 0 #control temperature

while True :
  if temp = 30
    valve =+ 20
    print "temp now 30 and valve 20"
  elif temp = 40
    valve =+ 40
    print "temp now 40 and valve 40"
  else
    print "temp n and valve n"

time.sleep(5) #looping 5 second not happen i get error

Solution

  • Based on your posted code and assuming you are trying to loop indefinitely with a period of 5s and increase the valve value depending on temperature, this code runs:

    import time
    
    temp = 0 # temperature
    valve = 0 #control temperature
    
    while True:
        if temp == 30:
            valve += 20
        elif temp == 40:
            valve += 40
        else:
            valve = 'n' 
            temp = 'n'
    
        print "temp now {temp} and valve {valve}".format(temp=temp, valve=valve)
        time.sleep(5) #looping 5 second not happen i get error
    

    Mistakes I could spot:

    • No import of time (import time)
    • Conditional statements in python are followed by :
    • You were using = to check for equality, while the correct syntax is ==
    • Python uses indentation to keep track of code blocks, so time.sleep(5) should be also aligned with the if statements, so that it is part of the while loop
    • (not an error), but an improvement: you can set your valve values in the conditional part of your loop and only print once at the end