Decision Making in Python Programming
Decision making In Python
In this tutorial we shall be looking at what all are the decision parameters that are available in Python.
There are three types of key words which are used in Python.
1) If : it works in that same fashion as we use it in English. Like if we win this match, the treat is on me. Let us look at an example.
c = 1 if c==1: print(“correct”) if c!=2: print(“not wrong”)
Output:correct not wrong
In the above program we compared c with 1 and it was true, so we got correct in the output. If it were not true, nothing would have happened, interpreter would have had checked the statement but since it did not match, so it skipped the print statement.
The second condition is also true as the value of c is not equal to two. So it printed not wrong.
2) Else: it also works the same way as we use it in English that is, an alternative for the if statement. For example, if it rains, then we would not go out to play but if it does not(else) then we will go out and play.
Let us look at an example to have a better understanding.
e = 24 if e==22: print(“correct”) else: print(“wrong”)
In the above code we compared the value of e with 22 if these values match the program will print correct but if it does not, the it prints wrong as we have given an alternative of else to it.
The interpreter checks the if statement, if it returns a true value, then it will execute the statement written in its indentation. But if the statement does not match that of the if statement then the interpreter looks for the else statement, in this case it encounters one, so it executes it.
3) Elif: it is used when we want to use both else and if that is, to add a statement that could be checked as the compiler straight away does whatever is written in the else statement.
Let us look at an example to get a better understanding
u = 55 if u == 50: print(‘True value is 50’) elif u== 55: print(‘True value is 55 ’)
Output: True value is 55
It will jump to elif only if the condition for the if statement is not true.
This is it for this tutorial, hope you guys enjoyed it and learned something from it.
Do not forget to practice as it is an important part of your learning.
See you in the next one!
Urgenthomework helped me with finance homework problems and taught math portion of my course as well. Initially, I used a tutor that taught me math course I felt that as if I was not getting the help I needed. With the help of Urgenthomework, I got precisely where I was weak: