Chapter 6
Chapter 6
Programming Exercise
1 Write a function for swapping two variables.
def swap_variables(a, b):
temp = a
a=b
b = temp
return a, b
2 Write a Python program to print a roll number and name of a student using
functions.
def print_student_details(roll_no, name):
print("Roll No:", roll_no)
print("Name:", name)
print_student_details(roll_no, name)
3 Write an iterative version function of the factorial of a number.
def factorial(n):
fact = 1
for i in range(1, n+1):
fact *= i
return fact
4 Write a Python function to compute average for variable length arguments of
numbers.
def calculate_average(*args):
if len(args) == 0:
return None
total = sum(args)
avg = total / len(args)
return avg
5 Implement a Python function for bubble sort a set of numbers {10, 2, 7, 24, 32}.
def bubble_sort(numbers):
n = len(numbers)
for i in range(n):
for j in range(0, n-i-1):
if numbers[j] > numbers[j+1]:
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
return numbers
return True
9 Write a function that finds the Nth element of a geometric sequence.
def tn_gs(a, r, n):
nth_term = a * r ** (n-1)
return nth_term
10 Write a program to check whether the number is a perfect number or not.
def is_perfect_number(num):
divisor_sum = 0
for i in range(1, num):
if num % i == 0:
divisor_sum += i
if divisor_sum == num:
return True
else:
return False