Home » Posts tagged 'Python If-Else'

Tag Archives: Python If-Else

Newly Updated Posts

Python If else statement

In this tutorial, we will learn If else statement in Python.

The if-else statement in Python is used to run various blocks of code depending on a specific condition. The if-else statement’s general syntax is as follows:

if condition:
    # code to be executed if the condition is True
else:
    # code to be executed if the condition is False

Here is an illustration of how to use Python’s if-else statement:

x = 10

if x > 0:
    print("x is positive")
else:
    print("x is zero or negative")

In this example, if the value of x is greater than 0, the statement x is positive will be printed. Otherwise, the statement x is zero or negative will be printed.

You can also use multiple elif (short for “else if”) statements to check for additional conditions. Here’s an example:

x = 10

if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

In this case, if x is greater than 0, the statement x is positive will be printed. If x is equal to 0, the statement x is zero will be printed. Otherwise, the statement x is negative will be printed.

Remember to indent the code blocks correctly to define the scope of each condition. Python uses indentation (typically four spaces) to group statements together.