DEV Community

ice8980
ice8980

Posted on

A Brief Introduction to if/else statements in Python

Did you know if and else statements are very important in python? When we ask questions we often ask about yes or no questions and decide to do something based on the answer. For example, we might ask "are you happy" and if the answer is yes, respond "good for you!" These types of questions are called conditions, and statements. These questions can be like if/else statements in python.

In this article, you'll learn about if/else statements in python.

IF STATEMENTS

boys = 10 
if boys > 10:
    print('there are a lot of boys!')
Enter fullscreen mode Exit fullscreen mode

An if statement in python is just like in English. For example, in English, we can say if there are 10 boys and if the boys are greater than ten say "there are a lot of boys!" This is the same for python but in python, we need to make a variable for what boys is and add a colon (:). The if statement in the code on top of this paragraph says if the boys are greater than 10 say "there are a lot of boys!" but instead we use the print keyword.

MORE INFO

if age < 20:
    print('you are young')
    print('hellooooo')
Enter fullscreen mode Exit fullscreen mode

Do you notice that inside the if statement there will be four spaces? The four spaces in very important because the four spaces tell python that the code is in the if statement. if we don't put the four spaces this error will appear.

IndentationError: expected an indented block
KeyboardInterrupt 
Enter fullscreen mode Exit fullscreen mode

This error will appear because a dumb programming language cannot understand if the code is in the if statement or not.

IF THEN ELSE STATEMENTS

If we want to add something if the if the condition is true we can use if then else statements.

boys = 20
if boys == 20:
    print("there are 20 boys")
else:
    print("there are not 20 boys")
Enter fullscreen mode Exit fullscreen mode

The code on tops says that there are 20 boys and if there are 20 boys print "there are 20 boys" but if the condition is False print "there are not 20 boys".

CONCLUSION
In conclusion, that is if/else statements.

Top comments (0)