Python

With Examples, Teach The If Statement In Python – Q&A

If statements are control flow statements that enable us to only execute specific code when a predetermined condition is met. Programmers can use the if statement to, for instance, print a message on the screen only when a certain condition is met. With the help of examples, we will learn how to use if statements in Python programming in this book.

Python also has alternative control flow statements like if..else, if..elif..else, and else.
embedded if, etc. However, only the if statements will be addressed in this manual; the other control statements will be covered in later lessons.

Python If statement syntax

If statements in Python have a fairly straightforward syntax.

if condition:
   block_of_code

Python – If statement Example

flag = True
if flag==True:
    print("Welcome")
    print("To")
    print("BeginnersBook.com")

Output:

Welcome
To
BeginnersBook.com

The flag variable’s value is checked in the example above, and if it is True, a few print statements are executed. The crucial thing to remember is that even if we merely substituted “flag” for the word “condition,” the code would still function as intended. Therefore, the following would be a better approach to construct the code above:

flag = True
if flag:
    print("Welcome")
    print("To")
    print("BeginnersBook.com")

This helps us grasp how the if statement functions. Either true or false would be the result of the condition. If the result of the condition is true, the statements inside the body of the “if” are executed; if the result is false, the statements inside the “if” are skipped. Let’s use another illustration to further comprehend this

flag = False
if flag:
    print("You Guys")
    print("are")
    print("Awesome")

Because the result of the condition is “false,” the output of this code is none, which means that nothing is printed.

If example in Python without boolean variables

The boolean variables have been used in place of conditions in the instances above. Any variable can be used in our conditions, though. For instance:

num = 100
if num < 200:
    print("num is less than 200")

Output:

num is less than 200

Related Articles

Leave a Reply

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

Back to top button