How to Use an if Statement in Python
Programs make decisions: warn when it's hot, skip a step when a file is missing. Python's if runs its indented block only when its condition is true, and elif and else handle the other cases.
uv, the Fast Python Package and Project Manager, Its Commands and pyproject.toml
View All TagsPrograms make decisions: warn when it's hot, skip a step when a file is missing. Python's if runs its indented block only when its condition is true, and elif and else handle the other cases.
A call like make_tea("black", 0, True) works, but nobody can tell what 0 and True mean. Keyword arguments name each value at the call, make_tea("black", milk=True), so the call explains itself and you can skip the parameters whose defaults are fine.
A Python file can be a script you run and a module other files import. The line if __name__ == "__main__": separates the two: the code under it runs when you start the file, and stays quiet when another file imports the file for its functions.
When something goes wrong, Python raises an exception, and the script stops unless something catches it. Catching one specific kind, such as ValueError, lets you handle the problem you expected while every other error still stops the script and shows you where it happened.
print is the first thing most Python programs use: it writes values to the terminal, each call on its own line. Two optional settings, sep and end, control what goes between the values and what comes after them.
Base64 turns bytes into plain text so they can travel in JSON, URLs or environment variables. base64.b64decode turns that text back into the original bytes, and with validate=True it refuses anything that isn't proper base64 instead of quietly skipping it.
A value your script needs, such as a setting or a field from a form, can be missing as an empty string "" or as None. Python treats both as false in a condition, so a single if not value: catches either.
Settings that change from one computer to the next, such as a port, a database address or an API key, belong in environment variables. Python reads them from os.environ, and os.environ.get returns None instead of failing when a variable isn't set.
A list keeps several values in order, in one variable: colors, names, prices. In Python you write it with square brackets, and you can add, read and change its items at any time.
A dictionary stores values under names, called keys: a book's title under "title", its year under "year". You write one in Python with curly braces and key: value pairs, and add more pairs at any time.