Software DevelopmentLearn Decision making using IF Conditions in Python

Learn Decision making using IF Conditions in Python

In Part4 (Arithmetic and Logical Operators), we have discussed the Simple Comparison Operations. After that, we talked very quickly about the Logical Operators. Now, it is time to build upon what we have learned in the previous Part. In this article, we will talk about Decision Making using the well known developing tool: if statement.

* * * * * *

Decision Making

Life doesn’t go one way. Our every day’s life is full of events that require making decision in someway. In the morning, I woke up late, so I should hurry to leave for my work and be there in time. But, what about breakfast?! I have two choices, either to have my breakfast at home, and be ready for hearing the blame from my manager, or to skip breakfast and leave quickly for work (and think about having sandwich or something else until the lunch hour comes). Despite being quite trivial situation, it gives us a good example for decision making.

If statement

The most common developing tool in use for decision making is the if statement. You may never find a programming languages that don’t support the if statement. Though its syntax differs from language to another, the logic is the same in all. The following is the syntax of the if statement in Python:

```if  condition:

one-or-more-statements```

The syntax consists of:

1. The reserved word if
2. A condition followed by a colon (:). The condition could be any expression that evaluates to True of False; i.e. it could be a simple comparison, a composite expression using logical operators, or even the Boolean values True or False themselves.
3. One or more statements, to be executed if the condition is met. These statements must be indented (shifted) to the right an equal amount of spaces. (You remember when I told you that Python cares about leading white spaces; I think you got the reason now).

Note:

If you have some experience working with C/C++, Java, or Perl, you would know that these languages use the curly braces { } to delimit the body of the loops and if statements. But in Python, no delimiters used to mark the start or the end of such blocks, just indentation.

Example

Let’s make things clear by example. The following script asks the user to enter a positive integer to calculate the factorial for.

Image 1: A script that calculates the factorial for an integer.

When we execute the script, it should return the factorial if the entered number is an integer.

Image 2: Executing the factorial script.

Now, to the explanation:

• Line 1: imports the math This is because our script uses the mathematical function factorial().
• Line 2: uses the function input() to prompt the user to enter a positive integer. The input is then passed to the function eval() to evaluate it. The result is assigned to the variable x.
• Line 3: checks the type of the variable x. If found to be an integer, the next two lines (Lines 4 and 5) will be executed. If not, nothing will happen (for now).

This uses the syntax we specified above:

`if type(x) == int:`

The reserved word if , followed by the conditional expression. Here the expression tests for equality (if the type of x equals integer). And the colon (:) to terminate the line.

• Lines 4 and 5: calculate the Factorial, assigns the result to the vaiable y, and then prints the result.
• One last thing to illustrate: the use of the new line character ‘\n’. Using ‘\n’ causes the text cursor to move down to the beginning of the next line.

* * * * * *

If…Else

Now, users of your scripts have complained they enter values, but the script returns nothing. They want to get a friendly message to tell them what is wrong!!

To see how to achieve their requirement, check this modified version of the factorial script.
Image 3: Modified version of the factorial script using IF…Else structure.

Image 4: The modified version prints a message to the user if he enters wrong input.

Explanation:

• Line 6: uses the reserved word else followed by a colon (:) to give the alternate (and the last) route if the first one has failed.
• Line 7: prints a message to the user to tell him that he entered an invalid input.

So simple and logic, isn’t it?!

* * * * * *

If…Elif…Else

Consider the following case:
Image 5: Interpreter generates an error when the user enters a negative number.

Did you see that?! Although I entered an integer, the interpreter gave an error!!

Yes, because you have entered a negative integer, while the script asked you to enter a positive one!!

That is true!! But it would be better if the script makes some more validation on the input to detect and warn the user if he entered a negative value, don’t you agree with me?

Image 6: Modified Version of the factorial script that validates for negative input.

Let’s execute this modified version:
Image 7: The script warns the user if he enters a negative number.

Great!! It performs the required validation step. Now, to the explanation:

• Line 3: checks if the entered number is less than 0. If so, Line 4 is executed to print a warning message to the user, that he has entered a negative number.
• Line 5: the elif (else if), is checked if the condition in the if statement in Line 3 is not met. It checks the type of the entered value.
• Line 8: the last resort; the else statement that is executed if neither of the condition above is met.

* * * * * *

In this article, we have talked about the if statement. We have discussed the concepts, and illustrated them with examples. Understanding the decision making mechanism using conditions is essential for any developer. So, I hope you like this article, and find it simple and useful.

Best Graphic Design Softwares In 2022

21,501Fans
4,221Followers
103,000Subscribers