[SOLVED] What does it mean to use 'if not' before a function name in Python?


I have come across some code I can’t work out and for which there is no provided explanation. I have tried! The code is in two parts and runs a computer health check. In the second block, what does the ‘if not’ line mean? (I’m not familiar with using a function name this way). The comments show what it does but, I’m interested in how it works. And on the same line, what is the meaning of the slash in parentheses?

#!/usr/bin/env python3
import requests
import socket
def check_localhost():
        localhost = socket.gethostbyname('localhost')
        return localhost == ""

def check_connectivity():
        request = requests.get("http://www.google.com")
        return request == 200
#!/usr/bin/env python3
from network import *
import shutil
import psutil

def check_disk_usage(disk):
    """Verifies that there's enough free space on disk"""
    du = shutil.disk_usage(disk)
    free = du.free / du.total * 100
    return free > 20

def check_cpu_usage():
    """Verifies that there's enough unused CPU"""
    usage = psutil.cpu_percent(1)
    return usage < 75
# If there's not enough disk, or not enough CPU, print an error
if not check_disk_usage('/') or not check_cpu_usage():
elif check_localhost() and check_connectivity():
    print("Everything ok")
    print("Network checks failed")


not in Python is the equivalent of ! in other languages; it’s a negator. It returns true if the following statement is not true, and false otherwise.

At a guess, the / in parentheses is referring to the root directory in a Unix filesystem.

So that line is saying, "If there’s not enough disk space where root is, or not enough cpu, print an error." The two functions check_disk_usage(folder) and check_cpu_usage() return boolean true (meaning OK) or false (meaning not OK).

Answered By – Lunivore

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *