More Simple Python Programs Using Functions
These examples help beginners understand function logic, parameters, arguments, loops, and
conditions in Python.
Example 7: Function to find the largest number
def largest(a, b):
if a > b:
print(a, "is larger")
else:
print(b, "is larger")
largest(10, 20)
Output: 20 is larger
Logic: Compares two numbers using if-else.
Example 8: Function to check even or odd
def even_odd(num):
if num % 2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")
even_odd(5)
even_odd(10)
Output: 5 is Odd 10 is Even
Logic: Uses modulus operator % to check divisibility by 2.
Example 9: Function to find area of rectangle
def area_rectangle(length, width):
area = length * width
print("Area =", area)
area_rectangle(5, 3)
Output: Area = 15
Logic: Area formula = length × width.
Example 10: Function to calculate total and average marks
def marks(total_subjects):
total = 0
for i in range(total_subjects):
mark = int(input("Enter mark: "))
total += mark
average = total / total_subjects
print("Total =", total)
print("Average =", average)
marks(3)
Sample Output: Enter mark: 80 Enter mark: 70 Enter mark: 90 Total = 240 Average = 80.0
Logic: Takes input marks using loop, finds total and average.
Example 11: Function returning multiple values
def calc(a, b):
add = a + b
sub = a - b
return add, sub
x, y = calc(10, 5)
print("Sum =", x)
print("Difference =", y)
Output: Sum = 15 Difference = 5
Logic: Returns two values using return statement.
Example 12: Function to print message multiple times
def repeat_msg(msg, times):
for i in range(times):
print(msg)
repeat_msg("Practice makes perfect!", 3)
Output: Practice makes perfect! Practice makes perfect! Practice makes perfect!
Logic: Prints message in a loop repeatedly.
Example 13: Function to find factorial of a number
def factorial(n):
fact = 1
for i in range(1, n+1):
fact *= i
print("Factorial =", fact)
factorial(5)
Output: Factorial = 120
Logic: Multiplies numbers from 1 to n using for loop.
Example 14: Function to check positive or negative
def check_number(num):
if num > 0:
print("Positive number")
elif num < 0:
print("Negative number")
else:
print("Zero")
check_number(-3)
check_number(0)
check_number(5)
Output: Negative number Zero Positive number
Logic: Uses if-elif-else to compare number with 0.
Example 15: Function to count vowels in a word
def count_vowels(word):
count = 0
for ch in [Link]():
if ch in 'aeiou':
count += 1
print("Number of vowels:", count)
count_vowels("Education")
Output: Number of vowels: 5
Logic: Loops through letters and counts vowels.
Example 16: Function to reverse a string
def reverse_string(text):
print("Reversed string:", text[::-1])
reverse_string("Python")
Output: Reversed string: nohtyP
Logic: Uses string slicing [::-1] to reverse text.
Summary: These 10 examples cover loops, conditions, parameters, arguments, and string
operations using simple functions.