How to add logic in Python

1 min

In Python, you can add logic using control statements like if, else, and elif.

Here's a simple example of an if statement:

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

The if statement checks whether the value of x is greater than 5, and if it is, it prints "x is greater than 5".

Here's an example of an if-else statement:

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

The else clause runs if the if statement's condition is not met.

You can also use elif to check multiple conditions:

x = 3
if x > 5:
    print("x is greater than 5")
elif x == 3:
    print("x is equal to 3")
else:
    print("x is less than 3")

In this example, elif checks if x is equal to 3, and runs the corresponding block if the condition is met.

Additionally, you can use loops like for and while to repeat actions until a certain condition is met. These control statements allow you to add logic and automate tasks in your Python code.