# While loop doesn't exit

**URL:** <https://discuss.python.org/t/while-loop-doesnt-exit/9353>\
**Category:** Python Help\
**Created:** [June 20, 2021, 10:11pm UTC](https://discuss.python.org/t/while-loop-doesnt-exit/9353 "2021-06-20T22:11:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![KenHorse](https://avatars.discourse-cdn.com/v4/letter/k/fbc32d/32.png) [@KenHorse](https://discuss.python.org/u/KenHorse)\
**Post date:** [June 20, 2021, 10:11pm UTC](https://discuss.python.org/t/while-loop-doesnt-exit/9353/1 "2021-06-20T22:11:51Z")

</div>

```auto
while indata != "%":  
  indata = ser.read()
  print (indata.decode())
  Counter = Counter + 1 
  if Counter > 20:
   sys.exit("Timed out waiting for response")

```

It always times out no matter what and the print statement verifies that “%” is being received. I even tried:

```auto

while indata.strip() != "%":
  indata = ser.read()
  print (indata.decode())  
  Counter = Counter + 1 
  if Counter > 20:
   sys.exit("Timed out waiting for Bootloader Active Character. Please try again")

```

and it still never exits the loop. This is Python3.7 under Linux

---

<div class="post-metadata">

**Author:** ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)\
**Post date:** [June 20, 2021, 10:32pm UTC](https://discuss.python.org/t/while-loop-doesnt-exit/9353/2 "2021-06-20T22:32:48Z")

</div>

You are reading indata as _bytes_ but comparing it to a _Unicode string_,  
the two will never be equal even if they look the same to the human eye:

```
>>> a = "%" # a string
>>> b = b"%" # bytes
>>> a == b
False

```

Change the condition in the while loop to `while indata != b"%"` and it  
should work.

---

<div class="post-metadata">

**Author:** ![KenHorse](https://avatars.discourse-cdn.com/v4/letter/k/fbc32d/32.png) [@KenHorse](https://discuss.python.org/u/KenHorse)\
**Post date:** [June 20, 2021, 10:56pm UTC](https://discuss.python.org/t/while-loop-doesnt-exit/9353/3 "2021-06-20T22:56:46Z")

</div>

Thank you , that did it. Last time I used this code was under Python 2.7.1. Quite a few changes since!
