Python Conditional Statements and Functions
After Completing This Topic
You will be able to create branches using if/elif/else and define functions using def to reuse code.
Conditional Statements β if, elif, else
Programs need to "behave differently depending on the situation." This is what conditional statements are for.
score = 85
if score >= 90: print("A grade")elif score >= 80: print("B grade")elif score >= 70: print("C grade")else: print("Retake")
# Output: B gradeConditions are checked in order from top to bottom. The first block that evaluates to True is executed, and the rest are skipped.
Indentation is Syntax
# β
Correctif True: print("Executed")
# β IndentationErrorif True:print("Error!")Python uses indentation (usually 4 spaces) instead of curly braces to define blocks. Incorrect indentation will result in a syntax error. Do not mix tabs and spaces.
Comparison and Logical Operators
# Comparison operatorsx = 10print(x > 5) # Trueprint(x == 10) # True (equal to)print(x != 10) # False (not equal to)print(x >= 10) # True (greater than or equal to)
# Logical operatorsage = 25has_id = True
if age >= 18 and has_id: print("Allowed to enter")
if age < 18 or not has_id: print("Not allowed to enter")| Operator | Meaning | Example |
|---|---|---|
and | Both are True | A and B |
or | At least one is True | A or B |
not | Invert | not A |
Functions β def
Instead of writing the same code multiple times, group it into a function and give it a name.
def greet(name): print(f"Hello, {name}!")
greet("Kim Hoon") # Hello, Kim Hoon!greet("Lee Soo") # Hello, Lee Soo!def function_name(parameters): β The indented block is the function body. The function is not executed until it is called.
return β Returning a Value
def add(a, b): return a + b
result = add(3, 5)print(result) # 8
# If there is no return, None is returneddef say_hello(): print("hello")
x = say_hello() # Prints "hello"print(x) # Noneprint() displays something on the screen, while return returns a value. These are completely different roles.
Default Values and Keyword Arguments
def power(base, exponent=2): return base ** exponent
print(power(3)) # 9 (Uses the default value of exponent=2)print(power(3, 3)) # 27 (Specifies exponent=3)
# Keyword arguments β order does not matterprint(power(exponent=4, base=2)) # 16Parameters with default values can be omitted when calling the function.
Variables Inside Functions β Scope
x = 10 # Global variable
def foo(): x = 20 # Local variable β only valid inside the function print(x) # 20
foo()print(x) # 10 β The global x did not changeVariables created inside a function disappear when the function finishes. Even if they have the same name as variables outside the function, they are separate variables. This is called scope.
Conditional Statements + Functions = Logic
def classify_bmi(weight, height): bmi = weight / (height ** 2)
if bmi < 18.5: return "Underweight" elif bmi < 25: return "Normal" elif bmi < 30: return "Overweight" else: return "Obese"
print(classify_bmi(70, 1.75)) # Normalprint(classify_bmi(90, 1.70)) # OverweightCreating branches with conditional statements and making code reusable with functions. Combining these two can express most of a program's logic.