Decision making in Python
Like most programming languages, Python also allows you to write code that perform different actions based on the results of a logical or comparative test conditions at run time. This means, we can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions. Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. WE need to determine which action to take and which statements to execute if outcome is TRUE or FALSE.
If then else
Python, like most languages, has an if statement for decision making. It consists of a boolean expression that if evaluated to true, will execute a code block. The if statement can also have an else> clause which will execute if the boolean expression evaluates to false. The if statement can be daisy chained to multiple if statements.
if(condition1) : # Code to be executed if condition1 is true elif(condition2) " # Code to be executed if the condition1 is false and condition2 is true else : # Code to be executed if both condition1 and condition2 are false
Switch statements
The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match. The major difference is that the test for the variable happens only once. This feature is available in Java and PHP but is not available in Python. We can emulate a switch statement by using a dictionary.
def one(): return "Sunday" def two(): return "Monday" def three(): return "Tuesday" def four(): return "Wednesday" def five(): return "Thursday" def six(): return "Friday" def seven(): return "Saturday" def numbers_to_day(argument): switcher = { 1: one, 2: two, 3: three, 4: four, 5: five, 6: six, 7: seven } func = switcher.get(argument, lambda: "Invalid month") print func()