Before checking out the conditional statements, let’s have a look at the various conditional operators.

Conditional Operators

Let’s take two integers a and b.

If a is greater than b, then it is denoted by a > b, and if a is smaller than b, it is denoted by a<b.

If a is the same as b, then we denote it as a==b. Note that a single ‘=’ is not used, as a single ‘=’ denotes assignment and not equality. If a is not equal to b, then we denote it as a!=b.

We also have the conditions greater than or equal to, and less than or equal to, which are denoted by >= and <= respectively.

Let’s now move on to if and else statements.

if and else

We need to make decisions in our daily life almost every day. The same is the case in programming. And for that, we need some statements that can take decisions and run some code when a condition is satisfied.

This is made possible by the if and else keywords. Note that Python relies heavily on indentation unlike C and C++, which use parentheses to demark the if and else statements.

Suppose, let us again take the two integers a and b. If a is greater than b, we will print the same, and vice versa. The following piece of code represents this –

if a>b:
   print('a is greater than b.')
else:
   print('b is greater than a.')

Note that without proper indentation, the above piece of code will not work. Also always remember that there should be a colon (:) always after the statements.

In the above piece of code, if the statement a>b fails to be true, then the control flow moves to the else statement, and the code block present after the colon is executed.

If the statement is true, then the code block present after if statement is executed.

In the next tutorial, we will look upon logical operators.

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019