-4

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
  • Your question is unclear, please state the inputs, desired outputs and post your errors – EdChum Dec 09 '15 at 16:01
  • that's part or slice of my python code – Ridho Habi Putra Dec 09 '15 at 16:02
  • with `if` you probably want to check equality (`==`), not assignment (`=`). `if temp == 30:`. You're also missing `:` at then end of your conditional lines. Does this code even run? – Jon Surrell Dec 09 '15 at 16:08
  • yes code is run. Thank You @JonSurrell. I Have one question again. how do looping in a python program but if a variable that has been repeated need not be repeated ? – Ridho Habi Putra Dec 09 '15 at 16:13
  • Is it doing anything like what you expect? Shouldn't `time.sleep(5)` be inside the `while` block? Shouldn't `=+` be `+=`? – Jon Surrell Dec 09 '15 at 16:15

1 Answers1

1

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
Damian
  • 51
  • 4
  • thank you for youre answer. I want asked again, how do looping in a python program but if a variable that has been repeated need not be repeated ? such as break and continue . @Damian – Ridho Habi Putra Dec 09 '15 at 16:32
  • 1
    I don't really understand your question. Is it that you want to loop over the unique values of a list? – Damian Dec 09 '15 at 16:42
  • If that's the case (looping over the unique values of a list) - just use set(list). So, you will have something like: for iterator in set(duplicate_list): # do something – Damian Dec 09 '15 at 16:57