Sign in to follow this  
Followers 0

Python -Looping

2 posts in this topic

Posted

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 >

Share this post


Link to post
Share on other sites

Posted

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Recently Browsing   0 members

    No registered users viewing this page.