Lab 6 Functions Solution
Lab 6 Functions Solution
Code Once
Introduction to Computers
Laboratory Manual
Experiment #6 Solution
Functions
Experiment #6: Functions
Homework
1. Write factorial(num) function that computes the factorial of an integer.
Solution:
def factorial(num):
fact = 1
for i in range(1, num + 1):
fact *= i
return fact
2. Write a function print_prime_numbers(num) that prints all the prime numbers up to
num. (hint: use isPrime function from the lab work.)
Solution:
def isPrime(num):
if num < 2:
return False
for i in range(2, num):
if (num % i) == 0:
return False
return True
def print_prime_numbers(num):
for i in range(1, num + 1):
if isPrime(i):
print(i)
3. Using the following function header, write a function that computes the distance
between two points.
def distance(x1, y1, x2, y2):
Solution:
def distance(x1, y1, x2, y2):
return ((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2)) ** 0.5
2
Experiment #6: Functions
5. Write a function that computes the sum of the digits in an integer. Use the following
function header:
def sum_digits(n):
For example, sum_digits(234) returns 9 (2 + 3 + 4).
Solution:
def sumDigits(n):
temp = abs(n)
sum = 0
while temp != 0:
remainder = temp % 10
sum += remainder
temp = temp // 10
return sum
Good Luck