Friday, May 29, 2026

150 Python Function Programs Question + Formula/Logic + Complete Program

 


150 Python Function Programs

Question + Formula/Logic + Complete Program

All programs use user-defined functions, short function names, parameters, and return statements wherever suitable.


 

Sequential Programs

S1. Sum of Two Numbers

Question: Write a Python program using a function to sum of two numbers.

Formula/Logic: sum = a + b

Complete Program:

def add(a, b):

    return a + b

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

ans = add(a, b)

print("Sum =", ans)

S2. Difference of Two Numbers

Question: Write a Python program using a function to difference of two numbers.

Formula/Logic: difference = a - b

Complete Program:

def sub(a, b):

    return a - b

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

ans = sub(a, b)

print("Difference =", ans)

S3. Product of Two Numbers

Question: Write a Python program using a function to product of two numbers.

Formula/Logic: product = a * b

Complete Program:

def mul(a, b):

    return a * b

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

ans = mul(a, b)

print("Product =", ans)

S4. Division of Two Numbers

Question: Write a Python program using a function to division of two numbers.

Formula/Logic: division = a / b

Complete Program:

def div(a, b):

    return a / b

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

ans = div(a, b)

print("Division =", ans)

S5. Remainder of Two Numbers

Question: Write a Python program using a function to remainder of two numbers.

Formula/Logic: remainder = a % b

Complete Program:

def rem(a, b):

    return a % b

 

a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

ans = rem(a, b)

print("Remainder =", ans)

S6. Square of a Number

Question: Write a Python program using a function to square of a number.

Formula/Logic: square = n ** 2

Complete Program:

def square(n):

    return n ** 2

 

n = float(input("Enter number: "))

ans = square(n)

print("Square =", ans)

S7. Cube of a Number

Question: Write a Python program using a function to cube of a number.

Formula/Logic: cube = n ** 3

Complete Program:

def cube(n):

    return n ** 3

 

n = float(input("Enter number: "))

ans = cube(n)

print("Cube =", ans)

S8. Average of Three Numbers

Question: Write a Python program using a function to average of three numbers.

Formula/Logic: average = (a+b+c)/3

Complete Program:

def avg3(a, b, c):

    return (a + b + c) / 3

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

c = float(input("Enter third number: "))

ans = avg3(a, b, c)

print("Average =", ans)

S9. Sum and Product of Three Numbers

Question: Write a Python program using a function to sum and product of three numbers.

Formula/Logic: sum=a+b+c, product=a*b*c

Complete Program:

def sumprod3(a, b, c):

    s = a + b + c

    p = a * b * c

    return s, p

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

c = float(input("Enter third number: "))

ans = sumprod3(a, b, c)

print("Sum =", ans[0])

print("Product =", ans[1])

S10. Area of Rectangle

Question: Write a Python program using a function to area of rectangle.

Formula/Logic: area = length * breadth

Complete Program:

def rect_area(l, b):

    return l * b

 

l = float(input("Enter length: "))

b = float(input("Enter breadth: "))

ans = rect_area(l, b)

print("Area =", ans)

S11. Perimeter of Rectangle

Question: Write a Python program using a function to perimeter of rectangle.

Formula/Logic: perimeter = 2 * (length + breadth)

Complete Program:

def rect_peri(l, b):

    return 2 * (l + b)

 

l = float(input("Enter length: "))

b = float(input("Enter breadth: "))

ans = rect_peri(l, b)

print("Perimeter =", ans)

S12. Area of Square

Question: Write a Python program using a function to area of square.

Formula/Logic: area = side ** 2

Complete Program:

def sq_area(s):

    return s ** 2

 

s = float(input("Enter side: "))

ans = sq_area(s)

print("Area =", ans)

S13. Perimeter of Square

Question: Write a Python program using a function to perimeter of square.

Formula/Logic: perimeter = 4 * side

Complete Program:

def sq_peri(s):

    return 4 * s

 

s = float(input("Enter side: "))

ans = sq_peri(s)

print("Perimeter =", ans)

S14. Area of Circle

Question: Write a Python program using a function to area of circle.

Formula/Logic: area = 3.14 * r * r

Complete Program:

def cir_area(r):

    return 3.14 * r * r

 

r = float(input("Enter radius: "))

ans = cir_area(r)

print("Area =", ans)

S15. Circumference of Circle

Question: Write a Python program using a function to circumference of circle.

Formula/Logic: circumference = 2 * 3.14 * r

Complete Program:

def cir_circ(r):

    return 2 * 3.14 * r

 

r = float(input("Enter radius: "))

ans = cir_circ(r)

print("Circumference =", ans)

S16. Diameter of Circle

Question: Write a Python program using a function to diameter of circle.

Formula/Logic: diameter = 2 * r

Complete Program:

def diameter(r):

    return 2 * r

 

r = float(input("Enter radius: "))

ans = diameter(r)

print("Diameter =", ans)

S17. Area of Triangle

Question: Write a Python program using a function to area of triangle.

Formula/Logic: area = 0.5 * base * height

Complete Program:

def tri_area(b, h):

    return 0.5 * b * h

 

b = float(input("Enter base: "))

h = float(input("Enter height: "))

ans = tri_area(b, h)

print("Area =", ans)

S18. Perimeter of Triangle

Question: Write a Python program using a function to perimeter of triangle.

Formula/Logic: perimeter = a + b + c

Complete Program:

def tri_peri(a, b, c):

    return a + b + c

 

a = float(input("Enter side 1: "))

b = float(input("Enter side 2: "))

c = float(input("Enter side 3: "))

ans = tri_peri(a, b, c)

print("Perimeter =", ans)

S19. Volume of Cube

Question: Write a Python program using a function to volume of cube.

Formula/Logic: volume = side ** 3

Complete Program:

def cube_vol(s):

    return s ** 3

 

s = float(input("Enter side: "))

ans = cube_vol(s)

print("Volume =", ans)

S20. Surface Area of Cube

Question: Write a Python program using a function to surface area of cube.

Formula/Logic: surface_area = 6 * side * side

Complete Program:

def cube_sa(s):

    return 6 * s * s

 

s = float(input("Enter side: "))

ans = cube_sa(s)

print("Surface Area =", ans)

S21. Volume of Cuboid

Question: Write a Python program using a function to volume of cuboid.

Formula/Logic: volume = l * b * h

Complete Program:

def cuboid_vol(l, b, h):

    return l * b * h

 

l = float(input("Enter length: "))

b = float(input("Enter breadth: "))

h = float(input("Enter height: "))

ans = cuboid_vol(l, b, h)

print("Volume =", ans)

S22. Surface Area of Cuboid

Question: Write a Python program using a function to surface area of cuboid.

Formula/Logic: surface_area = 2*(lb + bh + hl)

Complete Program:

def cuboid_sa(l, b, h):

    return 2 * (l*b + b*h + h*l)

 

l = float(input("Enter length: "))

b = float(input("Enter breadth: "))

h = float(input("Enter height: "))

ans = cuboid_sa(l, b, h)

print("Surface Area =", ans)

S23. Volume of Cylinder

Question: Write a Python program using a function to volume of cylinder.

Formula/Logic: volume = 3.14*r*r*h

Complete Program:

def cyl_vol(r, h):

    return 3.14 * r * r * h

 

r = float(input("Enter radius: "))

h = float(input("Enter height: "))

ans = cyl_vol(r, h)

print("Volume =", ans)

S24. Surface Area of Cylinder

Question: Write a Python program using a function to surface area of cylinder.

Formula/Logic: surface_area = 2*3.14*r*(r+h)

Complete Program:

def cyl_sa(r, h):

    return 2 * 3.14 * r * (r + h)

 

r = float(input("Enter radius: "))

h = float(input("Enter height: "))

ans = cyl_sa(r, h)

print("Surface Area =", ans)

S25. Volume of Sphere

Question: Write a Python program using a function to volume of sphere.

Formula/Logic: volume = (4/3)*3.14*r**3

Complete Program:

def sphere_vol(r):

    return (4/3) * 3.14 * r ** 3

 

r = float(input("Enter radius: "))

ans = sphere_vol(r)

print("Volume =", ans)

S26. Surface Area of Sphere

Question: Write a Python program using a function to surface area of sphere.

Formula/Logic: surface_area = 4*3.14*r*r

Complete Program:

def sphere_sa(r):

    return 4 * 3.14 * r * r

 

r = float(input("Enter radius: "))

ans = sphere_sa(r)

print("Surface Area =", ans)

S27. Volume of Cone

Question: Write a Python program using a function to volume of cone.

Formula/Logic: volume = (1/3)*3.14*r*r*h

Complete Program:

def cone_vol(r, h):

    return (1/3) * 3.14 * r * r * h

 

r = float(input("Enter radius: "))

h = float(input("Enter height: "))

ans = cone_vol(r, h)

print("Volume =", ans)

S28. Simple Interest

Question: Write a Python program using a function to simple interest.

Formula/Logic: si = (p*t*r)/100

Complete Program:

def simple_int(p, t, r):

    return (p * t * r) / 100

 

p = float(input("Enter principal: "))

t = float(input("Enter time: "))

r = float(input("Enter rate: "))

ans = simple_int(p, t, r)

print("Simple Interest =", ans)

S29. Compound Interest

Question: Write a Python program using a function to compound interest.

Formula/Logic: ci = p*((1+r/100)**t)-p

Complete Program:

def comp_int(p, r, t):

    return p * ((1 + r/100) ** t) - p

 

p = float(input("Enter principal: "))

r = float(input("Enter rate: "))

t = float(input("Enter time: "))

ans = comp_int(p, r, t)

print("Compound Interest =", ans)

S30. Amount After Interest

Question: Write a Python program using a function to amount after interest.

Formula/Logic: amount = principal + interest

Complete Program:

def amount_si(p, si):

    return p + si

 

p = float(input("Enter principal: "))

si = float(input("Enter interest: "))

ans = amount_si(p, si)

print("Amount =", ans)

S31. Percentage of Marks

Question: Write a Python program using a function to percentage of marks.

Formula/Logic: percentage = obtained/total*100

Complete Program:

def percent(o, t):

    return (o / t) * 100

 

o = float(input("Enter obtained marks: "))

t = float(input("Enter total marks: "))

ans = percent(o, t)

print("Percentage =", ans)

S32. Total and Average of Five Subjects

Question: Write a Python program using a function to total and average of five subjects.

Formula/Logic: total=m1+...+m5, average=total/5

Complete Program:

def marks5(m1, m2, m3, m4, m5):

    total = m1 + m2 + m3 + m4 + m5

    avg = total / 5

    return total, avg

 

m1 = float(input("Enter mark 1: "))

m2 = float(input("Enter mark 2: "))

m3 = float(input("Enter mark 3: "))

m4 = float(input("Enter mark 4: "))

m5 = float(input("Enter mark 5: "))

ans = marks5(m1, m2, m3, m4, m5)

print("Total =", ans[0])

print("Average =", ans[1])

S33. Profit

Question: Write a Python program using a function to profit.

Formula/Logic: profit = selling_price - cost_price

Complete Program:

def profit(cp, sp):

    return sp - cp

 

cp = float(input("Enter cost price: "))

sp = float(input("Enter selling price: "))

ans = profit(cp, sp)

print("Profit =", ans)

S34. Loss

Question: Write a Python program using a function to loss.

Formula/Logic: loss = cost_price - selling_price

Complete Program:

def loss(cp, sp):

    return cp - sp

 

cp = float(input("Enter cost price: "))

sp = float(input("Enter selling price: "))

ans = loss(cp, sp)

print("Loss =", ans)

S35. Discount Amount

Question: Write a Python program using a function to discount amount.

Formula/Logic: discount = price * rate / 100

Complete Program:

def discount(price, rate):

    return price * rate / 100

 

price = float(input("Enter marked price: "))

rate = float(input("Enter discount rate: "))

ans = discount(price, rate)

print("Discount =", ans)

S36. Selling Price After Discount

Question: Write a Python program using a function to selling price after discount.

Formula/Logic: sp = marked_price - discount

Complete Program:

def sp_disc(mp, disc):

    return mp - disc

 

mp = float(input("Enter marked price: "))

disc = float(input("Enter discount: "))

ans = sp_disc(mp, disc)

print("Selling Price =", ans)

S37. VAT Amount

Question: Write a Python program using a function to vat amount.

Formula/Logic: vat = price * rate / 100

Complete Program:

def vat(price, rate):

    return price * rate / 100

 

price = float(input("Enter price: "))

rate = float(input("Enter VAT rate: "))

ans = vat(price, rate)

print("VAT =", ans)

S38. Final Price After VAT

Question: Write a Python program using a function to final price after vat.

Formula/Logic: final_price = price + vat

Complete Program:

def final_vat(price, vat):

    return price + vat

 

price = float(input("Enter price: "))

vat = float(input("Enter VAT amount: "))

ans = final_vat(price, vat)

print("Final Price =", ans)

S39. Celsius to Fahrenheit

Question: Write a Python program using a function to celsius to fahrenheit.

Formula/Logic: f = c*9/5 + 32

Complete Program:

def to_fahr(c):

    return c * 9/5 + 32

 

c = float(input("Enter Celsius: "))

ans = to_fahr(c)

print("Fahrenheit =", ans)

S40. Fahrenheit to Celsius

Question: Write a Python program using a function to fahrenheit to celsius.

Formula/Logic: c = (f-32)*5/9

Complete Program:

def to_cels(f):

    return (f - 32) * 5/9

 

f = float(input("Enter Fahrenheit: "))

ans = to_cels(f)

print("Celsius =", ans)

S41. Kilometer to Meter

Question: Write a Python program using a function to kilometer to meter.

Formula/Logic: meter = kilometer * 1000

Complete Program:

def km_m(km):

    return km * 1000

 

km = float(input("Enter kilometer: "))

ans = km_m(km)

print("Meter =", ans)

S42. Meter to Centimeter

Question: Write a Python program using a function to meter to centimeter.

Formula/Logic: centimeter = meter * 100

Complete Program:

def m_cm(m):

    return m * 100

 

m = float(input("Enter meter: "))

ans = m_cm(m)

print("Centimeter =", ans)

S43. Kilogram to Gram

Question: Write a Python program using a function to kilogram to gram.

Formula/Logic: gram = kilogram * 1000

Complete Program:

def kg_g(kg):

    return kg * 1000

 

kg = float(input("Enter kilogram: "))

ans = kg_g(kg)

print("Gram =", ans)

S44. Hour to Minute

Question: Write a Python program using a function to hour to minute.

Formula/Logic: minute = hour * 60

Complete Program:

def hr_min(hr):

    return hr * 60

 

hr = float(input("Enter hour: "))

ans = hr_min(hr)

print("Minute =", ans)

S45. Minute to Second

Question: Write a Python program using a function to minute to second.

Formula/Logic: second = minute * 60

Complete Program:

def min_sec(m):

    return m * 60

 

m = float(input("Enter minute: "))

ans = min_sec(m)

print("Second =", ans)

S46. Speed

Question: Write a Python program using a function to speed.

Formula/Logic: speed = distance / time

Complete Program:

def speed(d, t):

    return d / t

 

d = float(input("Enter distance: "))

t = float(input("Enter time: "))

ans = speed(d, t)

print("Speed =", ans)

S47. Distance

Question: Write a Python program using a function to distance.

Formula/Logic: distance = speed * time

Complete Program:

def dist(s, t):

    return s * t

 

s = float(input("Enter speed: "))

t = float(input("Enter time: "))

ans = dist(s, t)

print("Distance =", ans)

S48. Time

Question: Write a Python program using a function to time.

Formula/Logic: time = distance / speed

Complete Program:

def time_taken(d, s):

    return d / s

 

d = float(input("Enter distance: "))

s = float(input("Enter speed: "))

ans = time_taken(d, s)

print("Time =", ans)

S49. Gross Salary

Question: Write a Python program using a function to gross salary.

Formula/Logic: gross = basic + da + hra

Complete Program:

def gross_sal(basic, da, hra):

    return basic + da + hra

 

basic = float(input("Enter basic salary: "))

da = float(input("Enter DA: "))

hra = float(input("Enter HRA: "))

ans = gross_sal(basic, da, hra)

print("Gross Salary =", ans)

S50. Swap Two Numbers

Question: Write a Python program using a function to swap two numbers.

Formula/Logic: temp=a; a=b; b=temp

Complete Program:

def swap(a, b):

    temp = a

    a = b

    b = temp

    return a, b

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

ans = swap(a, b)

print("After swap: a =", ans[0])

print("After swap: b =", ans[1])


 

Selection Programs

S1. Check Positive, Negative, or Zero

Question: Write a Python program using a function to check positive, negative, or zero.

Formula/Logic: if n>0 positive, elif n<0 negative, else zero

Complete Program:

def sign(n):

    if n > 0:

        return "Positive"

    elif n < 0:

        return "Negative"

    else:

        return "Zero"

 

n = float(input("Enter number: "))

ans = sign(n)

print(ans)

S2. Check Odd or Even

Question: Write a Python program using a function to check odd or even.

Formula/Logic: even if n % 2 == 0

Complete Program:

def odd_even(n):

    if n % 2 == 0:

        return "Even"

    else:

        return "Odd"

 

n = int(input("Enter number: "))

ans = odd_even(n)

print(ans)

S3. Check Pass or Fail

Question: Write a Python program using a function to check pass or fail.

Formula/Logic: pass if marks >= 40

Complete Program:

def pass_fail(m):

    if m >= 40:

        return "Pass"

    else:

        return "Fail"

 

m = float(input("Enter marks: "))

ans = pass_fail(m)

print(ans)

S4. Check Voting Eligibility

Question: Write a Python program using a function to check voting eligibility.

Formula/Logic: eligible if age >= 18

Complete Program:

def vote(age):

    if age >= 18:

        return "Eligible"

    else:

        return "Not eligible"

 

age = int(input("Enter age: "))

ans = vote(age)

print(ans)

S5. Check Driving License Eligibility

Question: Write a Python program using a function to check driving license eligibility.

Formula/Logic: eligible if age >= 18

Complete Program:

def license(age):

    if age >= 18:

        return "Eligible"

    else:

        return "Not eligible"

 

age = int(input("Enter age: "))

ans = license(age)

print(ans)

S6. Largest of Two Numbers

Question: Write a Python program using a function to largest of two numbers.

Formula/Logic: larger = a if a>b else b

Complete Program:

def max2(a, b):

    if a > b:

        return a

    else:

        return b

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

ans = max2(a, b)

print(ans)

S7. Smallest of Two Numbers

Question: Write a Python program using a function to smallest of two numbers.

Formula/Logic: smaller = a if a<b else b

Complete Program:

def min2(a, b):

    if a < b:

        return a

    else:

        return b

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

ans = min2(a, b)

print(ans)

S8. Largest of Three Numbers

Question: Write a Python program using a function to largest of three numbers.

Formula/Logic: compare a,b,c using if-elif

Complete Program:

def max3(a, b, c):

    if a >= b and a >= c:

        return a

    elif b >= a and b >= c:

        return b

    else:

        return c

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

c = float(input("Enter third number: "))

ans = max3(a, b, c)

print(ans)

S9. Smallest of Three Numbers

Question: Write a Python program using a function to smallest of three numbers.

Formula/Logic: compare a,b,c using if-elif

Complete Program:

def min3(a, b, c):

    if a <= b and a <= c:

        return a

    elif b <= a and b <= c:

        return b

    else:

        return c

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

c = float(input("Enter third number: "))

ans = min3(a, b, c)

print(ans)

S10. Middle Number Among Three Numbers

Question: Write a Python program using a function to middle number among three numbers.

Formula/Logic: middle number is neither largest nor smallest

Complete Program:

def middle3(a, b, c):

    if (a >= b and a <= c) or (a <= b and a >= c):

        return a

    elif (b >= a and b <= c) or (b <= a and b >= c):

        return b

    else:

        return c

 

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

c = float(input("Enter third number: "))

ans = middle3(a, b, c)

print(ans)

S11. Check Divisible by 3

Question: Write a Python program using a function to check divisible by 3.

Formula/Logic: n % 3 == 0

Complete Program:

def div3(n):

    if n % 3 == 0:

        return "Divisible"

    else:

        return "Not divisible"

 

n = int(input("Enter number: "))

ans = div3(n)

print(ans)

S12. Check Divisible by 5

Question: Write a Python program using a function to check divisible by 5.

Formula/Logic: n % 5 == 0

Complete Program:

def div5(n):

    if n % 5 == 0:

        return "Divisible"

    else:

        return "Not divisible"

 

n = int(input("Enter number: "))

ans = div5(n)

print(ans)

S13. Check Divisible by Both 3 and 5

Question: Write a Python program using a function to check divisible by both 3 and 5.

Formula/Logic: n % 3 == 0 and n % 5 == 0

Complete Program:

def div35(n):

    if n % 3 == 0 and n % 5 == 0:

        return "Divisible by both"

    else:

        return "Not divisible by both"

 

n = int(input("Enter number: "))

ans = div35(n)

print(ans)

S14. Check Leap Year

Question: Write a Python program using a function to check leap year.

Formula/Logic: year divisible by 400 or divisible by 4 but not 100

Complete Program:

def leap(y):

    if (y % 400 == 0) or (y % 4 == 0 and y % 100 != 0):

        return "Leap year"

    else:

        return "Not leap year"

 

y = int(input("Enter year: "))

ans = leap(y)

print(ans)

S15. Check Vowel or Consonant

Question: Write a Python program using a function to check vowel or consonant.

Formula/Logic: vowel if character in a,e,i,o,u

Complete Program:

def vowel(ch):

    ch = ch.lower()

    if ch in "aeiou":

        return "Vowel"

    else:

        return "Consonant"

 

ch = str(input("Enter character: "))

ans = vowel(ch)

print(ans)

S16. Check Alphabet, Digit, or Special Character

Question: Write a Python program using a function to check alphabet, digit, or special character.

Formula/Logic: use isalpha and isdigit

Complete Program:

def char_type(ch):

    if ch.isalpha():

        return "Alphabet"

    elif ch.isdigit():

        return "Digit"

    else:

        return "Special character"

 

ch = str(input("Enter character: "))

ans = char_type(ch)

print(ans)

S17. Check Uppercase or Lowercase

Question: Write a Python program using a function to check uppercase or lowercase.

Formula/Logic: use isupper and islower

Complete Program:

def case_chk(ch):

    if ch.isupper():

        return "Uppercase"

    elif ch.islower():

        return "Lowercase"

    else:

        return "Other"

 

ch = str(input("Enter character: "))

ans = case_chk(ch)

print(ans)

S18. Check Profit or Loss

Question: Write a Python program using a function to check profit or loss.

Formula/Logic: profit if sp>cp, loss if cp>sp

Complete Program:

def profit_loss(cp, sp):

    if sp > cp:

        return "Profit"

    elif cp > sp:

        return "Loss"

    else:

        return "No profit no loss"

 

cp = float(input("Enter cost price: "))

sp = float(input("Enter selling price: "))

ans = profit_loss(cp, sp)

print(ans)

S19. Calculate Grade From Marks

Question: Write a Python program using a function to calculate grade from marks.

Formula/Logic: A>=90, B>=80, C>=60, D>=40 else F

Complete Program:

def grade(m):

    if m >= 90:

        return "A"

    elif m >= 80:

        return "B"

    elif m >= 60:

        return "C"

    elif m >= 40:

        return "D"

    else:

        return "F"

 

m = float(input("Enter marks: "))

ans = grade(m)

print(ans)

S20. Check Division From Percentage

Question: Write a Python program using a function to check division from percentage.

Formula/Logic: distinction>=80, first>=60, second>=45, pass>=40

Complete Program:

def division(p):

    if p >= 80:

        return "Distinction"

    elif p >= 60:

        return "First division"

    elif p >= 45:

        return "Second division"

    elif p >= 40:

        return "Pass"

    else:

        return "Fail"

 

p = float(input("Enter percentage: "))

ans = division(p)

print(ans)

S21. Check Armstrong Number

Question: Write a Python program using a function to check armstrong number.

Formula/Logic: for 3 digit number, sum of cubes of digits equals number

Complete Program:

def arm3(n):

    a = n // 100

    b = (n // 10) % 10

    c = n % 10

    s = a**3 + b**3 + c**3

    if s == n:

        return "Armstrong"

    else:

        return "Not Armstrong"

 

n = int(input("Enter number: "))

ans = arm3(n)

print(ans)

S22. Check Palindrome Number

Question: Write a Python program using a function to check palindrome number.

Formula/Logic: reverse equals original

Complete Program:

def pal_num(n):

    rev = int(str(n)[::-1])

    if rev == n:

        return "Palindrome"

    else:

        return "Not palindrome"

 

n = int(input("Enter number: "))

ans = pal_num(n)

print(ans)

S23. Check Palindrome String

Question: Write a Python program using a function to check palindrome string.

Formula/Logic: string equals reverse string

Complete Program:

def pal_str(s):

    if s == s[::-1]:

        return "Palindrome"

    else:

        return "Not palindrome"

 

s = str(input("Enter string: "))

ans = pal_str(s)

print(ans)

S24. Check Prime Number

Question: Write a Python program using a function to check prime number.

Formula/Logic: prime has exactly two factors

Complete Program:

def prime(n):

    if n <= 1:

        return "Not prime"

    for i in range(2, n):

        if n % i == 0:

            return "Not prime"

    return "Prime"

 

n = int(input("Enter number: "))

ans = prime(n)

print(ans)

S25. Check Perfect Number

Question: Write a Python program using a function to check perfect number.

Formula/Logic: sum of proper factors equals number

Complete Program:

def perfect(n):

    s = 0

    for i in range(1, n):

        if n % i == 0:

            s += i

    if s == n:

        return "Perfect"

    else:

        return "Not perfect"

 

n = int(input("Enter number: "))

ans = perfect(n)

print(ans)

S26. Check Scholarship Eligibility

Question: Write a Python program using a function to check scholarship eligibility.

Formula/Logic: marks>=80 and attendance>=75

Complete Program:

def scholar(m, att):

    if m >= 80 and att >= 75:

        return "Eligible"

    else:

        return "Not eligible"

 

m = float(input("Enter marks: "))

att = float(input("Enter attendance: "))

ans = scholar(m, att)

print(ans)

S27. Check Admission Eligibility

Question: Write a Python program using a function to check admission eligibility.

Formula/Logic: marks>=60 and entrance>=50

Complete Program:

def admit(m, e):

    if m >= 60 and e >= 50:

        return "Eligible"

    else:

        return "Not eligible"

 

m = float(input("Enter marks: "))

e = float(input("Enter entrance marks: "))

ans = admit(m, e)

print(ans)

S28. Check Job Eligibility

Question: Write a Python program using a function to check job eligibility.

Formula/Logic: age>=18 and qualification passed

Complete Program:

def job(age, q):

    if age >= 18 and q.lower() == "yes":

        return "Eligible"

    else:

        return "Not eligible"

 

age = int(input("Enter age: "))

q = str(input("Passed qualification? yes/no: "))

ans = job(age, q)

print(ans)

S29. Check Loan Eligibility

Question: Write a Python program using a function to check loan eligibility.

Formula/Logic: salary>=30000 and age>=21

Complete Program:

def loan(sal, age):

    if sal >= 30000 and age >= 21:

        return "Eligible"

    else:

        return "Not eligible"

 

sal = float(input("Enter salary: "))

age = int(input("Enter age: "))

ans = loan(sal, age)

print(ans)

S30. Check Tax Applicable or Not

Question: Write a Python program using a function to check tax applicable or not.

Formula/Logic: tax applies if income > 500000

Complete Program:

def tax_chk(inc):

    if inc > 500000:

        return "Tax applicable"

    else:

        return "Tax not applicable"

 

inc = float(input("Enter income: "))

ans = tax_chk(inc)

print(ans)

S31. Income Tax Slab

Question: Write a Python program using a function to income tax slab.

Formula/Logic: basic slab calculation

Complete Program:

def tax_slab(inc):

    if inc <= 500000:

        return 0

    elif inc <= 1000000:

        return inc * 0.10

    else:

        return inc * 0.20

 

inc = float(input("Enter income: "))

ans = tax_slab(inc)

print(ans)

S32. Electricity Bill Slab

Question: Write a Python program using a function to electricity bill slab.

Formula/Logic: first 100 at 5, next 100 at 7, rest at 10

Complete Program:

def elec_bill(u):

    if u <= 100:

        return u * 5

    elif u <= 200:

        return 100 * 5 + (u - 100) * 7

    else:

        return 100 * 5 + 100 * 7 + (u - 200) * 10

 

u = float(input("Enter units: "))

ans = elec_bill(u)

print(ans)

S33. Water Bill Slab

Question: Write a Python program using a function to water bill slab.

Formula/Logic: first 50 at 3, next 50 at 5, rest at 8

Complete Program:

def water_bill(u):

    if u <= 50:

        return u * 3

    elif u <= 100:

        return 50 * 3 + (u - 50) * 5

    else:

        return 50 * 3 + 50 * 5 + (u - 100) * 8

 

u = float(input("Enter units: "))

ans = water_bill(u)

print(ans)

S34. Discount Slab

Question: Write a Python program using a function to discount slab.

Formula/Logic: discount 5%, 10%, 15% based on amount

Complete Program:

def disc_slab(amt):

    if amt >= 10000:

        return amt * 0.15

    elif amt >= 5000:

        return amt * 0.10

    elif amt >= 1000:

        return amt * 0.05

    else:

        return 0

 

amt = float(input("Enter amount: "))

ans = disc_slab(amt)

print(ans)

S35. Bonus Category

Question: Write a Python program using a function to bonus category.

Formula/Logic: bonus rate by service years

Complete Program:

def bonus(sal, yrs):

    if yrs >= 10:

        return sal * 0.20

    elif yrs >= 5:

        return sal * 0.10

    else:

        return sal * 0.05

 

sal = float(input("Enter salary: "))

yrs = int(input("Enter service years: "))

ans = bonus(sal, yrs)

print(ans)

S36. Salary Tax Category

Question: Write a Python program using a function to salary tax category.

Formula/Logic: category by salary range

Complete Program:

def sal_tax(sal):

    if sal >= 100000:

        return "High tax"

    elif sal >= 50000:

        return "Medium tax"

    else:

        return "Low tax"

 

sal = float(input("Enter salary: "))

ans = sal_tax(sal)

print(ans)

S37. BMI Category

Question: Write a Python program using a function to bmi category.

Formula/Logic: BMI = weight / height^2

Complete Program:

def bmi_cat(w, h):

    bmi = w / (h*h)

    if bmi < 18.5:

        return "Underweight"

    elif bmi < 25:

        return "Normal"

    elif bmi < 30:

        return "Overweight"

    else:

        return "Obese"

 

w = float(input("Enter weight kg: "))

h = float(input("Enter height m: "))

ans = bmi_cat(w, h)

print(ans)

S38. Age Category

Question: Write a Python program using a function to age category.

Formula/Logic: child<13, teen<20, adult<60, senior otherwise

Complete Program:

def age_cat(age):

    if age < 13:

        return "Child"

    elif age < 20:

        return "Teenager"

    elif age < 60:

        return "Adult"

    else:

        return "Senior"

 

age = int(input("Enter age: "))

ans = age_cat(age)

print(ans)

S39. Check Triangle Validity

Question: Write a Python program using a function to check triangle validity.

Formula/Logic: sum of any two sides greater than third side

Complete Program:

def tri_valid(a, b, c):

    if a + b > c and b + c > a and a + c > b:

        return "Valid triangle"

    else:

        return "Invalid triangle"

 

a = float(input("Enter side 1: "))

b = float(input("Enter side 2: "))

c = float(input("Enter side 3: "))

ans = tri_valid(a, b, c)

print(ans)

S40. Type of Triangle by Sides

Question: Write a Python program using a function to type of triangle by sides.

Formula/Logic: equilateral, isosceles, scalene

Complete Program:

def tri_side(a, b, c):

    if a == b == c:

        return "Equilateral"

    elif a == b or b == c or a == c:

        return "Isosceles"

    else:

        return "Scalene"

 

a = float(input("Enter side 1: "))

b = float(input("Enter side 2: "))

c = float(input("Enter side 3: "))

ans = tri_side(a, b, c)

print(ans)

S41. Type of Triangle by Angles

Question: Write a Python program using a function to type of triangle by angles.

Formula/Logic: right if one angle 90, obtuse if >90 else acute

Complete Program:

def tri_angle(a, b, c):

    if a + b + c != 180:

        return "Invalid"

    elif a == 90 or b == 90 or c == 90:

        return "Right angled"

    elif a > 90 or b > 90 or c > 90:

        return "Obtuse angled"

    else:

        return "Acute angled"

 

a = float(input("Enter angle 1: "))

b = float(input("Enter angle 2: "))

c = float(input("Enter angle 3: "))

ans = tri_angle(a, b, c)

print(ans)

S42. Check Character is Vowel Using in

Question: Write a Python program using a function to check character is vowel using in.

Formula/Logic: ch in vowels

Complete Program:

def vow_in(ch):

    if ch.lower() in "aeiou":

        return "Vowel"

    else:

        return "Not vowel"

 

ch = str(input("Enter character: "))

ans = vow_in(ch)

print(ans)

S43. Check String Starts With Capital Letter

Question: Write a Python program using a function to check string starts with capital letter.

Formula/Logic: first character is uppercase

Complete Program:

def start_cap(s):

    if s[0].isupper():

        return "Starts with capital"

    else:

        return "Does not start with capital"

 

s = str(input("Enter string: "))

ans = start_cap(s)

print(ans)

S44. Check Password Length

Question: Write a Python program using a function to check password length.

Formula/Logic: valid if length >= 8

Complete Program:

def pass_len(p):

    if len(p) >= 8:

        return "Valid"

    else:

        return "Invalid"

 

p = str(input("Enter password: "))

ans = pass_len(p)

print(ans)

S45. Check Username and Password

Question: Write a Python program using a function to check username and password.

Formula/Logic: match fixed username and password

Complete Program:

def login(u, p):

    if u == "admin" and p == "1234":

        return "Login successful"

    else:

        return "Login failed"

 

u = str(input("Enter username: "))

p = str(input("Enter password: "))

ans = login(u, p)

print(ans)

S46. Check Two Digit Number

Question: Write a Python program using a function to check two digit number.

Formula/Logic: 10 to 99 or -99 to -10

Complete Program:

def two_digit(n):

    if (n >= 10 and n <= 99) or (n <= -10 and n >= -99):

        return "Two digit"

    else:

        return "Not two digit"

 

n = int(input("Enter number: "))

ans = two_digit(n)

print(ans)

S47. Check Three Digit Number

Question: Write a Python program using a function to check three digit number.

Formula/Logic: 100 to 999 or -999 to -100

Complete Program:

def three_digit(n):

    if (n >= 100 and n <= 999) or (n <= -100 and n >= -999):

        return "Three digit"

    else:

        return "Not three digit"

 

n = int(input("Enter number: "))

ans = three_digit(n)

print(ans)

S48. Check Multiple of 10

Question: Write a Python program using a function to check multiple of 10.

Formula/Logic: n % 10 == 0

Complete Program:

def mul10(n):

    if n % 10 == 0:

        return "Multiple of 10"

    else:

        return "Not multiple of 10"

 

n = int(input("Enter number: "))

ans = mul10(n)

print(ans)

S49. Compare Two Strings

Question: Write a Python program using a function to compare two strings.

Formula/Logic: compare equality of strings

Complete Program:

def str_cmp(a, b):

    if a == b:

        return "Equal"

    else:

        return "Not equal"

 

a = str(input("Enter first string: "))

b = str(input("Enter second string: "))

ans = str_cmp(a, b)

print(ans)

S50. Check Email Contains @

Question: Write a Python program using a function to check email contains @.

Formula/Logic: @ in email

Complete Program:

def email_chk(e):

    if "@" in e:

        return "Valid basic email"

    else:

        return "Invalid email"

 

e = str(input("Enter email: "))

ans = email_chk(e)

print(ans)


 

Looping Programs

L1. Print Numbers from 1 to 10

Question: Write a Python program using a function to print numbers from 1 to 10.

Formula/Logic: create list using range(1,11)

Complete Program:

def one_ten():

    lst = []

    for i in range(1, 11):

        lst.append(i)

    return lst

 

ans = one_ten()

print(ans)

L2. Print Numbers from 10 to 1

Question: Write a Python program using a function to print numbers from 10 to 1.

Formula/Logic: create list using range(10,0,-1)

Complete Program:

def ten_one():

    lst = []

    for i in range(10, 0, -1):

        lst.append(i)

    return lst

 

ans = ten_one()

print(ans)

L3. Print Numbers from 1 to n

Question: Write a Python program using a function to print numbers from 1 to n.

Formula/Logic: range(1,n+1)

Complete Program:

def one_n(n):

    lst = []

    for i in range(1, n+1):

        lst.append(i)

    return lst

 

n = int(input("Enter n: "))

ans = one_n(n)

print(ans)

L4. Print Numbers from n to 1

Question: Write a Python program using a function to print numbers from n to 1.

Formula/Logic: range(n,0,-1)

Complete Program:

def n_one(n):

    lst = []

    for i in range(n, 0, -1):

        lst.append(i)

    return lst

 

n = int(input("Enter n: "))

ans = n_one(n)

print(ans)

L5. Print Even Numbers from 1 to n

Question: Write a Python program using a function to print even numbers from 1 to n.

Formula/Logic: i % 2 == 0

Complete Program:

def even_n(n):

    lst = []

    for i in range(1, n+1):

        if i % 2 == 0:

            lst.append(i)

    return lst

 

n = int(input("Enter n: "))

ans = even_n(n)

print(ans)

L6. Print Odd Numbers from 1 to n

Question: Write a Python program using a function to print odd numbers from 1 to n.

Formula/Logic: i % 2 != 0

Complete Program:

def odd_n(n):

    lst = []

    for i in range(1, n+1):

        if i % 2 != 0:

            lst.append(i)

    return lst

 

n = int(input("Enter n: "))

ans = odd_n(n)

print(ans)

L7. Print Even Numbers from 2 to 30

Question: Write a Python program using a function to print even numbers from 2 to 30.

Formula/Logic: range(2,31,2)

Complete Program:

def even_30():

    lst = []

    for i in range(2, 31, 2):

        lst.append(i)

    return lst

 

ans = even_30()

print(ans)

L8. Print Odd Numbers from 1 to 30

Question: Write a Python program using a function to print odd numbers from 1 to 30.

Formula/Logic: range(1,31,2)

Complete Program:

def odd_30():

    lst = []

    for i in range(1, 31, 2):

        lst.append(i)

    return lst

 

ans = odd_30()

print(ans)

L9. Multiplication Table of a Number

Question: Write a Python program using a function to multiplication table of a number.

Formula/Logic: term = n * i

Complete Program:

def table(n):

    lst = []

    for i in range(1, 11):

        lst.append(f"{n} x {i} = {n*i}")

    return lst

 

n = int(input("Enter number: "))

ans = table(n)

print(ans)

L10. Multiplication Tables from 1 to 10

Question: Write a Python program using a function to multiplication tables from 1 to 10.

Formula/Logic: nested loop: i*j

Complete Program:

def tables():

    lst = []

    for i in range(1, 11):

        for j in range(1, 11):

            lst.append(f"{i} x {j} = {i*j}")

    return lst

 

ans = tables()

print(ans)

L11. Sum of First n Natural Numbers

Question: Write a Python program using a function to sum of first n natural numbers.

Formula/Logic: sum = sum + i

Complete Program:

def sum_n(n):

    s = 0

    for i in range(1, n+1):

        s += i

    return s

 

n = int(input("Enter n: "))

ans = sum_n(n)

print(ans)

L12. Sum of Even Numbers from 1 to n

Question: Write a Python program using a function to sum of even numbers from 1 to n.

Formula/Logic: add i if i%2==0

Complete Program:

def sum_even(n):

    s = 0

    for i in range(1, n+1):

        if i % 2 == 0:

            s += i

    return s

 

n = int(input("Enter n: "))

ans = sum_even(n)

print(ans)

L13. Sum of Odd Numbers from 1 to n

Question: Write a Python program using a function to sum of odd numbers from 1 to n.

Formula/Logic: add i if i%2!=0

Complete Program:

def sum_odd(n):

    s = 0

    for i in range(1, n+1):

        if i % 2 != 0:

            s += i

    return s

 

n = int(input("Enter n: "))

ans = sum_odd(n)

print(ans)

L14. Product of First n Natural Numbers

Question: Write a Python program using a function to product of first n natural numbers.

Formula/Logic: product = product * i

Complete Program:

def prod_n(n):

    p = 1

    for i in range(1, n+1):

        p *= i

    return p

 

n = int(input("Enter n: "))

ans = prod_n(n)

print(ans)

L15. Factorial of a Number

Question: Write a Python program using a function to factorial of a number.

Formula/Logic: factorial = 1*2*...*n

Complete Program:

def fact(n):

    fact = 1

    for i in range(1, n+1):

        fact *= i

    return fact

 

n = int(input("Enter number: "))

ans = fact(n)

print(ans)

L16. Sum of Squares from 1 to n

Question: Write a Python program using a function to sum of squares from 1 to n.

Formula/Logic: sum = sum + i**2

Complete Program:

def sum_sq(n):

    s = 0

    for i in range(1, n+1):

        s += i ** 2

    return s

 

n = int(input("Enter n: "))

ans = sum_sq(n)

print(ans)

L17. Sum of Cubes from 1 to n

Question: Write a Python program using a function to sum of cubes from 1 to n.

Formula/Logic: sum = sum + i**3

Complete Program:

def sum_cube(n):

    s = 0

    for i in range(1, n+1):

        s += i ** 3

    return s

 

n = int(input("Enter n: "))

ans = sum_cube(n)

print(ans)

L18. Count Positive, Negative, and Zero Values

Question: Write a Python program using a function to count positive, negative, and zero values.

Formula/Logic: count values by condition

Complete Program:

def count_sign(n):

    pos = neg = zero = 0

    for i in range(n):

        x = int(input("Enter number: "))

        if x > 0:

            pos += 1

        elif x < 0:

            neg += 1

        else:

            zero += 1

    return pos, neg, zero

 

n = int(input("How many numbers: "))

ans = count_sign(n)

print(ans)

L19. Count Even and Odd Numbers

Question: Write a Python program using a function to count even and odd numbers.

Formula/Logic: check each input using %2

Complete Program:

def count_eo(n):

    even = odd = 0

    for i in range(n):

        x = int(input("Enter number: "))

        if x % 2 == 0:

            even += 1

        else:

            odd += 1

    return even, odd

 

n = int(input("How many numbers: "))

ans = count_eo(n)

print(ans)

L20. Average of n Numbers

Question: Write a Python program using a function to average of n numbers.

Formula/Logic: average = total / n

Complete Program:

def avg_n(n):

    s = 0

    for i in range(n):

        x = float(input("Enter number: "))

        s += x

    return s / n

 

n = int(input("How many numbers: "))

ans = avg_n(n)

print(ans)

L21. Count Digits of a Number

Question: Write a Python program using a function to count digits of a number.

Formula/Logic: divide by 10 repeatedly

Complete Program:

def count_digits(n):

    n = abs(n)

    count = 0

    if n == 0:

        return 1

    while n > 0:

        count += 1

        n //= 10

    return count

 

n = int(input("Enter number: "))

ans = count_digits(n)

print(ans)

L22. Sum of Digits

Question: Write a Python program using a function to sum of digits.

Formula/Logic: sum = sum + digit

Complete Program:

def sum_digits(n):

    n = abs(n)

    s = 0

    while n > 0:

        d = n % 10

        s += d

        n //= 10

    return s

 

n = int(input("Enter number: "))

ans = sum_digits(n)

print(ans)

L23. Product of Digits

Question: Write a Python program using a function to product of digits.

Formula/Logic: product = product * digit

Complete Program:

def prod_digits(n):

    n = abs(n)

    p = 1

    while n > 0:

        d = n % 10

        p *= d

        n //= 10

    return p

 

n = int(input("Enter number: "))

ans = prod_digits(n)

print(ans)

L24. Reverse a Number

Question: Write a Python program using a function to reverse a number.

Formula/Logic: rev = rev*10 + digit

Complete Program:

def reverse(n):

    rev = 0

    while n > 0:

        d = n % 10

        rev = rev * 10 + d

        n //= 10

    return rev

 

n = int(input("Enter number: "))

ans = reverse(n)

print(ans)

L25. Check Palindrome Number

Question: Write a Python program using a function to check palindrome number.

Formula/Logic: original == reverse

Complete Program:

def pal_loop(n):

    orig = n

    rev = 0

    while n > 0:

        d = n % 10

        rev = rev * 10 + d

        n //= 10

    if orig == rev:

        return "Palindrome"

    else:

        return "Not palindrome"

 

n = int(input("Enter number: "))

ans = pal_loop(n)

print(ans)

L26. Check Armstrong Number

Question: Write a Python program using a function to check armstrong number.

Formula/Logic: sum of cubes of digits equals number

Complete Program:

def arm_loop(n):

    orig = n

    s = 0

    while n > 0:

        d = n % 10

        s += d ** 3

        n //= 10

    if s == orig:

        return "Armstrong"

    else:

        return "Not Armstrong"

 

n = int(input("Enter number: "))

ans = arm_loop(n)

print(ans)

L27. Sum of Even Digits

Question: Write a Python program using a function to sum of even digits.

Formula/Logic: add digit if digit%2==0

Complete Program:

def sum_ed(n):

    s = 0

    while n > 0:

        d = n % 10

        if d % 2 == 0:

            s += d

        n //= 10

    return s

 

n = int(input("Enter number: "))

ans = sum_ed(n)

print(ans)

L28. Sum of Odd Digits

Question: Write a Python program using a function to sum of odd digits.

Formula/Logic: add digit if digit%2!=0

Complete Program:

def sum_od(n):

    s = 0

    while n > 0:

        d = n % 10

        if d % 2 != 0:

            s += d

        n //= 10

    return s

 

n = int(input("Enter number: "))

ans = sum_od(n)

print(ans)

L29. Count Even Digits

Question: Write a Python program using a function to count even digits.

Formula/Logic: count digit if digit%2==0

Complete Program:

def count_ed(n):

    c = 0

    while n > 0:

        d = n % 10

        if d % 2 == 0:

            c += 1

        n //= 10

    return c

 

n = int(input("Enter number: "))

ans = count_ed(n)

print(ans)

L30. Count Odd Digits

Question: Write a Python program using a function to count odd digits.

Formula/Logic: count digit if digit%2!=0

Complete Program:

def count_od(n):

    c = 0

    while n > 0:

        d = n % 10

        if d % 2 != 0:

            c += 1

        n //= 10

    return c

 

n = int(input("Enter number: "))

ans = count_od(n)

print(ans)

L31. Largest Digit in a Number

Question: Write a Python program using a function to largest digit in a number.

Formula/Logic: compare each digit

Complete Program:

def large_digit(n):

    largest = 0

    while n > 0:

        d = n % 10

        if d > largest:

            largest = d

        n //= 10

    return largest

 

n = int(input("Enter number: "))

ans = large_digit(n)

print(ans)

L32. Smallest Digit in a Number

Question: Write a Python program using a function to smallest digit in a number.

Formula/Logic: compare each digit

Complete Program:

def small_digit(n):

    smallest = 9

    while n > 0:

        d = n % 10

        if d < smallest:

            smallest = d

        n //= 10

    return smallest

 

n = int(input("Enter number: "))

ans = small_digit(n)

print(ans)

L33. Fibonacci Series

Question: Write a Python program using a function to fibonacci series.

Formula/Logic: next = first + second

Complete Program:

def fibo(n):

    a, b = 0, 1

    lst = []

    for i in range(n):

        lst.append(a)

        a, b = b, a + b

    return lst

 

n = int(input("Enter terms: "))

ans = fibo(n)

print(ans)

L34. Sum of Fibonacci Series

Question: Write a Python program using a function to sum of fibonacci series.

Formula/Logic: sum generated Fibonacci terms

Complete Program:

def sum_fibo(n):

    a, b = 0, 1

    s = 0

    for i in range(n):

        s += a

        a, b = b, a + b

    return s

 

n = int(input("Enter terms: "))

ans = sum_fibo(n)

print(ans)

L35. Factors of a Number

Question: Write a Python program using a function to factors of a number.

Formula/Logic: i is factor if n%i==0

Complete Program:

def factors(n):

    lst = []

    for i in range(1, n+1):

        if n % i == 0:

            lst.append(i)

    return lst

 

n = int(input("Enter number: "))

ans = factors(n)

print(ans)

L36. Check Prime Number

Question: Write a Python program using a function to check prime number.

Formula/Logic: no factor from 2 to n-1

Complete Program:

def prime_loop(n):

    if n <= 1:

        return "Not prime"

    for i in range(2, n):

        if n % i == 0:

            return "Not prime"

    return "Prime"

 

n = int(input("Enter number: "))

ans = prime_loop(n)

print(ans)

L37. Print Prime Numbers from 1 to n

Question: Write a Python program using a function to print prime numbers from 1 to n.

Formula/Logic: check every number for prime

Complete Program:

def primes_n(n):

    primes = []

    for num in range(2, n+1):

        is_prime = True

        for i in range(2, num):

            if num % i == 0:

                is_prime = False

                break

        if is_prime:

            primes.append(num)

    return primes

 

n = int(input("Enter n: "))

ans = primes_n(n)

print(ans)

L38. Print First n Prime Numbers

Question: Write a Python program using a function to print first n prime numbers.

Formula/Logic: keep counting primes until n found

Complete Program:

def first_primes(n):

    primes = []

    num = 2

    while len(primes) < n:

        is_prime = True

        for i in range(2, num):

            if num % i == 0:

                is_prime = False

                break

        if is_prime:

            primes.append(num)

        num += 1

    return primes

 

n = int(input("Enter n: "))

ans = first_primes(n)

print(ans)

L39. HCF of Two Numbers

Question: Write a Python program using a function to hcf of two numbers.

Formula/Logic: largest common factor

Complete Program:

def hcf(a, b):

    h = 1

    limit = min(a, b)

    for i in range(1, limit+1):

        if a % i == 0 and b % i == 0:

            h = i

    return h

 

a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

ans = hcf(a, b)

print(ans)

L40. LCM of Two Numbers

Question: Write a Python program using a function to lcm of two numbers.

Formula/Logic: lcm = a*b/hcf

Complete Program:

def lcm(a, b):

    h = 1

    for i in range(1, min(a,b)+1):

        if a % i == 0 and b % i == 0:

            h = i

    return (a * b) // h

 

a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

ans = lcm(a, b)

print(ans)

L41. Check Perfect Number

Question: Write a Python program using a function to check perfect number.

Formula/Logic: sum proper factors equals number

Complete Program:

def perfect_loop(n):

    s = 0

    for i in range(1, n):

        if n % i == 0:

            s += i

    if s == n:

        return "Perfect"

    else:

        return "Not perfect"

 

n = int(input("Enter number: "))

ans = perfect_loop(n)

print(ans)

L42. Print Perfect Numbers from 1 to n

Question: Write a Python program using a function to print perfect numbers from 1 to n.

Formula/Logic: check every number for perfect

Complete Program:

def perfects(n):

    lst = []

    for num in range(1, n+1):

        s = 0

        for i in range(1, num):

            if num % i == 0:

                s += i

        if s == num:

            lst.append(num)

    return lst

 

n = int(input("Enter n: "))

ans = perfects(n)

print(ans)

L43. Series 1, 3, 5, 7...

Question: Write a Python program using a function to series 1, 3, 5, 7....

Formula/Logic: term = 2*i - 1

Complete Program:

def ser_odd(n):

    lst = []

    for i in range(1, n+1):

        lst.append(2*i - 1)

    return lst

 

n = int(input("Enter terms: "))

ans = ser_odd(n)

print(ans)

L44. Series 20, 18, 16, 14...

Question: Write a Python program using a function to series 20, 18, 16, 14....

Formula/Logic: start 20, subtract 2

Complete Program:

def ser_20(n):

    lst = []

    term = 20

    for i in range(n):

        lst.append(term)

        term -= 2

    return lst

 

n = int(input("Enter terms: "))

ans = ser_20(n)

print(ans)

L45. Series 1, 4, 9, 16...

Question: Write a Python program using a function to series 1, 4, 9, 16....

Formula/Logic: term = i**2

Complete Program:

def ser_sq(n):

    lst = []

    for i in range(1, n+1):

        lst.append(i ** 2)

    return lst

 

n = int(input("Enter terms: "))

ans = ser_sq(n)

print(ans)

L46. Series 100, 99, 97, 94...

Question: Write a Python program using a function to series 100, 99, 97, 94....

Formula/Logic: subtract 1,2,3,...

Complete Program:

def ser_100(n):

    lst = []

    term = 100

    for i in range(1, n+1):

        lst.append(term)

        term -= i

    return lst

 

n = int(input("Enter terms: "))

ans = ser_100(n)

print(ans)

L47. Star Pattern Increasing

Question: Write a Python program using a function to star pattern increasing.

Formula/Logic: nested loop rows 1 to n

Complete Program:

def pat_inc(n):

    lines = []

    for i in range(1, n+1):

        lines.append("*" * i)

    return "\n".join(lines)

 

n = int(input("Enter rows: "))

ans = pat_inc(n)

print(ans)

L48. Star Pattern Decreasing

Question: Write a Python program using a function to star pattern decreasing.

Formula/Logic: nested loop rows n to 1

Complete Program:

def pat_dec(n):

    lines = []

    for i in range(n, 0, -1):

        lines.append("*" * i)

    return "\n".join(lines)

 

n = int(input("Enter rows: "))

ans = pat_dec(n)

print(ans)

L49. Number Pattern Increasing

Question: Write a Python program using a function to number pattern increasing.

Formula/Logic: print 1, 12, 123...

Complete Program:

def num_pat(n):

    lines = []

    for i in range(1, n+1):

        row = ""

        for j in range(1, i+1):

            row += str(j)

        lines.append(row)

    return "\n".join(lines)

 

n = int(input("Enter rows: "))

ans = num_pat(n)

print(ans)

L50. Floyd Triangle

Question: Write a Python program using a function to floyd triangle.

Formula/Logic: continuous numbers in triangular form

Complete Program:

def floyd(n):

    lines = []

    num = 1

    for i in range(1, n+1):

        row = []

        for j in range(i):

            row.append(str(num))

            num += 1

        lines.append(" ".join(row))

    return "\n".join(lines)

 

n = int(input("Enter rows: "))

ans = floyd(n)

print(ans)

Thursday, May 28, 2026

📘 4.2 User-defined Functions [Python Programming] - SEE COMPUTER SCIENCE 2083 - CDC NEW CURRICULUM

 📘 4.2 User-defined Functions  [Python Programming] - SEE COMPUTER SCIENCE 2083 - CDC NEW CURRICULUM


DOWNLOAD PDF NOTES [4.2 USER DEFINED FUNCTIONS]


📘 4.2 User-defined Functions [Python Programming]

A Python function is a block of organized and reusable code designed to perform a specific task.

Functions provide better modularity for applications and reduce code repetition through reusability.

 

Modularity: Breaking down a large, complex application into smaller, manageable blocks.

 

Types of Python Functions

 

1. Built-in Functions (Library Functions)

Functions that are already available in Python are called built-in functions. They are loaded into the computer's memory as soon as the Python interpreter starts.

Example:

  • print ( ) - Displays output
  • input ( ) - Takes input from the user
  • len ( ) - Returns the length of a string or list
  • int ( ) - Converts a value to an integer
  • sum ( ) - Calculates the sum of elements

 

2. User-defined Functions

Functions created by the programmer to perform a specific task are called user-defined functions. User-defined functions are written using the def keyword. Once defined, they can be called multiple times in a program.

 

Difference Between Built-in Functions and User-defined Functions

Feature

Built-in Functions

User-defined Functions

Creator

Created by Python developers.

Created by the user / programmer.

Availability

Available by default in Python without importing additional modules.

Must be written before using.

Memory

Loaded immediately when interpreter starts.

Loaded only when defined in your code.

Examples

print(), len()

calculate_tax ( )

Real-Life Example

Readymade clothes from a store.

Tailor-stitched custom clothes.

 

Creating User-defined Functions

A function definition begins with the keyword def (short for define). The syntax for creating a user-defined function is as follows:

 

Syntax

def <function_name> (parameter1, parameter2, ...):

    set of instructions to be executed

    [return <value>]

 

Important Points

i. The items enclosed in “[ ]” are optional parameters. Therefore, a function may or may not have parameters. Similarly, a function may or may not return a value.

ii. The function header always ends with a colon (:).

iii. The function name should be unique. The rules for naming identifiers also apply to function names.

iv. The statements outside the function indentation are not considered part of the function.

 

Example

# Program to illustrate the use of user-defined functions

def add_numbers(x, y):

    total = x + y

    return total

num1 = 5

num2 = 6

 

print("The sum is", add_numbers(num1, num2))

 

Output

The sum is 11

 

Scope of Function

The scope of a function refers to the area of a program where a function or variable can be accessed.

Generally, scope can be classified into the following types:

 

i. Local Scope

Variables declared inside a function are accessible only within that function.

 

ii. Global Scope

Variables declared outside any function can be accessed from anywhere in the program.

 

Functions Returning a Value

The return statement in Python is used to return a value back to the calling function. A function can take input values as parameters, process them, and return the output using the return statement.

Usually, function definitions have the following basic structure:

 

Syntax

def function_name(arguments):

    return <value>

 

Example

# Function to calculate the area of a rectangle

def area(length, width):

    return length * width

 

length = 5

width = 8

result = area(length, width)

print("Area of Rectangle:")

print(result)

 

Output

Area of Rectangle:
40

 

Parameters and Arguments in Functions

Parameters are the variables written inside the parentheses in a function definition. These values are required for the function to work.

Example

# Function to calculate the area of circle using function
def area_of_circle(radius):

    area = radius ** 2 * 22 / 7

    return area

radius = float(input("Please enter the radius of the given circle: "))
print("The area of the given circle is:", area_of_circle(radius))

 

An argument is an actual value passed to a function. In other words, arguments are the values provided in the function call statement.

 

The list of arguments should match the order of parameters in the function definition.

 

Example of argument in function call

area(5)

5 is an argument. An argument can be constant, variable, or expression.

 

Parameters are actually variables/placeholders, not values.
Arguments are the actual values passed during function call.

 

Scope of Variables

The scope of a variable determines where the variable can be accessed in a program.

The two common types of variable scope are:

1. Local Scope

2. Global Scope

 

1. Local Scope

Variables declared inside a function are called local variables. These variables can only be accessed within that function. A local variable exists only while the function is executing.

 

Example

def multiply_by_two():
    number = 5   # local variable
    result = number * 2
    print("Inside function:", result)

multiply_by_two()
# print(result)  # This will give an error because 'result' is local to the function

 

Output

Inside function: 10

 

2. Global Scope

Variables declared outside all functions are called global variables. These variables can be accessed from anywhere in the program.

 

Example

number = 10   # global variable

def add_five():
    result = number + 5
    print("Inside function:", result)

add_five()
print("Outside function:", number)

 

Output

Inside function: 15
Outside function: 10

Passing Parameters

Python allows different ways to pass data (arguments) into a function.

 

Python supports three types of arguments:

 

1. Positional (Required) Arguments

2. Default Arguments

3. Keyword (Named)

 

1. Positional/Required Arguments

Arguments passed in the same order as the parameters are defined are called positional or required arguments.

 

Example

If a function definition header is like

def check(a, b, c):

then function calls for this can be:

check(x, y, z)      # 3 values (all variables) passed

check(2, x, y)      # 3 values (literal variables) passed

check(2, 5, 7)      # 3 values (all literals) passed

 

2. Default Arguments

Default arguments are the parameters that take default values if no value is provided during the function call.

 

Example

def interest(principal, time, rate=0.10):

here 0.10 is the default value for parameter rate

The default value is specified in a manner syntactically similar to a variable initialization.

 

Example

def Interest(prin, time, rate=0.10):      # legal
def Interest(prin, time=2, rate):         # illegal
def Interest(prin=2000, time=2, rate):    # illegal
def Interest(prin, time=2, rate=0.10):    # legal
def Interest(prin=200, time=2, rate=0.10): # legal

Important point

Default parameters must always come after required parameters.

 

Example 2

def power (base, exp = 2) :

    return base ** exp

 

print (power(4))

print (power (2, 3))

 

Here, in the first function call, only one argument, i.e. the base. So, it uses default value of exp, i.e. 2. In the second function call, both arguments are defined so base = 2 and exp = 3.

 

Output

16

8

 

3. Keyword (Named) Arguments

Arguments passed using parameter names in a function call, so the order does not matter, are called keyword (or named) arguments.

 

Examples

interest(prin=2000, time=2, rate=0.10)
interest(time=2, prin=2600, rate=0.09)
interest(time=2, rate=0.12, prin=2000)

 

All the above function calls are valid now, even if the order of arguments does not match the order of parameters as defined in the function header.

 

Returning Values from Functions

A function in Python can be defined with or without returning a value to the calling function. There are two types of functions in Python:

1. Functions Returning Values (Non-void Functions)
2. Functions Not Returning Values (Void Functions)

 

1. Functions Returning Values (Non-void Functions)

Functions that return a computed value to the calling function are called non-void functions.
The return statement is used to return the value.

The returned value may be a literal (5), a variable (x), or an expression (x + y).

Syntax

return <value>

 

Example

def add(x, y):

    return x + y

result = add(5, 3)

Here, the returned value from add( ) replaces the function call.

 

2. Functions Not Returning Values (Void Functions)

Functions that perform a task but do not return any value to the calling function are called void functions.

A void function may contain:

return

That is, the return statement without any value or expression.

 

Examples of Void Functions

def greet():
    print("Hello")

def greet1(name):
    print("Hello", name)

def quote():

    print("Python is good")
    return

def printsum(a, b, c):
    print("Sum is", a + b + c)
    return

 

Important Point

Void functions do not return any value. However, Python automatically returns a special value called None.

 

Example

def greet():
    print("Hello")

a = greet()
print(a)

 

Output

Hello
None

 

Returning Multiple Values

Python allows a function to return multiple values using a single return statement.

 

Syntax

return <value1>, <value2>, <value3>

 

Example

def squared(x, y, z):
    return x * x, y * y, z * z

t = squared(2, 5, 7)
print(t)

 

Output

(4, 25, 49)

 

Example

def squared(x, y, z):
    return x * x, y * y, z * z

v1, v2, v3 = squared(2, 3, 4)
print("The returned values are as under:")
print(v1, v2, v3)

 

Output

The returned values are as under:
4 9 16