Python Core Programming
Q1. Write a program to add two numbers.
Problem Explanation
This simple program reads two numbers from user input and displays their sum. It demonstrates basic arithmetic operations and input/output in Python.
Step-By-Step Instructions
- Use input() to get numbers from user
- Convert input strings to integers using int()
- Add the two numbers
- Display the result using print()
Code
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum = num1 + num2
print(f"Sum of {num1} and {num2} is {sum}")
Output
Key Concept
input() returns strings, so type conversion is necessary. f-strings format output nicely. This is fundamental to Python data processing.
Q2. Write a program to find factorial.
Problem Explanation
Factorial of n (n!) = n × (n-1) × (n-2) × ... × 1. This program uses a loop to calculate factorial iteratively.
Step-By-Step Instructions
- Read a number from user
- Initialize result to 1
- Loop from 1 to n, multiplying each number
- Display the factorial
Code
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"Factorial of {n} is {factorial}")
Output
Key Concept
range(1, n+1) generates numbers 1 to n. *= operator multiplies and assigns. This demonstrates loop-based calculations and factorials.
Q3. Write a program to find simple interest.
Problem Explanation
Simple Interest = (Principal × Rate × Time) / 100. This program calculates SI using the financial formula.
Code
principal = float(input("Enter principal: "))
rate = float(input("Enter rate: "))
time = float(input("Enter time (years): "))
si = (principal * rate * time) / 100
print(f"Simple Interest: {si}")
print(f"Total Amount: {principal + si}")
Key Concept
Arithmetic operations in financial calculations. This demonstrates practical application of formulas in programming.
Q4. Write a program to check the string is palindrome or not.
Problem Explanation
A palindrome reads the same forwards and backwards. This program reverses the string and compares it with the original.
Code
string = input("Enter a string: ").lower().replace(" ", "")
reversed_string = string[::-1]
if string == reversed_string:
print(f"'{string}' is a palindrome")
else:
print(f"'{string}' is not a palindrome")
Key Concept
[::-1] reverses strings easily. lower() and replace() prepare string for comparison. This teaches string manipulation.
Q5. Write a program to reverse a string.
Problem Explanation
This program reverses a string using slicing. Python's built-in string slicing makes this operation straightforward.
Code
string = input("Enter a string: ")
reversed_string = string[::-1]
print(f"Original: {string}")
print(f"Reversed: {reversed_string}")
Output
Key Concept
[::-1] slicing with step -1 reverses. This is Pythonic and efficient. String immutability requires creating new strings.
Q6. Write a program to remove i'th character of string.
Problem Explanation
This program removes a character at a specific index using string slicing before and after the index.
Code
string = input("Enter a string: ")
index = int(input("Enter index to remove: "))
result = string[:index] + string[index+1:]
print(f"Result: {result}")
Key Concept
String slicing enables character removal. Concatenation rebuilds the string. This teaches string indexing and manipulation.
Q7. Write a program to check substring is present or not.
Problem Explanation
The 'in' operator in Python checks if a substring exists within a string. Case-sensitive by default.
Code
string = input("Enter a string: ")
substring = input("Enter substring to find: ")
if substring in string:
print(f"'{substring}' found in '{string}'")
else:
print(f"'{substring}' not found in '{string}'")
Key Concept
'in' operator is Pythonic for membership testing. Case sensitivity affects results. This teaches string searching fundamentals.
Q8. Program to swap first and last elements of list.
Problem Explanation
This program swaps the first and last elements of a list using tuple unpacking or temporary variable.
Code
lst = [1, 2, 3, 4, 5]
# Method 1: Tuple unpacking (Pythonic)
lst[0], lst[-1] = lst[-1], lst[0]
print(f"After swap: {lst}")
# Method 2: Temporary variable
# temp = lst[0]
# lst[0] = lst[-1]
# lst[-1] = temp
Key Concept
Tuple unpacking enables simultaneous assignment. lst[-1] accesses last element. This demonstrates Pythonic swapping.
Q9. Write a program to swap two elements in a list.
Problem Explanation
This program swaps two elements at given indices in a list.
Key Concept
Indexed access allows element manipulation. Tuple unpacking simplifies swapping. This teaches list operations.
Q10. Write A program to find out different ways to clear a list.
Problem Explanation
Python provides multiple ways to clear a list: clear() method, del keyword, or assignment to empty list.
Code Example
# Method 1: clear()
lst1 = [1, 2, 3]
lst1.clear() # lst1 = []
# Method 2: del (slicing)
lst2 = [1, 2, 3]
del lst2[:] # lst2 = []
# Method 3: Assignment
lst3 = [1, 2, 3]
lst3 = []
# Method 4: pop() in loop
lst4 = [1, 2, 3]
while lst4:
lst4.pop()
Key Concept
Multiple approaches to clearing demonstrate Python flexibility. clear() is most direct. This teaches list manipulation methods.
Q11. Write a python program to reversing list.
Problem Explanation
Lists can be reversed using reverse() method, slicing, or reversed() function.
Code Example
lst = [1, 2, 3, 4, 5]
# Method 1: reverse() - modifies in place
lst.reverse() # [5, 4, 3, 2, 1]
# Method 2: slicing - creates new list
lst2 = lst[::-1]
# Method 3: reversed() - returns iterator
lst3 = list(reversed(lst))
Key Concept
reverse() modifies in-place, slicing creates new list. Different methods suit different needs. This teaches list operations.
Q12. Python Program for Linear Search.
Problem Explanation
Linear search checks each element sequentially until target is found. Time complexity: O(n).
Code
def linear_search(lst, target):
for i in range(len(lst)):
if lst[i] == target:
return i
return -1
lst = [5, 2, 8, 1, 9]
target = 8
result = linear_search(lst, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Key Concept
Linear search is simple but slow for large lists. Binary search is faster but requires sorted data. This teaches fundamental search algorithms.
Q13. Write a program for insertion sort.
Problem Explanation
Insertion sort builds sorted array by inserting elements one at a time. Time complexity: O(n²).
Code
def insertion_sort(lst):
for i in range(1, len(lst)):
key = lst[i]
j = i - 1
while j >= 0 and lst[j] > key:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
return lst
lst = [64, 34, 25, 12, 22, 11, 90]
sorted_lst = insertion_sort(lst)
print(f"Sorted list: {sorted_lst}")
Key Concept
Insertion sort is stable and efficient for small lists. Elements shift to make room for insertion. This demonstrates fundamental sorting algorithms.
Q14. Python Program to demostrateuse of dictionaries by Key or Value.
Problem Explanation
Dictionaries store data as key-value pairs. Elements can be accessed, modified, and iterated by key or value.
Code
student = {"name": "John", "age": 25, "gpa": 3.8}
# Access by key
print(student["name"]) # John
# Iterate keys
for key in student.keys():
print(f"{key}: {student[key]}")
# Iterate values
for value in student.values():
print(value)
# Check key existence
if "age" in student:
print(f"Age: {student['age']}")
Key Concept
Dictionaries provide efficient O(1) lookup by key. keys(), values(), items() methods provide different iteration options. This teaches dictionary operations.
Q15. Python program to remove a key from dictionary.
Problem Explanation
Dictionary keys can be removed using del statement or pop() method. pop() returns the value while del doesn't.
Code
Python
student = {"name": "John", "age": 25, "gpa": 3.8}
# Method 1: del statement
del student["gpa"]
# Method 2: pop() - returns value
age = student.pop("age")
print(f"Removed age: {age}")
# Method 3: pop() with default
dept = student.pop("dept", "N/A") # Returns "N/A" if key not exists
print(f"Remaining: {student}")
student = {"name": "John", "age": 25, "gpa": 3.8}
# Method 1: del statement
del student["gpa"]
# Method 2: pop() - returns value
age = student.pop("age")
print(f"Removed age: {age}")
# Method 3: pop() with default
dept = student.pop("dept", "N/A") # Returns "N/A" if key not exists
print(f"Remaining: {student}")
Key Concept
pop() is safer as it handles missing keys. del raises error for missing keys. Both modify the dictionary in-place. This teaches dictionary manipulation.