Skip to main content

Command Palette

Search for a command to run...

If Else Statement in Python

Published
•1 min read•View as Markdown

An if else statement in Python is used to execute different blocks of code based on whether a specific condition is true or false. It allows a program to respond differently to different situations or inputs. Here’s a basic structure:

pythonCopy codeif condition:
    # code to execute if the condition is true
else:
    # code to execute if the condition is false
  • The condition is any expression that evaluates to True or False.

  • If the condition is True, the code block under the if clause runs.

  • If the condition is False, the code under the else clause runs instead.

Here’s a simple example:

pythonCopy codeage = 20
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

In this example, the program will print "You are an adult." because the condition age >= 18 is true. If age were less than 18, it would print "You are a minor."

Learn more with the free online Python tutorial and use the free online Python editor to grow in your tech journey!