Conditions and loops

Conditions are checked using a left and right value comparison. The evaluation returns either true or false, and a specific action is performed depending on the result.

There are certain condition operators that are used to evaluate the left and right value comparisons:

Operators Meaning
== If both values are equal
!= If both values are NOT equal
> If the left value is greater than the right value
< If the left value is smaller than the right value
>= If the left value is greater than or equal to the right value
<= If the left value is lesser than or equal to the right value
in If the left value is part of the right value

 

An example of the condition evaluation is as follows:

As we can see, we are checking whether 2>3 (2 is greater that 3). Of course, this would result in false, so the action in the else section is executed. If we reverse the check, 3>2, then the output would have been left value is greater.

In the preceding example, we used the if condition block, which consists of the following:

if <condition>:     
perform action
else:
perform action2

Notice the indentation, which is compulsory in Python. If we had not intended it, Python would not interpret what action to execute in which condition, and hence would have thrown an error of incorrect indentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.186.92