Programming Activity (Part 2)
Programming Activity (Part 2)
1. Errors in Python:
Given the following Python code, identify and fix the errors (syntax, logical, or runtime).
def factorial(n):
result = 1
for i in range(n):
result = result * i
return result
num = "5"
print(factorial(num))
● Question:
○ What type of errors do you see in the code?
○ How can you fix the errors? Write the corrected code
2. Flow of Control:
● Write a Python program that checks whether a number entered by the user is positive,
negative, or zero using if, elif, and else.
Example Input:
number = 5
Example Output:
The number is positive.
3. Conditional Statements:
○ Use if-else or if-elif-else to calculate and print the absolute value of the
number.
Example Input:
number = -10
Example Output:
Absolute value is 10
●
Write a Python program that takes three numbers as input and sorts them in ascending order
using if-else statements.
Example Input:
num1 = 5
num2 = 3
num3 = 8
Example Output:
Sorted numbers: 3, 5, 8
Write a Python program to check whether a number is divisible by 5 and 3 or not using
if-else statements.
Example Input:
number = 15
Example Output:
The number is divisible by 5 and 3.
4. Iterative Statements:
Activity 6: For Loop Pattern
Write a Python program using a for loop to print the following pattern:
*
**
***
****
*****
Write a Python program using a for loop to calculate the sum of the first n natural numbers.
The value of n should be taken as input from the user.
Example Input:
n=5
Example Output:
The sum of the first 5 natural numbers is 15.
Write a Python program to find the factorial of a positive integer using a while loop.
Example Input:
num = 4
Example Output:
The factorial of 4 is 24.
Write a Python program using a while loop to generate the first n Fibonacci numbers.
Example Input:
n=5
Example Output:
Fibonacci series: 0 1 1 2 3
Example Output:
1
2
4
5
7
5. Strings in Python:
Write a Python program that takes two strings as input and concatenates them.
Example Input:
str1 = "Hello"
str2 = "World"
Example Output:
HelloWorld
Write a Python program to check if a substring exists within a given string using the in operator.
Example Input:
str1 = "Hello, World!"
substring = "World"
Example Output:
"World" is found in "Hello, World!"
Write a Python program to slice a string and print the first 5 characters, the last 5 characters,
and every alternate character.
Example Input:
text = "PythonProgramming"
Example Output:
First 5 characters: Pytho
Last 5 characters: amming
Alternate characters: PtoPormig
Example Input:
text = "hello world 123"
Example Output:
Capitalized: Hello world 123
Lowercase: hello world 123
Index of 'o': 4
Is alphanumeric: False