SSC Resources · Ict

Python Basics Practise Sheet

Lecture slides and notes for Python Basics Practise Sheet from the Ict module in SSC Resources by Md Ahbab. 5 pages.

Document Info: 5 pages · PDF

Python Basics Practise Sheet, first page preview

Content Preview

Python Practice Sheet Please follow the codes and think how they are executed line by line in order to understand them. Part I: Theory Questions (2 Marks Each) 1. break vs. continue • break: Exits the entire loop immediately. • continue: Skips the current iteration and moves to the next one. Example: for i in range(5): if i == 3: break # Loop ends here when i == 3 print(i) for i in range(5): if i == 3: continue # Skips printing 3 print(i) 2. Type Casting Converting a variable from one type to another. • str → int: int("123") → 123 • int → float: float(5) → 5.0 • float → str: str(3.14) → "3.14" 3. == vs. is • ==: Compares values (are contents equal?). • is: Compares identities (are they the same object?). Use case: a = [1, 2]

b = [1, 2] print(a == b) # True (values equal) print(a is b) # False (different objects) 4. for vs. while Loop • for: Used when the number of iterations is known. • while: Used when looping until a condition becomes false. Example scenario for while: Keep asking the user for input until they enter "exit". 5. Nested Loops A loop inside another loop. Example use case (in words): Printing a multiplication table (rows and columns), or processing 2D data like a grid or matrix. Part II: Coding Problems (5 Marks Each) 1. Even or Odd n = int(input("Enter an integer: ")) if n % 2 == 0: print("Even") else: print("Odd") 2. Sum of First N Naturals N = int(input("Enter N: ")) total = 0 i = 1 while i <= N: total += i i += 1 print("Sum =", total) 3. Factorial n = int(input("Enter n: ")) fact = 1 for i in range(1, n + 1): fact *= i print(f"{n}! =", fact) 4. Multiplication Table x = int(input("Enter a number: ")) for i in range(1, 11):

print(f"{x} × {i} = {x * i}") 5. Prime Check p = int(input("Enter a number: ")) if p <= 1: print("Not Prime") else: for i in range(2, int(p**0.5) + 1): if p % i == 0: print("Not Prime") break else: print("Prime") 6. Sum of Digits m = int(input("Enter a number: ")) s = 0 while m > 0: s += m % 10 m = m // 10 print("Sum of digits =", s) 7. Reverse a String s = input("Enter a string: ") reversed_s = s[::-1] print("Reversed:", reversed_s) 8. Max and Min in a List nums = list(map(int, input("Enter numbers: ").split())) max_val = nums[0] min_val = nums[0] for num in nums: if num > max_val: max_val = num if num < min_val: min_val = num print("Max:", max_val) print("Min:", min_val) 9. Right-Angled Triangle Pattern h = int(input("Enter height: ")) for i in range(1, h + 1): print("* " * i) 10. Floyd’s Triangle r = int(input("Enter rows: ")) num = 1 for i in range(1, r + 1): for j in range(i): print(num, end=" ") num += 1 print() 11. Numeric Pyramid n = int(input("Enter height: ")) for i in range(1, n + 1):