Functions & if-elif-else
What is a function?
A function is a named block of code that performs a specific task. You give it inputs (arguments), it does the work and may give back a result (return value). Think of a juice machine: put in oranges (input), press the button (call), get juice (output).
Built-in functions
prices = [120, 45, 300, 75]
print(len(prices), max(prices), min(prices), sum(prices))
print(abs(-15), round(7.468, 1), pow(2, 5))
print(int('80') + 20, float('2.5') * 4, type(3.0))| Function | Use |
|---|---|
| print(), input() | Output and input |
| int(), float(), str(), bool() | Type conversion |
| len(), max(), min(), sum(), sorted() | Work on sequences |
| abs(), round(), pow(), divmod() | Number helpers |
| type(), id() | Type and identity of an object |
Functions from modules
A module is a file of ready functions. Import it before use.
import math import statistics as st print(math.sqrt(625), math.ceil(4.01), math.floor(4.99)) marks = [56, 72, 72, 90, 64] print(st.mean(marks), st.median(marks), st.mode(marks))
User-defined functions
def function_name(parameter1, parameter2=default):
statements
return valuedef gst_amount(price, rate=18):
"""Return the GST on a price."""
return price * rate / 100
def final_price(price, rate=18):
return price + gst_amount(price, rate)
print(gst_amount(1000)) # default rate 18%
print(gst_amount(1000, 5)) # 5% rate
print(final_price(2500, 12))final_price calls gst_amount — functions can use other functions, which keeps each one small and easy to test.
return vs print
def show_line(ch, n):
print(ch * n) # this function only prints
show_line('=', 20)
result = show_line('-', 10)
print(result)A function without return gives back None. Use return when the result is needed for further calculation; use print only to display.
Decision making with if
Programs must often choose between actions. The if statement checks a condition; if it is True, the indented block runs. The optional else block runs when the condition is False.
temp = float(input('Room temperature: '))
if temp > 30:
print('Switch on the AC')
else:
print('Fan is enough')if-elif-else
For more than two choices, use elif. Python checks each condition in order and runs only the first block that is True. Example: Air Quality Index categories.
aqi = int(input('Enter AQI: '))
if aqi <= 50:
status = 'Good'
elif aqi <= 100:
status = 'Satisfactory'
elif aqi <= 200:
status = 'Moderate'
elif aqi <= 300:
status = 'Poor'
else:
status = 'Very Poor / Severe'
print('Air quality:', status)Nested if
age = int(input('Age: '))
has_licence = input('Licence (y/n): ')
if age >= 18:
if has_licence == 'y':
print('You can drive')
else:
print('Get a licence first')
else:
print('Too young to drive')Functions + conditions together
def ticket_price(age):
if age < 5:
return 0
elif age < 12 or age >= 60:
return 50
else:
return 100
for a in (3, 8, 25, 65):
print('Age', a, '-> Rs.', ticket_price(a))Summary & practice
- Built-in functions (len, max, round…), module functions (math, statistics) and user-defined functions (def).
returnsends back a value; no return → None.if,if-else,if-elif-else, nested if; colon and indentation are compulsory.
1) Write a function bmi(weight, height) that returns BMI = weight ÷ height², and print "Underweight" (< 18.5), "Normal" (18.5–24.9) or "Overweight" (≥ 25). 2) Write a function that returns the larger of two numbers without using max().
