[go: up one dir, main page]

0% found this document useful (0 votes)
3 views11 pages

FILMON_HAILE.CP-Assignment IV

The document is an assignment on computer programming prepared by Filmon Haile for the Addis Ababa Institute of Technology. It includes various Python programming tasks such as differentiating between data types, writing conditional statements, and implementing functions for mathematical operations. Additionally, it covers recursion, string manipulation, and logical conditions in Python.

Uploaded by

danielgetahun66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

FILMON_HAILE.CP-Assignment IV

The document is an assignment on computer programming prepared by Filmon Haile for the Addis Ababa Institute of Technology. It includes various Python programming tasks such as differentiating between data types, writing conditional statements, and implementing functions for mathematical operations. Additionally, it covers recursion, string manipulation, and logical conditions in Python.

Uploaded by

danielgetahun66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

ADDIS ABABA INSTITUTE OF TECHNOLOGY CAMPUS

DEPARTMENT OF PRE-ENGINEERING
Computer programming
Assignment IV

❖ PREPARED BY:-
FILMON HAILE UGR/8564/17

SUBMITTED TO:-

INS. KINDE MEKURIA

SUBMISSION DATE:- MAY,26,2025

1
1.In Python, what is the difference between “False” and False?

1. "False" (String)

• Type: String

• Value: The literal 5-character sequence F, a, l, s, e

2. False (Boolean)

• Type: Boolean (True or False)

• Value: One of Python's two built-in Boolean values (True or False)

2. Write a Python if-else statement that checks whether a given value is an even or odd

number.

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

if x % 2 == 0: print(f"{x} is an even number.")

else: print(f"{x} is an odd number.")

3. Write a Python program to:

2
a. Find the sum of the digits of a number:

b. Reverse the given number:

c. Check whether the number is a palindrome or not

number = str(input("Enter a number: "))

#1. Calculate sum of digits

digit_sum = 0

for digit in number:

digit_sum += int(digit)

print("Sum of digits:", digit_sum)

#2. Reverse the number

reversed_number = number[::-1] # This slices the string backward

print("Reversed number:", reversed_number)

#3. Check if it's a palindrome

if number == reversed_number: print("It is a palindrome!")

else: print("It is not a palindrome.")

3
4. Write a Python program that checks if a given number is prime.

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

count = 0

if x > 1:

for i in range(2, x):

if x % i == 0:

count += 1

print(f"{x} is prime" if count == 0 else f"{x} is not prime")

else: print(f"{x} is not prime")

5. What is the value of x after the following statement execution?

x=1

x *= x + 1

Answer: x=x*(x+1) =2

6. Who do the following code display?

temperature = 50

if temperature >= 50: print("too hot")

if temperature < 50: print("too cold")

4
elif temperature <= 40: print("too cold")

else: print("just right")

the code shows both "too hot" and "just right" because:

1. The first if (temperature >= 50) prints "too hot" (true for 50)

2. The second if-elif-else block is evaluated separately:

o if temperature < 50 is false (not excuted)

o elif temperature <= 40 is false (skipped)

o So the else executes and prints "just right"

The else belongs only to the second if statement, not the first one, causing both messages to
appear.

7. After executing the following code, what would be the value of y?

x=0

y = 100 if x > 0 else 200

answer: 200

8. How many times will the string “Hello World” be printed by the following while

statement?

count = 0
while count < 10:
print("Hello World ")

5
The while loop will print "Hello World" infinitely because

1. count starts at 0

2. The condition count < 10 is always true (since count is never incremented)

3. The loop never stops

9. What will the following Python code fragment will display?

num = 7

while num > 0:

num -= 2

print(num)

Answer

-1

10. What sequence will the function range(20,11,-3) will return?

Answer

20, 17, 14

11. For the following Python code fragment:

a. What will be printed on the screen?

b. How many times will the while loop iterate?

counter = 10

while True:

if counter < 5: continue

counter = counter – 1

print(counter)

Answer for a.

6
7

Answer for b.

The loop will iterate infinitely (forever), but it will only print the above values before getting stuck .

12. Find the sum and average of a list of numbers using function composition. (Function

Composition is a way of combining functions such that the result of one function is

passed as the argument of the next function).

Answer

# Function to calculate sum of numbers

def calculate_sum(numbers):

total = 0

for num in numbers:

total += num

return total

# Function to calculate average

def calculate_average(numbers):

return calculate_sum(numbers) / len(numbers)

# Main program

numbers = [10, 20, 30, 40, 50] # Our list of numbers

# Using the functions together (function composition)

sum_of_numbers = calculate_sum(numbers)

average_of_numbers = calculate_average(numbers)

# Displaying results

print("Numbers:", numbers)

print("Sum:", sum_of_numbers)

print("Average:", average_of_numbers)

13. If called, the display function below is called with arguments as in display(‘Tests’,4),

7
What will be the output?

def display(str, n):

while n > 0:

for i in range(n): print(str[i],end="")

print("")

n -= 1

Answer

Test

Tes
Te

T
14. Write a Python code that finds the sum of the first n natural numbers using a recursive
function.

Answer

def sum_natural_numbers(n):

if n == 0:

return 0

else:

return n + sum_natural_numbers(n - 1)

15. Write a python program that solves x power of y recursively.


Answer

def power(x, y):

if y == 0:

return 1

elif y == 1:

return x

else:

return x * power(x, y - 1)

8
16. Write a Python program that finds the GCD of two numbers.

Answer

Using Recursion

def GCD(a, b):


if b == 0:

return a

else:

return GCD(b, a % b)

Using While Loop

def GCD(a, b):

while b != 0:

a, b = b, a % b
return a

17. Using while loop, implement countdown by n.

def countdown_by_n(count_from, count_by): """Prints a count down from count_from by


count_by. Stops printing before the result goes negative.”””

Answer

def countdown_by_n(count_from, count_by):

x = count_from

while x >= 0:

print(x)
x -= count_by

18. For the given function definition, if f=fib(3) is called, write the sequence of the lines
executed from the beginning where the fib function is call to the end of the function call.
Hint the first to be executed is line 10 and the last is also line 10, note that there is
recursive calls.

1 def fib(n):

2 sum = 0

9
3 if n == 0 or n == 1:

4 return 1

6 sum += fib(n-1)
7 sum += fib(n-2)

8 return sum

10 f = fib(3)

Answer

10 -> 1 -> 2 -> 3 -> 6 -> 1 -> 2 -> 3 -> 6 -> 1 -> 2 -> 3 -> 4 -> 6 -> 7 -> 1 -> 2 -> 3 -> 4 ->
7 -> 8 -> 6 -> 7 -> 1 -> 2 -> 3 -> 4 -> 7 -> 8 -> 10

19. The following near_and_far() function accepts three ints a, b, and c as arguments
and Return True if one of b or c is "close" (differing from a by at most 1), while the other
is "far", differing from both other values by 2 or more. Fill all of the 5 spaces with the
correct comparison or logical operators. (Hint: near_far(2,3,4) returns true while
near_far(2,3,4) returns false)
def near_and_far(a, b, c):

cond1 = abs(a-b) ___ 1 and abs(b-c) ____ 2 and abs(a-c) ____ 2

cond2 = abs(a-c) ____1 and abs(a-b) ____ 2 and abs(c-b) ____ 2

return cond1 ____ cond2


Answer in completed form

def near_and_far(a, b, c):

cond1 = abs(a-b) <= 1 and abs(b-c) >= 2 and abs(a-c) >= 2

cond2 = abs(a-c) <= 1 and abs(a-b) >= 2 and abs(c-b) >= 2


return cond1 or cond2

20. For the sequence 2, 3, 6, 18, 108, 1944..., write a recursive function
next_produc(n) that calculates the nth number of the sequence.

Answer

10
def next_product(n):
if n == 0:
return 2
elif n == 1:
return 3
else:
return next_product(n-1) * next_product(n-2)
21. Write a recursive function reverse() that returns the value of its string argument,
except reversed. For example, reverse("python") should return "nohtyp".
Answer

def reverse(s):

if len(s) <= 1:

return s

return reverse(s[1:]) + s[0]

11

You might also like