Understanding Conditionals in Python Programming

Aug 22, 2024

CS50 Introduction to Programming with Python - Conditionals

Presented by David Malan
Focus: Conditionals in Python, making decisions in code.


What are Conditionals?

  • Allow execution of different lines of code based on conditions.
  • Create logical forks in the code.

Comparison Operators in Python

  • Greater than: >
  • Greater than or equal to: >=
  • Less than: <
  • Less than or equal to: <=
  • Equality: == (two equal signs)
  • Not equal: !=

Using Conditionals in Python

  • Use the if keyword to ask questions.
  • Syntax:
    if condition:
        # code to execute
    
  • Example of comparisons:
    if X < Y:
        print("X is less than Y")
    elif X > Y:
        print("X is greater than Y")
    else:
        print("X is equal to Y")
    

Control Flow and Flowcharts

  • Code executes from top to bottom.
  • Use a flowchart to visualize logical flow:
    • Start -> Question (Boolean expression) -> True/False branches -> End

Improving Conditional Logic

  • Avoid asking unnecessary questions.
  • Use elif to chain conditions logically:
    if X < Y:
        # ...
    elif X > Y:
        # ...
    else:
        # ...
    
  • Using else provides a catch-all for when all previous conditions are false.

Example Program: Compare Values

  • Program compares user-input integers and prints results:
    X = int(input("What's X? "))
    Y = int(input("What's Y? "))
    if X < Y:
        print("X is less than Y")
    elif X > Y:
        print("X is greater than Y")
    else:
        print("X is equal to Y")
    

Further Enhancements

  • Use logical operators and, or to combine conditions:
    if (X > 90 and X <= 100):
        print("A")
    elif (X > 80 and X < 90):
        print("B")
    

Grading Example

  • Implementing grading logic based on score ranges:
    if score >= 90:
        print("A")
    elif score >= 80:
        print("B")
    elif score >= 70:
        print("C")
    elif score >= 60:
        print("D")
    else:
        print("F")
    

Using Functions

  • Create reusable functions for repeated logic:
    def is_even(n):
        return n % 2 == 0
    
    • Call functions within conditional statements.

Use of match Statement

  • New match statement as a more compact alternative to multiple if conditions:
    match name:
        case "Harry":
            print("Gryffindor")
        case "Hermione":
            print("Gryffindor")
        case "Ron":
            print("Gryffindor")
        case "Draco":
            print("Slytherin")
        case _:  # catch-all
            print("Who?")
    

Summary

  • Conditionals allow for logical decision-making in programming.
  • Use if, elif, else, and now match to structure your code effectively.
  • Aim for readability and conciseness to improve code quality.