# -*- coding: utf-8 -*- """ Created on Wed Sep 30 11:47:45 2020 @author: jbobowsk """ # This tutorial will introduce simple implementations of conditional if # statements in MATLAB. # Here's a simple if statement. If statements use the same indentation # scheme as for loops. Indented lines immediately following the if # statement are within the if control sturcture. The if statement ends # when the indented block of code ends. ans = 'y' if ans == 'y': print('yes') # In the example above, ans was set equal to 'y' and the if condition was # true such that 'yes' was printed. In the example below, ans is not equal # to 'y' and the if condition is false. As a result, no output is printed. ans = 'n' if ans == 'y': print('yes') # We can enhance the capability of our if statement by adding an else # statement. Anytime the if condition is false, the else statement will # execute. # True, so 'yes' output. ans = 'y' if ans == 'y': print('yes') else: print('no') # False, so 'no' output. ans = 'n' if ans == 'y': print('yes') else: print('no') # False, so 'no' output. ans = 'x' if ans == 'y': print('yes') else: print('no') # In the above if statement the only "y" produces a "yes", any other entry # results in "no". Suppose that you only want to accept "y" and "n" as # valid responses. Including an 'else if' condtion (using 'elif') as done # below produces the desired results. # If condition true, so output 'yes'. ans = 'y' if ans == 'y': print('yes') elif ans == 'n': print('no') else: print('invalid response') # Elseif condition true, so output 'no'. ans = 'n'; if ans == 'y': print('yes') elif ans == 'n': print('no') else: print('invalid response') # If and elseif conditions false, so output 'invalid response'. ans = 'x'; if ans == 'y': print('yes') elif ans == 'n': print('no') else: print('invalid response') # To complete this tutorial, here's how you can prompt the user for an # input in Python. All you need to do is use the 'input()' statement. val = input("Enter your value: ") if val == 'y': print('yes') elif val == 'n': print('no') else: print('invalid response')