Python Foundational Practice & Code Challenges
Welcome to the hands-on practice workbook. This section contains realistic problems designed to test your core algorithmic thinking, optimization strategies, and engineering workflows.
Community Challenges & External Resources
To expand your practice routine beyond this module directory, explore this curated repository containing structured daily programming sprints:
- External Sprints: Break the Ice with Python — External daily reference repo for foundational programming drills.
Practice Portfolio
1: TYPE CONVERSION
Question: Build a runtime console program that prompts for a birth year, converts it to an integer, calculates age based on the year 2025, and prints it.
Hint: Text from input() defaults to a String (str). You must cast it to an integer to perform math.
Concept: Variables & Math Operations
birth_year = input("Enter your birth year: ")
age = 2025 - int(birth_year)
print (f'your age is: {age}')
2: PASSWORD CHECKER
Question: Capture a username and password, calculate the password length, mask it with asterisks (*), and print a confirmation message.
Hint: Multiply a string character by an integer (e.g., '*' * 5) to repeat it. Use len() for length.
Concept: Strings & Indexing & Variables
username = input ("Enter your Username")
password = input ("Enter your password")
password_length = len(password)
hidden_password = password_length * '*'
print(f"Hey {username}, your password {hidden_password} is {password_length} letter long")
3: LOGICAL OPERATOR
Question: Evaluate the boolean flags is_magician and is_expert to print distinct messages depending on their skill combination.
Hint: Combine logical checks using and along with not for negative state evaluations.
Concept: Boolean Type & Conditional Logic
is_magician = True
is_expert = False
if is_magician and is_expert:
print('you are a master magician')
elif is_magician and not is_expert:
print('at least you\'re getting there')
elif not is_magician:
print('you need magic powers')
4: TRICKY COUNTER
Question: Compute the total cumulative sum of numbers from 1 to 10 within a sequence without printing the intermediate steps.
Hint: Keep your final print statement un-indented completely outside the loop to avoid iteration logging.
Concept: Loops & Lists
myList = [1,2,3,4,5,6,7,8,9,10]
counter = 0 #we need varible on the outside of loop
for i in myList:
counter = counter + i
print(counter) #the print indentation to be outside of the loop to avoid iteration
5: INDEX FINDER
Question: Generate a range up to 100, scan the sequence, and print out the exact list index when the value hits 50.
Hint: The enumerate() built-in automatically generates sequential tracker keys alongside loop items.
Concept: Loops & Lists
for i,char in enumerate (list(range(100))):
if char == 50:
print (f'index of 50 is : {i}')
6: GUI EXERCISE
Question: Loop over a nested multidimensional binary matrix to print asterisks (*) for true entries and blank space for false ones.
Hint: Set the keyword argument end='' inside your print statement to prevent automatic newline breaks.
Concept: Loops & Functions
picture = [
[0,0,0,1,0,0,0],
[0,0,1,1,1,0,0],
[0,1,1,1,1,1,0],
[1,1,1,1,1,1,1],
[0,0,0,1,0,0,0],
[0,0,0,1,0,0,0]
]
# Generates a Christmas tree
def show_tree():
for row in picture: #for loop, item, variable
for pixel in row: #nesting, item of item(pixels in row)
if pixel: #conditional logic, item & logical operator(pixel == 1) or just pixel because we don't need 1(its a truthy value)
print('*', end='') #Default behavior: newline after each print, using end=''empty string
else:
print(' ', end='')
print('') #need new line after every list
show_tree()
7: FIND DUPLICATES
Question: Extract and isolate repeating duplicate characters from a raw list into a clean validation array without recurrence.
Hint: Track occurrences with .count(), and use a not in conditional check to avoid duplications.
Concept: Lists & Conditional Logic
some_list = ['a', 'b', 'c', 'd', 'b', 'm', 'n', 'n']
duplicates = []
for char in some_list:
if some_list.count(char) > 1:
if char not in duplicates: #avoids repeatability
duplicates.append(char)
#for loop, .count() & .append(), if, in & not
print(duplicates)
8: CHECK DRIVER AGE
Question: Write an engine evaluating an optional age variable to print distinct driver eligibility profiles across three gates.
Hint: Configure a safe fallback value (like age = 0) straight inside your function argument definitions.
Concept: Functions & Conditional Logic
def checkDriverAge(age = 0):
if int(age) < 18:
print("Sorry, you are too young to drive this car. Powering off")
elif int(age) > 18:
print("Powering On. Enjoy the ride!")
elif int(age) == 18:
print("Congratulations on your first year of driving. Enjoy the ride!")
checkDriverAge()
9: FUNCTIONS EXERCISE
Question: Build a function that drops odd digits from a list parameter, extracts the even items, and returns the highest target even number.
Hint: Use the modulo parameter item % 2 == 0 to discover evens, then wrap your final result in max().
Concept: Functions & Math Operations
def highest_even(li):
evens = []
for item in li:
if item % 2 == 0:
evens.append(item)
return max(evens)
print(highest_even([1,2,3,4,5,11,21,10]))
10: CATS EVERYWHERE
Question: Setup a dynamic base blueprint tracking cat profiles, instantiate three objects, and use a functional utility to extract the top age.
Hint: The syntax *args lets a function cleanly handle a variable number of positional arguments as an iterable list.
Concept: Object-Oriented Programming
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
cat1 = Cat('whisker', 10)
cat2 = Cat('kitty', 3)
cat3 = Cat('jewels', 6)
def oldest_cat(*args):
return max(args)
print(
f'The oldest cat is {oldest_cat(cat1.age, cat2.age, cat3.age)} years old')
11: Inheritance Exercise
Question: Design an architectural base class layout and sub-classes that polymorphicly run identical tracking behaviors.
Hint: Pass child objects down inside structural tracking arrays to cleanly execute custom overridden configurations.
Concept: Object-Oriented Programming
class Pets():
animals = []
def __init__(self, animals):
self.animals = animals
def walk(self):
for animal in self.animals:
print(animal.walk())
class Cat():
def __init__(self, name, age):
self.name = name
self.age = age
def walk(self):
return f'{self.name} is just walking around'
class Simon(Cat):
def sing(self, sounds):
return f'{sounds}'
class Sally(Cat):
def sing(self, sounds):
return f'{sounds}'
#1 Add another Cat
class Jerry(Cat):
def sing(self, sounds):
return f'{sounds}'
my_cats = [Simon('Simon', 5), Sally('Sally', 3), Jerry('Jerry', 4)]
my_pets = Pets(my_cats)
my_pets.walk()
12: EXTENDING LIST
Question: Inherit from the native built-in list primitive but override its magic dunder length calculation property to return 1000.
Hint: Subclassing primitives like list maintains core behaviors like .append() while allowing targeted dunder overrides.
Concept: Object-Oriented Programming & Lists
class SuperList(list): #inheriting from built-in with parameter list
def __len__(self):
return 1000
super_list1 = SuperList()
print(len(super_list1))
super_list1.append(5)
print(super_list1[0])
print(issubclass(SuperList, list))
13: FUNCTIONAL PROGRAMMING EXERCISE
Question: Run data pipelines applying functional methods to mutate arrays via map, sequence pairs via zip, and limit data with filter.
Hint: Pure functional steps do not modify collections in-place; wrap outputs in type explicit factories like list().
Concept: Functional Programming
from functools import reduce
my_pets = ['sisi', 'bibi', 'titi', 'carla']
def capitalize (char):
return char.upper()
print(list(map(capitalize, my_pets)))
my_strings = ['a', 'b', 'c', 'd', 'e']
my_numbers = [5,4,3,2,1]
print(tuple(zip(sorted(my_numbers), my_strings)))
scores = [73, 20, 65, 19, 76, 100, 88]
def greater_50(num):
return num >= 50
print(list(filter(greater_50, scores)))
def accumulator(acc, item):
return acc + item
print(reduce(accumulator, (my_numbers + scores)))
14: Lambda EXERCISE
Question: Build anonymous mathematical transformation formulas, and execute custom tuple list sorting pathways using specific secondary index keys.
Hint: Supply a lambda script definition pointing to target mapping coordinates inside your .sort(key=...) keyword parameter.
Concept: Functional Programming & Tuples
my_list = [5,4,3]
print(list(map(lambda i: i ** 2, my_list)))
# List sorting
a = [(0,2), (4,3), (9,9), (10,-1)]
a.sort(key= lambda x: x[1]) #sorts according to second item in tuple
print(a)
15: COMPREHENSION EXERCISE
Question: Refactor multi-line loops using list comprehensions and set castings to clean duplicate items in a streamlined operational step.
Hint: Nest your collection parsing array checks directly within list tracking bounds [x for x in li if ...].
Concept: Functional Programming & Sets
some_list = ['a', 'b', 'c', 'd', 'b', 'm', 'n', 'n']
duplicates = list(set([x for x in some_list if some_list.count(x) > 1]))
print(duplicates)
16: DECORATOR EXERCISE
Question: Develop a high-order function decorator pattern named @authenticated that intercepts user profile calls to validate tracking properties.
Hint: The decorator wrapper layer takes functional arguments and checks indexes before triggering inner targets.
Concept: Decorators
user1 = {
'name': 'Sorna',
'valid': True
}
def authenticated(fn):
def wrapper(*args, **kwargs):
if args[0]['valid']== True: #== True is not needed because it checks for truthy value
return fn(*args, **kwargs)
else:
return print('invalid user')
return wrapper
@authenticated
def message_friends(user):
print('message has been sent')
message_friends(user1)
17: ERROR HANDLING EXERCISE
Question: Enforce defensive entry pipelines within infinite input sequences handling calculation and structural type failures gracefully.
Hint: Use explicit exception parameters like except ValueError: and execute teardown states using finally:.
Concept: Error Handling
while True:
try:
age = int(input('Enter your age:' ))
10/age
except ValueError:
print('please enter a valid number')
#continue #continue, if value error occurs. the code starts over
except ZeroDivisionError:
print('Enter value more than Zero')
break #breaks from the loop, does'nt print the actual age
else:
print('thank you')
#break #breaks out of the loop
finally:
print('ok, I am finally done')
print('can you hear me?') #it does'nt get printed until the break statement is present
18: FIBONACCI EXERCISE
Question: Construct two numeric progression calculators tracking sequence generation metrics via list arrays versus lazy evaluated generators.
Hint: Generators deploy the yield statement to return elements tracking real-time states sequentially instead of storing values in RAM blocks.
Concept: Generators
# generators keeps the value in same location and just prints it out instead of saving in the memory
def fib_gen(num):
a = 0
b = 1
for item in range(num):
yield a
temp = a
a = b
b = temp + a
for i in fib_gen(20):
print(i)
# list keep every value in different locations
def fib_list(num):
a = 0
b = 1
list = []
for item in range(num):
list.append(a)
temp = a
a = b
b = temp + a
return list
print(fib_list(20))
19: GUESS A NUMBER
Question: Code an interactive gaming interface selecting integer criteria boundaries, prompting for loop parsing inputs, and safeguarding against typing crashes.
Hint: Leverage standard try/except constructs over your conversion layers to intercept invalid syntax anomalies cleanly.
Concept: Modules & Packages & Error Handling
import random
print('GUESS A NUMBER')
x = random.randint(1, 10)
# if argv[1] and argv[2]:
# x = randint(int(argv[1]), int(argv[2]))
# else:
print(x)
while True:
try:
guess = int(input('enter a numbers 1-10: '))
if guess is x:
print('You are a genius')
break
except ValueError:
print('you did something wrong')
continue
20: TRANSLATOR
Question: Build an automation step utilizing terminal commands to download dependencies, parse file streams, and log translations.
Hint: Deploy system paths safely surrounded by with open(...) patterns to handle file open/close automation rules seamlessly.
Concept: File I/O & Development Tools
import subprocess
subprocess.check_call([__import__('sys').executable, '-m', 'pip', 'install', 'translate'])
from translate import Translator
translator = Translator(to_lang='ja')
try:
with open("C:/Users/marwa/OneDrive/Desktop/test.txt", mode='r') as my_file:
text = my_file.read()
translation = translator.translate(text)
with open('./test-ja.txt', 'w') as my_file2:
my_file2.write(translation)
except FileNotFoundError as err:
print('file not found')