What does β€œif not data: break” mean?

I found this Python code here .

I don't understand what if not data: break means on line 18.

 #!/usr/bin/env python import socket TCP_IP = '127.0.0.1' TCP_PORT = 5005 BUFFER_SIZE = 20 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() print 'Connection address:', addr while 1: data = conn.recv(BUFFER_SIZE) if not data: break print "received data:", data conn.send(data) # echo conn.close() 
+4
source share
3 answers

It just checks to see if the received data empty; if so, it exits the loop. Very similar to checking an empty string.

 >>> not "" True >>> bool("") False 

If data = conn.recv(BUFFER_SIZE) gives an empty string, the while ends.

+4
source

This means that if the last attempt to get data in the connection did not produce any data, exit the loop trying to get more data.

Cm

 while 1: while block 

is a while loop with a condition that always evaluates to true. Therefore, this is an infinite loop that will evaluate the while block at each iteration.

Except in our case, while block has a break in it. If you click break , it will exit the loop. Let's look at the while block :

  data = conn.recv(BUFFER_SIZE) if not data: break print "received data:", data conn.send(data) # echo 

This block says that accepting connection data conn no more than BUFFER_SIZE bytes. If no data has been received, not data is evaluated as true, and we execute the if body. In this case, this is the break statement that we discussed, so we exit the loop and stop receiving data. If the if condition is false, the message "received data:" , followed by the received data, will be printed to the console. Finally, data is returned back to another endpoint.

0
source

This means that if the data is empty, null, or equivalent, the while loop will end.

0
source

Source: https://habr.com/ru/post/1493816/


All Articles