In python you can use strings with the or and and keywords. The program sends a TCP request and prints the response, but if it fails it prints connection error. def Send_TCP_Request(): try: tcpc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpc.settimeout(1) tcpc.connect(('0.0.0.0', 8000)) tcpc.send('Hello World') Result = tcpc.recv(1024) tcpc.close() except: Result = None return Result def setup(): M5.begin() print(Send_TCP_Request() or "Connection Error")