The if statement is one of the most important control structures in Python. It allows you to add decision-making capability to your code, enabling it to react to conditions and make logical choices.

In this guide, we’ll walk through the basic syntax of Python’s if statement, show you how it works with various data types, and provide practical examples. (link)


What Is an if Statement in Python?

In Python, the if statement checks whether a condition is True or False. If the condition is True, the indented code block runs. Otherwise, it’s skipped.

You can also chain conditions using elif (else if) and define a fallback case using else.

Code Python if

if condition:
    # do something
elif another_condition:
    # do something else
else:
    # fallback action

Proper indentation is critical in Python. Misaligned blocks will result in syntax errors.


1. Integer and Float

number = 10
if number > 5:
    print("number is greater than 5.")

pi = 3.14
if pi == 3.14:
    print("pi is 3.14.")

These conditions work with any numeric values.


2. String

name = "Alice"
if name == "Alice":
    print("Hello, Alice!")

sentence = "Python is a powerful language."
if "Python" in sentence:
    print("Found Python in the sentence.")

Strings can be compared or checked for inclusion using in.


3. List

fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
    print("There's apple in the list.")

if len(fruits) > 2:
    print("There are more than 3 fruits in the list.")

You can check membership or list length.


4. Dictionary

person = {"name": "Bob", "age": 25}
if "name" in person:
    print("The name key exists.")

if person.get("age") and person["age"] > 20:
    print("Age is 20 or older.")

Use in for keys and .get() for safe access.


5. Set

unique_numbers = {1, 2, 3, 4, 5}
if 3 in unique_numbers:
    print("The set contains 3.")

another_set = set()
if not another_set:
    print("The set is empty.")

Sets are great for checking membership and empty states.


6. Tuple

coordinates = (10, 20)
if len(coordinates) == 2:
    print("Coordinates are two-dimensional.")

if 10 in coordinates:
    print("Tuple contains 10.")

Tuples work similarly to lists for conditionals.


7. Boolean

is_active = True
if is_active:
    print("Active status.")

if not is_active:
    print("Disabled.")

Booleans are used directly or negated with not.


8. None (Null in Python)

value = None
if value is None:
    print("No value.")

value = 10
if value is not None:
    print("The value exists:", value)

Use is and is not when comparing with None.


9. Compound Conditions

age = 30
city = "New York"

if age > 20 and city == "New York":
    print("I'm over 20 years old and live in New York City.")

if age < 18 or city == "New York":
    print("I'm a minor or live in New York.")

Combine conditions using and, or, and not.


10. Type Checking with isinstance()

data = [1, 2, 3]
if isinstance(data, list):
    print("data is a list.")

value = 42
if isinstance(value, int):
    print("value is an integer.")

isinstance() helps you write safer type-aware conditions.


Common Pitfalls

  • Indentation Errors: All code inside an if, elif, or else block must be indented.
  • Assignment vs Comparison: Don’t use = where you mean ==.

Final Thoughts

Python’s if statement is the foundation of decision-making in code. It allows your program to act conditionally, which is essential for building dynamic, responsive applications.

Whether you’re working with numbers, strings, collections, or booleans, mastering if logic will improve your ability to write smart, efficient Python code.

By Mark

-_-

Leave a Reply

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