Python - Decision MakingPosted by Aliya on February 23rd, 2019 Python - Decision MakingDecisions in a program are used when the program has conditional choices to execute code block. Let's take an example of traffic lights, where different colors of lights lit up at different situations based on the conditions of the road or any specific rule. Python provides various types of conditional statements:
If Statement:It's similar to other languages. The text if there is a reasonable word in comparison with the comparison data and the decision is based on the comparison result. Syntax:if expression: #execute your code If the Boolean character evaluates TRUE, the declaration of indoor inside if the report is to be enforced. The Boolean statement is assessed as SIGNATURE, the first code of code after the completion of the text if it will be output. Example:a = 15 if a > 10: print("a is greater") Output:a is greater Python if else Statement:Another text can be added if it is stated. Another text is included in the block of code to be executed if the condition is required if the text is 0 or FALSE value. Syntax:if expression: #execute your code else: #execute your code Example:a = 15 b = 20 if a > b: print("a is greater") else: print("b is greater") Output:b is greater Python Elif Statement:elif - is a keyword used in Python replacement of else if to place another condition in the program. This is called chained conditional. Syntax:if expression: #execute your code elif expression: #execute your code else: #execute your code Example:a = 15 b = 15 if a > b: print("a is greater") elif a == b: print("both are equal") else: print("b is greater") Output:both are equal Nested if Statement:There may be a situation you want to check for another situation after the situation is settled in reality. In these situations, you can use the optional equipment. Syntax:if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) elif expression4: statement(s) else: statement(s)else: statement(s) Example:#!/usr/bin/pythonvar = 100if var < 200: print "Expression value is less than 200" if var == 150: print "Which is 150" elif var == 100: print "Which is 100" elif var == 50: print "Which is 50" elif var < 50: print "Expression value is less than 50"else: print "Could not find true expression"print "Good bye!" Output:Expression value is less than 200Which is 100Good bye! Single Statement ConditionIf the textbooks can be implemented in one line only, the programs can write the same heading as header Statement. Example:a = 15 if (a == 15): print("The value of a is 15") Like it? Share it!More by this author |