0% found this document useful (0 votes)
24 views16 pages

Python Programming Exercises Guide

The document contains a series of exercises demonstrating various Python programming concepts, including running code in interactive mode, handling errors, performing mathematical operations, control flow, data structures, file handling, and functions. Each exercise includes an aim and corresponding code examples, showcasing practical applications such as calculating distances, checking for even numbers, and analyzing data with libraries like Pandas and Matplotlib. The exercises are structured to guide learners through foundational programming skills and problem-solving techniques.

Uploaded by

gairolaajaduk
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)
24 views16 pages

Python Programming Exercises Guide

The document contains a series of exercises demonstrating various Python programming concepts, including running code in interactive mode, handling errors, performing mathematical operations, control flow, data structures, file handling, and functions. Each exercise includes an aim and corresponding code examples, showcasing practical applications such as calculating distances, checking for even numbers, and analyzing data with libraries like Pandas and Matplotlib. The exercises are structured to guide learners through foundational programming skills and problem-solving techniques.

Uploaded by

gairolaajaduk
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

Exercise 1 – Basics

1(a) Running instructions in Interactive Interpreter and a Python Script


Aim: To demonstrate running Python code in the interactive shell and as a script.
>>> print("Hello from Interactive Mode")
Hello from Interactive Mode
>>> 5 + 10
15

1(b) Indentation Error (Raise and Correct)


Aim: To write a program that purposefully raises an Indentation Error and then corrects it.
def check_num(n):
if n > 0: # Missing indentation
print("Positive")

Code (Corrected Version):


def check_num(n):
if n > 0:
print("Positive")
check_num(5)
Output: Positive

1
Exercise 2 – Operations
2(a) Distance between two points (Pythagorean Theorem)
Aim: To compute the distance between two points $(x_1, y_1)$ and $(x_2, y_2)$.
Code:
import math
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
distance = [Link]((x2 - x1)**2 + (y2 - y1)**2)
print(f"Distance: {distance:.2f}")
2(b) Command Line Arguments ([Link])
Aim: To take 2 numbers as command line arguments and print their sum.
Code:
import sys
if len([Link]) < 3:
print("Please provide 2 numbers")
else:
num1 = float([Link][1])
num2 = float([Link][2])
print(f"Sum: {num1 + num2}")

2
Exercise 3 - Control Flow
3(a) Check if a number is Even or Not
Aim: To check whether a given number is even or odd.
Code:
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is Even")
else:
print(f"{num} is Odd")

3(b) Decimal equivalents of 1/2 to 1/10


Aim: To print decimal equivalents of fractions using a for loop.
Code:
for i in range(2, 11):
print(f"1/{i} = {1/i}")

3(c) Loop over a sequence


Aim: To iterate over a list sequence using a for loop.
Code:
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
print(fruit)
Output:
Apple
Banana
Cherry

3
3(d) Countdown using while loop
Aim: To print a countdown from a user-given number to zero.
Code:
count = int(input("Enter start number: "))
while count >= 0:
print(count)
count -= 1

4
Exercise 4 - Control Flow (Continued)
4(a) Sum of Primes below 2 million
Aim: To find the sum of all prime numbers below 2 million.
Code:
def sum_primes(limit):
sieve = [True] * limit
sieve[0] = sieve[1] = False
for i in range(2, int(limit**0.5) + 1):
if sieve[i]:
for j in range(i*i, limit, i):
sieve[j] = False
return sum(i for i, is_prime in enumerate(sieve) if is_prime)

print(f"Sum: {sum_primes(2000000)}")
Output: Sum: 142913828922
4(b) Sum of Even Fibonacci numbers (Values < 4 million)
Aim: To find the sum of even-valued terms in the Fibonacci sequence not exceeding 4
million.
Code:
a, b = 1, 2
total_sum = 0
while a <= 4000000:
if a % 2 == 0:
total_sum += a
a, b = b, a + b
print(f"Sum of even Fibonacci terms: {total_sum}")
Output: Sum of even Fibonacci terms: 4613732

5
4(c) Linear Search and Binary Search
Aim: To implement Linear and Binary Search.
Code:
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1

def binary_search(arr, x):


low = 0
high = len(arr) - 1
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
arr = [2, 3, 4, 10, 40]
print("Linear Search for 10:", linear_search(arr, 10))
print("Binary Search for 40:", binary_search(arr, 40))

Output:
Linear Search for 10: 3
Binary Search for 40: 4

6
Exercise 5 - Data Structures
5(a) Count characters in string (using Dictionary)
Aim: To count the occurrence of each character in a string.
Code:
text = "hello world"
freq = {}
for char in text:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
print(freq)
Output:
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
5(b) Birthday Dictionary (Split and Join)
Aim: To trace a birthday using dictionary and string methods.
Code:
birthdays = {"Alice": "May 1", "Bob": "Dec 12"}
query = input("Enter name (Alice/Bob): ")

if query in birthdays:
parts = birthdays[query].split() # split "May 1" into ["May", "1"]
print(f"Month: {parts[0]}, Day: {parts[1]}")
formatted = "-".join(parts)
print(f"Formatted: {formatted}")
Output:
Enter name (Alice/Bob): Alice
Month: May, Day: 1
Formatted: May-1

7
Exercise 6 - Data Structures (Continued)
6(a) Combine lists into a Dictionary
Aim: To write a program that combines two lists into a dictionary.
Code:
keys = ['Name', 'Age', 'City']
values = ['Alice', 25, 'New York']
combined_dict = dict(zip(keys, values))
print(combined_dict)

6(b) File Type Heuristic via Character Frequency


Aim: To guess if a file is Python, C, or Text based on character frequency (looking for { or ;
vs indentation).
Code:
def identify_file(content):
if "def " in content and "import " in content:
return "Python Program"
elif "#include" in content or ("{" in content and ";" in content):
return "C Program"
else:
return "Text File"
code_sample = "def main(): print('Hello')"
print(f"Sample is: {identify_file(code_sample)}")
Output:
Sample is: Python Program

8
Exercise 7 - Files
7(a) Print file lines in reverse
Aim: To read a file and print its lines in reverse order.
try:
with open("[Link]", "r") as f:
lines = [Link]()
for line in reversed(lines):
print([Link]())
except FileNotFoundError:
print("File not found.")
Output:
Line3
Line2
Line1
7(b) Compute Char, Word, Line count
Aim: To count characters, words, and lines in a file.
Code:
try:
with open("[Link]", "r") as f:
data = [Link]()
lines = [Link]()
words = [Link]()
print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
print(f"Characters: {len(data)}")
except FileNotFoundError:
print("File not found")
Output: Lines: 3
Words: 15
Characters: 85

9
Exercise 8 - Functions
8(a) Ball Collision
Aim: To check if two balls collide based on position and radius.
Code:
import math
def ball_collide(b1, b2):
x1, y1, r1 = b1
x2, y2, r2 = b2
distance = [Link]((x2 - x1)**2 + (y2 - y1)**2)
return distance <= (r1 + r2)
ball1 = (0, 0, 5)
ball2 = (6, 0, 5) # Distance is 6, Sum radii is 10. Should collide.
print(f"Collision: {ball_collide(ball1, ball2)}")
Output:
Collision: True
8(b) Mean, Median, Mode
Aim: To calculate mean, median, and mode of a list.
Code:
import statistics
data = [1, 2, 2, 3, 4, 7, 9]
print(f"Mean: {[Link](data)}")
print(f"Median: {[Link](data)}")
print(f"Mode: {[Link](data)}")
Output:
Plaintext
Mean: 4
Median: 3
Mode: 2

10
Exercise 9 - Functions (Continued)
9(a) Nearly Equal Strings
Aim: To check if two strings are nearly equal (one mutation away).
Code:
def nearly_equal(str1, str2):
count = 0
i=j=0
while i < len(str1) and j < len(str2):
if str1[i] != str2[j]:
count += 1
if len(str1) > len(str2): i += 1
elif len(str2) > len(str1): j += 1
else: i += 1; j += 1
else:
i += 1; j += 1
if count < 2: return True
return False
print(f"Is 'reset' nearly 'rest'? {nearly_equal('reset', 'rest')}")

11
9(b) Find Duplicates
Aim: To find duplicate elements in a list.
Code:
def dups(lst):
seen = set()
duplicates = set()
for x in lst:
if x in seen:
[Link](x)
[Link](x)
return list(duplicates)

print(f"Duplicates: {dups([1, 2, 3, 2, 1, 5])}")


Output:
Duplicates: [1, 2]

9(c) Find Unique Elements


Aim: To find unique elements in a list.
Code:
def unique(lst):
return list(set(lst))

print(f"Unique: {unique([1, 2, 2, 3])}")


Output:
Unique: [1, 2, 3]

12
Exercise 10 - Functions (Problem Solving)
10(a) Cumulative Product
Aim: To compute the cumulative product of a list.
Code:
def cumulative_product(lst):
result = []
prod = 1
for num in lst:
prod *= num
[Link](prod)
return result
print(f"Cumulative Product: {cumulative_product([1, 2, 3, 4])}")
Output:
Cumulative Product: [1, 2, 6, 24]

10(b) Reverse list (Manual)


Aim: To reverse a list without using the built-in reverse function.
Code:
def reverse_manual(lst):
new_lst = []
for i in range(len(lst)-1, -1, -1):
new_lst.append(lst[i])
return new_lst
print(f"Reversed: {reverse_manual([1, 2, 3])}")
Output:
Reversed: [3, 2, 1]

13
10(c) GCD and LCM (One-liners)
Aim: To compute GCD and LCM using one-line functions.
Code:
import math
gcd = lambda a, b: [Link](a, b)
lcm = lambda a, b: (a * b) // [Link](a, b)
print(f"GCD of 12, 15: {gcd(12, 15)}")
print(f"LCM of 12, 15: {lcm(12, 15)}")
Output:
GCD of 12, 15: 3
LCM of 12, 15: 60

14
Exercise 11 - Python Packages
11(a) Install Packages (Demonstration)
Aim: To demonstrate installation and usage of requests.
Code:
import requests
try:
r = [Link]('[Link]
print(f"Status Code: {r.status_code}")
except:
print("Internet connection required")
Output:
Status Code: 200
11(b) Plot graphs using Matplotlib
Aim: To plot a simple graph using Matplotlib.
Code:
import [Link] as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
[Link](x, y)
[Link]('X Axis')
[Link]('Y Axis')
[Link]('Sample Plot')
[Link]() # This will open a window
Output:

15
11(c) Data Analysis using Pandas
Aim: To create a simple DataFrame using Pandas.
Code:
import pandas as pd
data = {'Name': ['Tom', 'Jerry'], 'Age': [20, 21]}
df = [Link](data)
print(df)
Output:
Name Age
0 Tom 20
1 Jerry 21

16

You might also like