Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🐍 Unit 2 – Python Programming  ·  Lesson 06

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).

Argumentsprice = 1000, rate = 18Function bodyprice * rate / 100Return value180.0
A function takes input and returns output

Built-in functions

Python
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))
4 300 45 540 15 7.5 32 100 10.0 <class 'float'>
FunctionUse
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.

Python
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))
25.0 5 4 70.8 72 72

User-defined functions

Syntax
def function_name(parameter1, parameter2=default):
    statements
    return value
Python
def 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))
180.0 50.0 2800.0

final_price calls gst_amount — functions can use other functions, which keeps each one small and easy to test.

return vs print

Python
def show_line(ch, n):
    print(ch * n)            # this function only prints

show_line('=', 20)
result = show_line('-', 10)
print(result)
==================== ---------- None

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.

StartInput temptemp > 30 ?YesNoPrint "Fan is enough"Print "Switch on the AC"Stop
if-else as a flowchart
Python
temp = float(input('Room temperature: '))
if temp > 30:
    print('Switch on the AC')
else:
    print('Fan is enough')
Room temperature: 33.5 Switch on the AC

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.

Python
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)
Enter AQI: 187 Air quality: Moderate
AQI category limits used in the program0100200300400500GoodSatisf.ModeratePoorV.Poor50100200300400
AQI 187 falls in the Moderate bar

Nested if

Python
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')
Age: 19 Licence (y/n): n Get a licence first

Functions + conditions together

Python
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))
Age 3 -> Rs. 0 Age 8 -> Rs. 50 Age 25 -> Rs. 100 Age 65 -> Rs. 50

Summary & practice

  • Built-in functions (len, max, round…), module functions (math, statistics) and user-defined functions (def).
  • return sends back a value; no return → None.
  • if, if-else, if-elif-else, nested if; colon and indentation are compulsory.
✅ Practice

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().

Frequently Asked Questions

What is the difference between a built-in and a user-defined function?
Built-in functions such as len(), max() and print() come with Python. User-defined functions are written by the programmer using the def keyword.
Why is indentation important in if statements?
Indentation tells Python which statements belong to the if or else block. Wrong indentation gives an IndentationError or makes the wrong statements run.
Can a function have a default parameter?
Yes, e.g. def gst_amount(price, rate=18). If the caller does not pass rate, 18 is used.
← Class 11 Informatics Practices
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicfor Loop, range() & Nested Loops Your progress: 6 / 20 (30%) · Lesson 7 / 20 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free