0

I am using below code to replace a string, it is actually working, I want to know if there is better way to do it ? I just want to read data coming from serial, if it is same value do nothing but if it is new value print it...

new = ""
old = ""

while True:
    new = readQR("/dev/input/event7")
    if new != old:
        print (new)
        old = ""
        old = new
        new = ""
    else:
        new = ""
3
  • 1
    Couple of comments in here, in python you don't need to set the variable as empty in order to assign a new value, you could just do: old = new you don't need old="" and new="" also the else block is not needed Commented Mar 7, 2022 at 5:54
  • 3
    please explain the expecetd working behaviour. Commented Mar 7, 2022 at 5:54
  • 1
    instead of the three lines you're using to swap old and new, you could do it in just one line, old, new = new, "" Commented Mar 7, 2022 at 5:57

2 Answers 2

1

I am guessing that you are new to Python. In case you already now these then it might help others :)

You can trim down your code to this:

new = ""
old = ""

while True:
    new = readQR("/dev/input/event7")
    if new != old:
        old, new = (new, "")  # tuple unpacking

We don't need to do new = "" in else condition as it would be overwritten by readQR in the next iteration.

Brief explanation of old, new = (new, ""):

Here what we are doing is that we are creating a tuple - (new, "") and unpacking it in old and new.

This example might help in understanding the concept of tuple unpacking-

>>> a = 1
>>> b = 2
>>>
>>> t = a, b  # t is a tuple
>>> t
(1, 2)
>>>
>>> b, a = t  # tuple unpacking - same as b = t[0] and a = t[1]
>>> b
1
>>> a
2

You can refer to this video - Tuples & Tuple Unpacking in Python

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply, but it doesnt give me any output ; new = "" old = "" while True: new = readQR("/dev/input/event7") if new != old: old, new = (new, "") print (new) as I want to change old value with new value and if it is same value do nothing...
1

I figured it out based on AnirudhSharma's answer:

old, new = ("", "")

while True:
    new = readQR("/dev/input/event7")
    if new != old:
        old = new
        print (new)

1 Comment

Nice that you got it working and welcome to Stack Overflow :)

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.