Python Control Statements

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

It is very common for programs to execute statements based on some conditions. In this section we will learn about python if .. else ...  statement.

But before we need to learn about relational operators. Relational operators allows us to compare two objects.

Symbol Description
<=  smaller than or equal to
<  smaller than
>  greater than
>=  greater than or equal to
==  equal to
!=  not equal to

The result of comparision will always be a boolean value i.e True or  False . Remember True  and False  are python keyword for denoting boolean values.

Let take some examples:

Now you are ready to tackle if statements.The syntax of If statement  is:

Note: Each statements in the if block must be indented using the same number of spaces, otherwise it will lead to syntax error. This is very different from many other languages like Java, C, C# where curly braces (  {} ) is used.

Now let’s see an example


here you can see that if number is even then "Number is even"  is printed otherwise "Number is odd"  is printed.

Note: else clause is optional you can use only if clause if you want, like this

here when value of today  is "party"  then thumbs up!  will get printed, otherwise nothing will print.

If your programs needs to check long list of conditions then you need to use if-elif-else statements.

You can add as many elif condition as programs demands.

here is an example to illustrate if-elif-else  statement.

Nested if statements:

You can nest if statements  inside another if statements  as follows


In the next post we will learn about Python Functions.

Other Tutorials

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

Be the First to Comment!

Notify of