Practice Mode

πŸ“š Student Practice

Original questions from assignments. Try solving them yourself!

πŸ“˜ The course source also has Practice Questions on Maths and Additional Python / Pandas Questions in notebook formβ€”same style, extra practice.

πŸ“ Assignment 1: Data Types & Strings

1 Create two numbers. One float another integer. Add two numbers and print the result in integer format. Easy
Create a float like 3.14 and an int like 5. Use int() to convert the sum to integer.
2 "i live in india since my childhood". Count number of 'i' in this text. Easy
Use the .count('i') method on strings. Be careful - this is case sensitive!
3 How do you check if a variable is of a certain data type in Python? Easy
Use type(variable) to get the type, or isinstance(variable, type) to check against a specific type.
4 Write a python code to find last 4 characters of a string: 'Machine Learning' Easy
Use negative slicing: string[-4:] gets the last 4 characters.
5 Write a python code to remove trailing space from string: 'Machine Learning. ' Easy
Use .rstrip() to remove trailing whitespace, or .strip() for both ends.
6 Write a Python program to print every second character from the string: "Data Science with Python" Medium
Use slicing with step: string[::2] gets every second character starting from index 0.
7 Write a python code to check given character is digit or not: 265 Easy
Convert to string first, then use .isdigit() method.
8 Write a python code to Convert a string to lowercase: 'MACHINE LEARNING' Easy
Use the .lower() method on strings.
9 Write a python code to count the number of occurrences of a character 'e' in a string: 'Machine Learning and Deep Learning' Easy
Use .count('e') method on the string.
10 Write a python code to check if a string contains only alphabetic characters. String = 'HelloPython' Easy
Use .isalpha() method - returns True if all characters are alphabetic.

πŸ”„ Assignment 2: Loops & Conditions

1 Create a list with numbers 1 to 10 in it ([1,2,3….10]). Write a for loop on this list to sum up all numbers in the list except 5 and 7. Print the result. Medium
Use if num not in [5, 7] or if num != 5 and num != 7 inside your loop before adding to sum.
2 Write a while loop to create a list with numbers from 1 to 100. When inserting new number in the list, skip every number which is divisible by 3. Print the result. Tip: To check whether number is divisible by 3 you can use % operator Medium
Use if num % 3 != 0 to check if NOT divisible by 3, then append to list.
3 Write a program that prints the 1 to 10 numbers. Easy
Use for i in range(1, 11) - remember range end is exclusive!
4 Write a python code to print the summation of all the numbers from 1 to 100. Easy
Use sum(range(1, 101)) or accumulate in a loop.
5 Write a Python program to find the common elements between two lists.
list1 = [11,2,190,43,23,65,19]
list2 = [12,11,121,190,43,23,76,190]
Medium
Convert to sets and use & operator: set(list1) & set(list2)
6 Write a python code to create separate lists of Even and Odd numbers from a list: [21,44,22,878,55,90,17,68,69,91] Medium
Loop through list, check num % 2 == 0 for even, else odd. Append to respective lists.
7 Calculate the sum of all numbers in a list using a loop: [21,44,767,98,37] Easy
Initialize total = 0, then total += num for each number in the list.
8 Write a python code to check if a number is positive, negative, or zero. Easy
Use if num > 0, elif num < 0, else for zero.
9 Find the length of the longest word in a string: 'Data Science and Machine Learning' Medium
Split string into words with .split(), then find max(words, key=len) or loop to find longest.
10 Write a program to calculate the sum of squares of all numbers from 1 to 10 using a while loop. Medium
Sum of squares: 1Β² + 2Β² + 3Β² + .... Add i**2 to total, increment i while i <= 10.

πŸ“¦ Assignment 3: Lists & Dictionaries

1 Create a list with numbers 1 to 10 and sort it in ascending and descending order. Easy
Use sorted(list) for ascending, sorted(list, reverse=True) for descending.
2 data = [1,2,3,4,6,7,7,8,9,9]. Drop duplicate values from this list and print the remaining numbers. Easy
Convert to set and back: list(set(data)). Use dict.fromkeys(data) to preserve order.
3 Write a python code to find the second largest number in a list: [21,44,767,98,37,106,345,87] Medium
Sort descending and get index 1, or use sorted(list)[-2]
4 Write a Python program to find the maximum and minimum values in a list: list1 = [21,44,767,98,37] Easy
Use built-in max(list1) and min(list1) functions.
5 Create two separate dictionaries and Merge them. Easy
Use {**dict1, **dict2} or dict1 | dict2 (Python 3.9+) or dict1.update(dict2)
6 Write a Python program to create a dictionary where keys are integers from 1 to 5 and corresponding values are their squares. Easy
Use dictionary comprehension: {i: i**2 for i in range(1, 6)}
7 Create a Python dictionary with keys as cars and values as their respective prices.
car_models = ["Toyota Camry", "Honda Civic", "Ford Mustang", "Chevrolet Silverado", "Nissan Altima"]
car_prices = [2500000, 2200000, 4000000, 3500000, 2300000]
Easy
Use dict(zip(car_models, car_prices)) to combine two lists into a dictionary.
8 Create a dictionary with 5 key pair values. Key would be a grocery item name and value will be its price (any value in the range of 10 to 1000). Write a for loop to iterate over a dictionary and print key-value pairs. While printing if the value is greater Rs. 500 then print a line – "this is a costly item." Medium
Use for item, price in dict.items(): to iterate, then if price > 500: to check.
9 In the dictionary created in above task, delete the key value pairs where price is less than average price of all the items in the dictionary. Medium
Calculate avg with sum(dict.values())/len(dict). Create new dict with items above avg, or use dict comprehension.
10 Write a python code that takes two sets as input and returns a set containing only the common elements. Easy
Use set1 & set2 or set1.intersection(set2) to find common elements.

βš™οΈ Assignment 4: Functions

1 Create a function which takes 2 numbers as inputs and returns the following three values: Addition of two numbers, Subtraction of two numbers, Multiplication of two numbers. Easy
Return multiple values with return a+b, a-b, a*b. Call with add, sub, mul = func(x, y)
2 Write a python function to calculate the factorial of a given integer: 10

For example: Factorial of 5 = 5Γ—4Γ—3Γ—2Γ—1 = 120
Medium
Use a loop: start with result=1, multiply by each number from 2 to n. Or use recursion.
3 Write a python function that takes a list of integers as input and returns a new list with the integers sorted in descending order. Easy
Use return sorted(lst, reverse=True) inside your function.
4 Write a python function that takes a string as input and returns the number of vowels in the string. Easy
Loop through string, check if char.lower() in 'aeiou', count matches.
5 Create a function that checks if a given number is even or odd. Easy
Use num % 2 == 0 to check even. Return "Even" or "Odd" string, or True/False.
6 Create a function to find the sum of all even numbers in a list: [12,2,33,11,45,8] Medium
Filter evens first: sum(n for n in lst if n % 2 == 0)
7 Write a function to remove duplicate elements from a list. Easy
Use return list(set(lst)) or list(dict.fromkeys(lst)) to preserve order.
8 Create a Python function to reverse a string. Easy
Use slicing: return text[::-1]
9 Create a function greet_user that takes a name as an argument and prints "Hello, [Name]!". If no name is provided, it should print "Hello, Guest!" Easy
Use default parameter: def greet_user(name="Guest"):
10 Create a function that takes an integer as input and returns its cube. Easy
Cube is nΒ³: return n ** 3 or return n * n * n

πŸš€ Assignment 5: OOP, NumPy & Pandas

1 Write a Python Class Circle which has the following variables and functions: Hard

Variables:

β€’ pi_value = 3.14 (private variable)

β€’ radius

Functions:

β€’ area_calculator

β€’ circumference_calculator

Task: Create an object of Class Circle and calculate its area and circumference.

Use __pi_value for private variable. Area = Ο€ Γ— rΒ². Circumference = 2 Γ— Ο€ Γ— r. Use __init__ to set radius.
2 Write a function which returns the addition of all numbers in a numpy array. NumPy array should contain 50 random numbers in the range of 10 to 100 generated using random number generator. Medium
Use np.random.randint(10, 101, size=50) and np.sum(array)
3 NumPy Matrix Operations: Hard

i) Create a 3Γ—2 (3 rows, 2 columns) matrix using numpy and transpose it.

ii) After transposing print the first row of matrix (index 0)

iii) Print second element in first row

iv) Flatten the matrix to 1D (1 Dimensional) array

v) Print maximum, minimum and average value of 1D array

Create with np.array([[...],[...],[...]]). Transpose with .T. Flatten with .flatten(). Stats: np.max(), np.min(), np.mean()
4 Read the Housing.csv file in your notebook and perform the following operations:

πŸ“₯ Download dataset: Housing.csv β€” save in the same folder as your notebook.

Hard

i) Calculate average and median price per square foot area (assume area column's unit is sq ft)

ii) Calculate median price per bedroom.

iii) Calculate average price per sq ft for furnished, semi-furnished and unfurnished homes.

iv) Are homes with guestrooms AND main road location costlier than remaining houses? Analyze the data using pandas to come up with your answer.

v) Convert the values in air conditioning column to 0 and 1 using lambda function

vi) Create a new column with the name price_index. Assign it 1 if the price of house is higher than average price else assign it value 0

vii) Sort the data by area, bathrooms and bedrooms column in descending order

Use pd.read_csv('Housing.csv'). Price per sqft: df['price']/df['area']. GroupBy for categories: df.groupby('furnishingstatus')['price'].mean(). Lambda: df['ac'].apply(lambda x: 1 if x == 'yes' else 0)

✍️ Ready to try?

Open Python on your computer or use an online editor like Replit or Google Colab to practice!