• 0

Python -Looping


Question

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 >

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

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.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.