Conditionals

Conditionals in Python

Conditionals in Python are especially easy to read and write. They allow your program to make decisions by running certain blocks of code only when specific conditions are met. Python's syntax makes them clean, readable, and simple to use.

If

The simplest form of a conditional in Python looks like this:

age = 18
if age >= 18:
    print("You're an adult!")

This tells Python: "If the value of age is 18 or more, then print the message."

Indentation matters in Python, the code block that belongs to the if statement must be indented.

Sometimes you want to check if a certain item exists within a larger group, like a character in a string or an item in a list.

message = "hello world"
if "hello" in message:
    print("The greeting is in the message.")

This works with other iterables too:

fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
    print("Banana is in the list!")

Multiple Conditions

You can combine conditions using logical operators such as

  • and
  • or
  • not
text = "hello world"
if "hello" in text and "world" in text:
    print("Both words are present!")

This only prints if both conditions are true. Use "or" if you want it to run when either condition is true.

Truthy and Falsy

In Python, certain values are considered falsy such as empty strings, lists, dictionaries, None types etc and targeting this can lead to writing compact code.

name = "Adam"
if name:
    print("Name is provided.")

If name is an empty string (""), the if block won't run.

But you can also check whether a variable is empty or false using not.

username = ""
if not username:
    print("No username provided.")

    

This is useful for input validation and defaults.

Walrus Operator

The walrus operator := allows you to assign a variable within an if statement. This can make your code more concise and efficient. Instead of writing two lines (one to calculate len() and one to check it) we do both in one go.

if (length := len("hello")) > 3:
    print(f"The word is {length} characters long.")

Elif and Else

Elif (else if) and else let you expand your logic beyond a single if.

temperature = 30

if temperature > 35:
    print("It's very hot.")
elif temperature > 20:
    print("Nice weather!")
else:
    print("It's cold.")