0% found this document useful (0 votes)
4 views13 pages

Python Programming Problems and Solutions

This document is a revision and practice booklet for Python programming, covering fundamental concepts such as variables, data types, control statements, and lists through 32 solved problems. Each problem includes a solution, sample output, and key ideas to aid understanding. The booklet is structured into three parts, focusing on fundamentals, strings and control statements, and lists and tuples.

Uploaded by

2023332002
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)
4 views13 pages

Python Programming Problems and Solutions

This document is a revision and practice booklet for Python programming, covering fundamental concepts such as variables, data types, control statements, and lists through 32 solved problems. Each problem includes a solution, sample output, and key ideas to aid understanding. The booklet is structured into three parts, focusing on fundamentals, strings and control statements, and lists and tuples.

Uploaded by

2023332002
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

PYTHON PROGRAMMING

Potential Problems & Step-by-Step


Solutions

Based on three course lectures

Variables • Data Types • Operators • Strings • Control Statements • Lists • Tuples

32 solved problems • sample outputs • exam-focused key ideas

Prepared as an A4 revision and practice booklet

Python Programming | Problems & Solutions Page 1


How to Use This Booklet
First try each problem without looking at the solution. Then compare your logic, indentation, operators, and output. Run
the code with different inputs to test boundary cases.

Part Main topics Problems

1 Variables, types, input/output, operators 1-10

2 Strings, slicing, methods, decisions, nested if 11-25

3 Lists, slicing, methods, tuples 26-32

Important Rules
• input() always returns a string; cast it when numerical input is required.

• Use == for comparison and = for assignment.

• Indent blocks consistently, normally with four spaces.

• Strings and tuples are immutable; lists are mutable.

• In slicing, the start is included and the end is excluded.

Python Programming | Problems & Solutions Page 2


Part 1 — Fundamentals
Solve each task first, then use the code and sample output to verify your answer.

Problem 1: Print a Greeting


Display Hello World and your name on separate lines.
Solution
print("Hello World")
print("My name is Shamim")

Sample output
Hello World
My name is Shamim

Key idea: print() displays text or values.

Problem 2: Variables and Data Types


Store a name, age, price, and availability status. Print each value and its type.
Solution
name = "Shamim"
age = 23
price = 25.99
available = True

print(name, type(name))
print(age, type(age))
print(price, type(price))
print(available, type(available))

Key idea: Typical types are str, int, float, and bool.

Problem 3: Sum of Two Numbers


Input two integers and print their sum.
Solution
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum is:", a + b)

Sample output
Enter first number: 12
Enter second number: 8
Sum is: 20

Key idea: input() returns a string, so int() is required.

Problem 4: Area of a Square


Input the side length of a square and calculate its area.
Solution
side = float(input("Enter side length: "))
area = side ** 2
print("Area of square:", area)

Sample output
Enter side length: 5
Area of square: 25.0

Key idea: The exponent operator ** calculates powers.

Python Programming | Problems & Solutions Page 3


Problem 5: Average of Two Floats
Input two floating-point numbers and print their average.
Solution
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
average = (x + y) / 2
print("Average is:", average)

Sample output
Enter first number: 4.5
Enter second number: 7.5
Average is: 6.0

Key idea: Parentheses ensure the sum is calculated first.

Problem 6: Compare Two Numbers


Input a and b. Print True if a is greater than or equal to b; otherwise print False.
Solution
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print(a >= b)

Sample output
Enter a: 10
Enter b: 4
True

Key idea: Comparison operators return Boolean values.

Problem 7: Simple Bill Calculator


Input price, quantity, and discount. Add 5% tax after discount and print the grand total.
Solution
price = float(input("Price: "))
quantity = int(input("Quantity: "))
discount = float(input("Discount: "))
subtotal = price * quantity
after_discount = subtotal - discount
tax = after_discount * 0.05
grand_total = after_discount + tax
print("Grand total:", grand_total)

Sample output
Price: 120
Quantity: 3
Discount: 10
Grand total: 367.5

Key idea: A longer expression is clearer when divided into steps.

Problem 8: Assignment Operators


Start with a balance of 1000, deposit 500, withdraw 200, then add 2% interest.
Solution
balance = 1000
balance += 500
balance -= 200
balance *= 1.02
print("Final balance:", balance)

Sample output
Final balance: 1326.0

Key idea: x += y is shorthand for x = x + y.

Python Programming | Problems & Solutions Page 4


Problem 9: Logical Loan Check
Approve a loan only when income is above 30000 and credit score is above 650.
Solution
income = int(input("Monthly income: "))
credit_score = int(input("Credit score: "))
approved = income > 30000 and credit_score > 650
print("Approved:", approved)

Sample output
Monthly income: 45000
Credit score: 720
Approved: True

Key idea: and requires both conditions to be True.

Problem 10: Correct the Type Error


The expression 1 + "2" fails. Correct it so the result is 3.
Solution
a = 1
b = "2"
total = a + int(b)
print(total)

Sample output
3

Key idea: Python does not automatically add an int and a str.

Python Programming | Problems & Solutions Page 5


Part 2 — Strings and Control Statements
Solve each task first, then use the code and sample output to verify your answer.

Problem 11: Age from Birth Year


Input a birth year and calculate age using 2026 as the current year.
Solution
current_year = 2026
year = int(input("Enter birth year: "))
age = current_year - year
print("Your age is:", age)

Sample output
Enter birth year: 2001
Your age is: 25

Key idea: This is a direct application of input, casting, and subtraction.

Problem 12: Escape Sequences


Print a name and department on separate lines, then print city and country separated by a tab.
Solution
print("Name: Forhad\nDepartment: CSE")
print("Sylhet\tBangladesh")

Sample output
Name: Forhad
Department: CSE
Sylhet Bangladesh

Key idea: \n creates a new line and \t creates horizontal spacing.

Problem 13: Concatenation and Length


Join Sylhet and Bangladesh as Sylhet, Bangladesh and print the number of characters.
Solution
city = "Sylhet"
country = "Bangladesh"
full = city + ", " + country
print(full)
print("Length:", len(full))

Sample output
Sylhet, Bangladesh
Length: 18

Key idea: len() counts letters, punctuation, and spaces.

Problem 14: String Indexing


For PYTHON, print the first, third, and last characters using indexing.
Solution
word = "PYTHON"
print(word[0])
print(word[2])
print(word[-1])

Sample output
P
T
N

Key idea: Negative index -1 means the last character.

Python Programming | Problems & Solutions Page 6


Problem 15: String Slicing
From amazing, produce ama, azi, amaz, and zing using slicing.
Solution
word = "amazing"
print(word[0:3])
print(word[2:5])
print(word[:4])
print(word[3:])

Sample output
ama
azi
amaz
zing

Key idea: A slice includes the start index but excludes the end index.

Problem 16: String Methods


For an email, print lowercase form, test whether it ends in .edu, and replace sust with cse.
Solution
email = "[Link]@[Link]"
print([Link]())
print([Link](".edu"))
print([Link]("sust", "cse"))

Sample output
[Link]@[Link]
True
[Link]@[Link]

Key idea: String methods return new strings; the original is unchanged.

Problem 17: Count a Character


Count lowercase a in I am a student of Data Science.
Solution
sentence = "I am a student of Data Science"
print("Occurrences:", [Link]("a"))

Sample output
Occurrences: 4

Key idea: count() returns the total number of non-overlapping occurrences.

Problem 18: Odd or Even


Input an integer and determine whether it is odd or even.
Solution
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even")
else:
print("Odd")

Sample output
Enter a number: 17
Odd

Key idea: An even number leaves remainder 0 when divided by 2.

Python Programming | Problems & Solutions Page 7


Problem 19: Greatest of Three
Input three numbers and print the greatest, including cases where values are equal.
Solution
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
if a >= b and a >= c:
print("Greatest:", a)
elif b >= a and b >= c:
print("Greatest:", b)
else:
print("Greatest:", c)

Sample output
Enter a: 12
Enter b: 25
Enter c: 9
Greatest: 25.0

Key idea: Using >= correctly handles ties.

Problem 20: Multiple of Seven


Check whether a user-entered number is a multiple of 7.
Solution
number = int(input("Enter a number: "))
if number % 7 == 0:
print(number, "is a multiple of 7")
else:
print(number, "is not a multiple of 7")

Sample output
Enter a number: 49
49 is a multiple of 7

Key idea: A multiple produces remainder 0.

Problem 21: Grade Calculator


Assign A+ for 80 or above, A for 70-79, B for 60-69, C for 50-59, and F below 50. Reject marks outside 0-100.
Solution
marks = int(input("Enter marks: "))
if marks < 0 or marks > 100:
print("Invalid marks")
elif marks >= 80:
print("Grade: A+")
elif marks >= 70:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")

Sample output
Enter marks: 76
Grade: A

Key idea: Order conditions from the highest range downward.

Python Programming | Problems & Solutions Page 8


Problem 22: Triangle Validity
Input three positive sides and determine whether they can form a triangle.
Solution
a = float(input("Side a: "))
b = float(input("Side b: "))
c = float(input("Side c: "))
if a > 0 and b > 0 and c > 0 and a+b > c and b+c > a and a+c > b:
print("Valid triangle")
else:
print("Not a valid triangle")

Sample output
Side a: 3
Side b: 4
Side c: 5
Valid triangle

Key idea: For a valid triangle, every pair of sides must exceed the third.

Problem 23: Leap Year


Determine whether a year is a leap year using nested if statements.
Solution
year = int(input("Enter a year: "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year")
else:
print("Not a leap year")
else:
print("Leap year")
else:
print("Not a leap year")

Sample output
Enter a year: 2000
Leap year

Key idea: Century years must also be divisible by 400.

Problem 24: Roller-Coaster Eligibility


A rider must be at least 48 inches tall. Set ticket prices by age: under 12 = $15, 12-18 = $25, over 18 = $40.
Solution
height = float(input("Height in inches: "))
age = int(input("Age: "))
if height >= 48:
if age < 12:
print("Eligible. Ticket: $15")
elif age <= 18:
print("Eligible. Ticket: $25")
else:
print("Eligible. Ticket: $40")
else:
print("Not eligible")

Sample output
Height in inches: 60
Age: 15
Eligible. Ticket: $25

Key idea: Nested if checks age only after height eligibility is satisfied.

Python Programming | Problems & Solutions Page 9


Problem 25: Password Strength
Require at least 8 characters, at least one letter, and at least one uppercase letter.
Solution
password = input("Create a password: ")
if len(password) < 8:
print("Too short")
elif [Link]():
print("Add letters")
elif [Link]() == password:
print("Add an uppercase letter")
else:
print("Strong password")

Sample output
Create a password: Python2026
Strong password

Key idea: Comparing text with its lowercase version detects uppercase letters.

Python Programming | Problems & Solutions Page 10


Part 3 — Lists and Tuples
Solve each task first, then use the code and sample output to verify your answer.

Problem 26: Favourite Movies


Input three favourite movie names and store them in a list.
Solution
movies = []
for i in range(3):
movie = input(f"Movie {i + 1}: ")
[Link](movie)
print("Favourite movies:", movies)

Sample output
Movie 1: Inception
Movie 2: Interstellar
Movie 3: Avatar
Favourite movies: ['Inception', 'Interstellar', 'Avatar']

Key idea: append() adds one item to the end of a list.

Problem 27: List Slicing


Given [10, 20, 30, 40, 50, 60], print the middle four items, first three items, and items from index 3 onward.
Solution
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:5])
print(numbers[:3])
print(numbers[3:])

Sample output
[20, 30, 40, 50]
[10, 20, 30]
[40, 50, 60]

Key idea: List slicing follows the same start-inclusive, end-exclusive rule.

Problem 28: List Methods


Starting with [2, 1, 3], append 4, insert 5 at index 1, sort descending, and reverse the result.
Solution
numbers = [2, 1, 3]
[Link](4)
[Link](1, 5)
[Link](reverse=True)
print("Descending:", numbers)
[Link]()
print("Reversed:", numbers)

Sample output
Descending: [5, 4, 3, 2, 1]
Reversed: [1, 2, 3, 4, 5]

Key idea: sort(reverse=True) sorts descending; reverse() only reverses current order.

Python Programming | Problems & Solutions Page 11


Problem 29: Remove and Pop
From [2, 1, 3, 1], remove the first 1, then pop the item at index 1 and display both the removed value and final list.
Solution
numbers = [2, 1, 3, 1]
[Link](1)
removed = [Link](1)
print("Popped:", removed)
print("Final list:", numbers)

Sample output
Popped: 3
Final list: [2, 1]

Key idea: remove(value) uses a value; pop(index) uses a position and returns the item.

Problem 30: Palindrome List


Check whether a list is a palindrome using copy() and reverse().
Solution
items = [1, 2, 3, 2, 1]
reversed_items = [Link]()
reversed_items.reverse()
if items == reversed_items:
print("Palindrome")
else:
print("Not palindrome")

Sample output
Palindrome

Key idea: copy() prevents the original list from being reversed.

Problem 31: Tuple Grade Count


Count grade A in (C, D, A, A, B, B, A), then convert the tuple to a list and sort it from A to D.
Solution
grades = ("C", "D", "A", "A", "B", "B", "A")
print("Number of A grades:", [Link]("A"))
grade_list = list(grades)
grade_list.sort()
print("Sorted:", grade_list)

Sample output
Number of A grades: 3
Sorted: ['A', 'A', 'A', 'B', 'B', 'C', 'D']

Key idea: Tuples are immutable, so convert to a list before sorting.

Problem 32: Tuple Index and Count


Find the first index of apple and count how many times it appears.
Solution
fruits = ("banana", "apple", "mango", "apple")
print("First index:", [Link]("apple"))
print("Count:", [Link]("apple"))

Sample output
First index: 1
Count: 2

Key idea: index() returns the first occurrence; count() returns all occurrences.

Python Programming | Problems & Solutions Page 12


Quick Revision Sheet
Purpose Syntax / method

Display output print(value)

Read input input(prompt)

Cast values int(), float(), str(), list(), tuple()

Power / remainder ** / %

Combine conditions and, or, not

Slice sequence[start:end]

String tools .lower(), .upper(), .replace(), .find(), .count()

Add list items .append(value), .insert(index, value)

Remove list items .remove(value), .pop(index)

Order list .sort(), .sort(reverse=True), .reverse()

Tuple lookup .index(value), .count(value)

Final Advice
Do not memorize code line by line. Understand the input, required processing, condition, and expected output. Practise
by changing values and predicting the result before running each program.

Python Programming | Problems & Solutions Page 13

You might also like