Jump to content



Photo

Python -Looping


  • Please log in to reply
1 reply to this topic

#1 Craig Hopson

Craig Hopson

    Neowinian

  • Joined: 17-November 12
  • Location: London
  • OS: Windows 8 :-(

Posted 12 October 2013 - 14:24

Hi guys i am new to python and have written this function

def Probe(serial = None):
	if not serial:
		return "0"
	if not os.path.isdir("/sys/bus/w1/devices/" + serial):
		return "0"
	tfile = open("/sys/bus/w1/devices/" + serial + "/w1_slave")
	text = tfile.read()
>	if text.find("YES") < 1:
>                        time.sleep(2)
>			tfile.close()
>			tfile = open("/sys/bus/w1/devices/" + serial + "/w1_slave")
>			text = tfile.read()
>			if text.find("YES") < 1:
>                               time.sleep(2)
>				tfile.close()
>				tfile = open("/sys/bus/w1/devices/" + serial + "/w1_slave")
>				text = tfile.read()
	tfile.close()
	secondline = text.split("\n")[1]
	temperaturedata = secondline.split(" ")[9]
	temperature = float(temperaturedata[2:])
	temperature = temperature / 1000
	output = "%.1f" %temperature
	return output

now the section in red as you can see if text DOES'NT have "YES" in it it will wait (sleep) 2 seconds then try again but i would like to change it to a loop so it wont just try twice then give up it will loop 5 times then give up

 

Thanks ALL

 

EDIT The red highlighter dont work so maked with >




#2 +theblazingangel

theblazingangel

    Software Engineer

  • Tech Issues Solved: 4
  • Joined: 25-March 04
  • Location: England, UK

Posted 12 October 2013 - 14:59

This is a very basic modification.

1) Cut out the nested if statement (last five lines highlighted).
2) Create two variables, one perhaps called 'foundYes' to store a success/fail state and the other a counter. Somewhere before the if statement initialise the counter to 0 and foundYes to false.
3) Wrap the if statement in a while loop. The while loop should test two conditions, first that foundYes is false, second that the loop counter has not exceeded your max of 5.
4) Add a statement within the loop but outside of the if statement to increment the counter on each loop.
5) Add a statement within the if statement to set foundYes to true.