Session 5 Conditional Logic
Conditional Logic
Indentation Matters if a == 1: print("If a is one, this will print.") print("So will this.") print("And this.") print("This will always print because it is not indented.")
Basic Comparisons ● greater than less than ● ● greater than or equal to ● less than or equal to ● equal to ● not equal to
Less Than/Greater Than #Example 1 # Variables used in the example ``if`` statements a = 4 b = 5 # Basic comparisons if a < b: print("a is less than b") if a > b: print("a is greater than b") print("Done")
Greater/Less Than or Equal To #example 2 if a <= b: print("a is less than or equal to b") if a >= b: print("a is greater than or equal to b")
Equal or Not Equal To #Example 3 # Equal if a == b: print("a is equal to b") # Not equal if a != b: print("a and b are not equal")
= does not mean == # This is wrong a == 1 # This is also wrong if a = 1: print("A is one")
And/Or # And if a < b and a < c: print("a is less than b and c") # Non-exclusive or if a < b or a < c: print("a is less than either b or c (or both)")
Boolean Variables ● True ● False # Boolean data type. This is legal! a = True if a: print("a is true")
Using And/Or with Booleans a = True b = False if a and b: print("a and b are both true")
if/else statement temperature = int(input("What is the temperature in Fahrenheit? ")) if temperature > 90: print("It is hot outside") else: print("It is not hot outside") print("Done")
if/elif/else temperature = int(input("What is the temperature in Fahrenheit? ")) if temperature > 90: print("It is hot outside") elif temperature < 30: print("It is cold outside") else: print("It is not hot outside") print("Done")
two_truths_lie.py #print 2 truths and a lie print('Welcome to Two Truths and a Lie! /n One of the following statements is a lie...you need to identify which one!') print('1. I have a donkey living in my backyard.') print('2. I have three fur babies') print('3. I speak four languages')
two_truths_lie.py #give instructions on how to guess and store the user input into a variable truth_or_lie = input('Now put in the number of the statement you think is the lie: 1, 2, or 3!') #convert the string input to an integer conv_truth_or_lie = int(truth_or_lie)
two_truths_lie.py #1st condition, the variable is 1 if conv_truth_or_lie == 1: print('Congrats, you have identified the lie correctly!') #2nd condition, the variable is 2 elif conv_truth_or_lie == 2: print('That is not the one!') #3rd condition, the variable is 3 elif conv_truth_or_lie == 3: print('Sorry, you have to try again')
Recommend
More recommend