0

Language: Python

I want the value of a variable to be initialized to zero at the start of the execution. This variable is used in a function & its value may also get changed within the function. But I do not want the value of this variable to reset to zero whenever a function call is made. Instead, its value should be equal to the updated value from its previous function call.

Example:
get_current() is constantly returning a different value when it is called. ctemp is initially zero. In the first function call get_current_difference() will return cdiff & then update the value of ctemp such that ctemp = current. In the second function call, the value of ctemp should not be zero. Instead, it should be equal to the updated value from the first function call.

import serial
arduino = serial.Serial('/dev/ttyACM1',9600)
ctemp = 0

def get_current():
    line = arduino.readline()
    string = line.replace('\r\n','')
    return string

def get_current_difference():
    global ctemp
    current = get_current()
    cdiff = float(current) - ctemp
    return cdiff
    ctemp = current

while 1:
    current = get_current_difference()
    print(current)
0

2 Answers 2

1

You return before setting value of ctemp

return cdiff
ctemp = current

must become

ctemp = current
return cdiff
Sign up to request clarification or add additional context in comments.

3 Comments

Does it make a difference?
@user106268 Nothing will execute after you return. So ctemp is unreachable
return actively exits a function; it doesn't just queue up a return value for when the function eventually reaches the last line of the definition.
1

You are describing mutable state and a function to modify it, which is what classes are for.

class Temperature:
    def __init__(self, arduino):
        self.ctemp = 0
        self.arduino = arduino

    def current(self):
        line = self.arduino.readline()
        return line.replace('\r\n', '')

    def difference(self):
        current = self.current()
        cdiff = float(current) - self.ctemp
        self.ctemp = current
        return cdiff

t = Tempurature(serial.Serial('/dev/ttyACM1', 9600)
while True:
    print(t.difference())

Using a class scales if, for example, you have multiple temperature monitors to work with.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.