Introduction to Programming in Python: Conditionals I PDF
Document Details
Uploaded by EnticingSuprematism
Università della Svizzera italiana
Walter Binder
Tags
Summary
This document provides an introduction to conditional statements in Python. It details the 'if' statement and guides through examples demonstrating its use. Practical aspects including the implementation of conditions for specific scenarios are briefly addressed.
Full Transcript
Introduction to Programming in Python Conditionals I Walter Binder Making Decisions in Python Real-life parallel Actions depend on conditions ○ Do only if condition is met if the weather is if weather == 'good': go...
Introduction to Programming in Python Conditionals I Walter Binder Making Decisions in Python Real-life parallel Actions depend on conditions ○ Do only if condition is met if the weather is if weather == 'good': good walk_outside() then walk outside 2 The if Statement (or Conditional expression Statement) if keyword (evaluate to True or False) if expression: # Executed only if # expression is truthy if body 3 if if expression: # Executed if expression is truthy if Keyword introducing a branch ○ branch: conditionally executed code section 4 If Header if expression: # Executed if expression is truthy if statement evaluates an expression ○ Python evaluates expression for its truthiness Always use colon 5 if Body if expression: # Executed if expression is truthy if body is a code block Must have same indentation Indented code run only if expression is truthy 6 Example: if if weather == 'good': walk_outside() if the weather is good 7 Example: if if weather == 'good': Begi walk_outside() End n if the weather is good then walk outside 8 Example: if if weather == 'good': walk_outside() walk_outside() # Code outside if branch If weather is different from 'good' ○ if body skipped 9 Understanding if What is the output of executing the following snippet? def price_with_discount(items, total): discount = 0 # There are two separate if statements if items >= 100: # → True: because items = 100 discount = 0.05 # Discount is 5% so far # This second if is not mutually exclusive to the first one if total >= 100_000: # → True: because total = 100_000 discount += 0.1 # Now discount is 15% return total * (1 - discount) # 15% discount applied print(price_with_discount(100, 100_000)) # → 85000.0 10 Exercise 10.1: Exercise: exam_classification(...) Implement exam_classification(...) as described in the docstring: ''' Computes an exam score. Note: use if statement. Parameters: score (int or float): the score from an exam. Must be positive. Note: use assert. Returns: (str): 'Fail' if score is below 60, otherwise 'Pass'. >>> exam_classification(59) 'Fail' >>> exam_classification(60) 'Pass' ''' 11 Making Decisions in Python Real-life parallel Do if condition is met Otherwise do another action if the weather is if weather == 'good': good walk_outside() then walk else: outside, stay_home() otherwise stay at home 12 if Statement with else if expression keyword (evaluate to True or False) if expression: # Executed only if # expression is truthy if body else: # Executed only if else body # expression is falsy else keyword (optional ) 13 else if expression: # Executed if expression is truthy else: # Executed if expression is falsy else Keyword introducing an alternative optional branch, following an if branch 14 else if expression: # Executed if expression is truthy else: # Executed if expression is falsy else definition require preceding if definition 15 else Header if expression: # Executed if expression is truthy else: # Executed if expression is falsy else: No expression Always use colon 16 else Body if expression: # Executed if expression is truthy else: # Executed if expression is falsy else body is a code block Must have same indentation Indented code run if expression is falsy 17 Example: if-else if weather == 'good': walk_outside() else: stay_home() if the weather is good 18 Example: if-else if weather == 'good': Begi walk_outside() End n else: stay_home() if the weather is good then walk outside, 19 Example: if-else if weather == 'good': walk_outside() else: stay_home() # Code outside if-else Alternative branch is skipped 20 Example: if-else if weather == 'good': walk_outside() else: stay_home() if the weather is good then walk outside, otherwise 21 Example: if-else if weather == 'good': walk_outside() else: Begi stay_home() End n if the weather is good then walk outside, otherwise stay at home 22 Example: if-else if weather == 'good': walk_outside() walk_outside() else: stay_home() # Code outside if-else If weather is different from 'good' ○ Only alternative (else) branch executed 23 Understanding if-else What is the output of executing the following snippet? def classify_number(num): # if and else are mutually exclusive if num % 2 == 0: # → False: because 7 % 2 == 1 return 'Even' # Not executed else: # The evaluated expression was falsy return 'Odd' # Then, else branch is executed print(classify_number(7)) # → Odd 24 Exercise 10.2: Exercise: absolute_difference(...) Implement absolute_difference(...) as described in the docstring: ''' Computes the absolute difference between two numbers. Note: use if-else. Parameter: num1 (int or float): the first number. num2 (int or float): the second number. Returns: (int or float): the absolute difference between the numbers. >>> absolute_difference(5, 3) 2 >>> absolute_difference(3, 5) 2 ''' 25 Ternary Operator Ternary operator Concise syntax for if-else in one line Given: expression1 if Condition else expression2 Evaluate Condition If Condition is truthy ○ Evaluate expression1 and return its resulting value Otherwise ○ Evaluate expression2 and return its resulting value 26 Understanding the Ternary Return value assigned condition is evaluated first Operator res = 'Even' if num % 2 == 0 else 'Odd' evaluated and evaluated and returned if returned if condition is true condition is false Unlike if statement, ternary operator is an expression Can be used in assignments ○ E.g., res is assigned the ternary-operator return value 27 Exercise 10.3: absolute_value(...) Exercise: Implement absolute_value(...) as described in the docstring: ''' Computes the absolute value of a given number. Note: use the ternary operator. Parameter: num (int or float): the number to find the absolute value of. Returns: (int or float): the absolute value of the number. >>> absolute_value(-5) 5 >>> absolute_value(5) 5 >>> absolute_value(0) 0 ''' Note: there is built-in function to compute the absolute value: 28 abs(...), which we will study later in the course… Chaining Ternary Operators Ternary operators can be chained For readability, use only for simple assignments or expressions Evaluation from left to right left condition is right first evaluated condition res = 'Pass' if grade > 60 else 'Retake' if grade >= 45 else 'Fail' evaluated and evaluated and evaluated and returned returned if right returned if right if left condition is condition isevaluated true condition is false and true returned only if left condition is 29 Exercise 10.4: Debugging - Ternary Operator Chaining Exercise: Execute the following changing grade and check the outputs grade = 90 print('Pass' if grade > 60 else 'Retake' if grade >= 45 else 'Fail') If needed, use debugging mode to further inspect step-by-step execution 30 Key Takeaways: Keywords Keyword Short definition if To introduce a branch else To introduce an alternative branch, following an if branch 31 Key Takeaways: if statement if expression keyword (evaluate to True or False) if expression: # Executed only if # expression is truthy if body 32 Key Takeaways: if Statement with if expression else keyword (evaluate to True or False) if expression: # Executed only if # expression is truthy if body else: # Executed only if else body # expression is falsy else keyword (optional ) 33 Key Takeaways: Ternary Operator left condition is right first evaluated condition res = 'Pass' if grade > 60 else 'Retake' if grade >= 45 else 'Fail' evaluated and evaluated and evaluated and returned returned if right returned if right if left condition is condition isevaluated true condition is false and true returned only if left condition is false 34 Quiz 10 Ready to test your knowledge? 35