Python Programming Labs

Master Python collections, functions, and string manipulation through hands-on coding challenges.

Collections & Functions - Module 2

Build practical Python skills with lists, functions, and string operations.

Lab 4: Lists & Collections
Beginner
Coding Challenge
Your Task: Create and manipulate a Python list to manage a collection of fruits. Learn essential list operations that you'll use constantly in Python programming.

Detailed Requirements:
1. Create a list called "fruits" - Initialize with at least 3 fruits: fruits = ["apple", "banana", "cherry"]
   • Lists are ordered, mutable (changeable) collections
   • Use square brackets [] to create a list
   • Items are separated by commas
   • Lists can contain mixed types, but usually hold similar items

2. Add an item using append() - Add "orange" to the end: fruits.append("orange")
   • append() adds ONE item to the end of the list
   • Modifies the list in-place (doesn't return a new list)
   • To add multiple items, use extend() or + operator

3. Access items by index - Print the first fruit: print(fruits[0])
   • Python uses ZERO-BASED indexing (first item is index 0)
   • Negative indices count from the end: fruits[-1] is the last item
   • IndexError occurs if index is out of range

4. Get the list length - Use len(fruits) to count items
   • len() returns the number of items in a list
   • Works on strings, tuples, dictionaries, and other iterables too

5. Loop through the list - Print each fruit using a for loop:
for fruit in fruits: print(fruit)

💡 Pro Tips:
• Check if item exists: if "apple" in fruits:
• Remove by value: fruits.remove("banana")
• Remove by index: del fruits[0] or fruits.pop(0)
• Slice a list: fruits[1:3] gets items at index 1 and 2
• Sort a list: fruits.sort() or sorted(fruits)

Expected Output:
Original list: ['apple', 'banana', 'cherry'] After append: ['apple', 'banana', 'cherry', 'orange'] First fruit: apple List length: 4 All fruits: apple banana cherry orange

Requirements Checklist

Create a list called "fruits" with at least 3 items
Use append() to add an item to the list
Access an item using index notation [0]
Use len() to get the list length
Use a for loop to iterate through the list
Print the list contents
Output
# Click "Run Code" to execute your Python code # Your program output will appear here
Hints & Tips
• Create list: fruits = ["apple", "banana", "cherry"]
• Add item: fruits.append("orange")
• Access first: fruits[0] (zero-based indexing!)
• Access last: fruits[-1] (negative index)
• Get length: len(fruits)
• Loop: for fruit in fruits:
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 5: Functions
Intermediate
Coding Challenge
Your Task: Create Python functions to perform calculations. Functions are reusable blocks of code that make your programs modular, organized, and easier to maintain.

Detailed Requirements:
1. Create a function called "add_numbers" that takes two parameters and returns their sum:
def add_numbers(a, b): return a + b    • def keyword defines a function
   • Function name follows snake_case convention
   • Parameters go inside parentheses
   • Colon : is required after the parentheses
   • Function body must be indented (4 spaces)
   • return sends a value back to the caller

2. Create a function called "multiply_numbers" that multiplies two numbers:
def multiply_numbers(a, b): return a * b

3. Create a function called "greet" with a default parameter:
def greet(name="World"): return f"Hello, {name}!"    • Default parameters have a fallback value
   • If no argument is passed, the default is used
   • greet() returns "Hello, World!"
   • greet("Alice") returns "Hello, Alice!"

4. Call each function and print results:
print(add_numbers(5, 3)) # Output: 8 print(multiply_numbers(4, 7)) # Output: 28 print(greet()) # Output: Hello, World! print(greet("Python")) # Output: Hello, Python!

💡 Pro Tips:
• Functions without return implicitly return None
• Use docstrings to document functions: """This function adds two numbers."""
• *args allows variable number of arguments: def sum_all(*args):
• **kwargs allows keyword arguments: def func(**kwargs):
• Lambda functions for simple operations: square = lambda x: x ** 2

Expected Output:
Sum: 8 Product: 28 Hello, World! Hello, Python!

Requirements Checklist

Define a function "add_numbers" with two parameters
Define a function "multiply_numbers" with two parameters
Define a function "greet" with a default parameter
Use return statements in your functions
Call functions and print the results
Test greet() with and without arguments
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Define function: def function_name(param1, param2):
• Return value: return result
• Default parameter: def greet(name="World"):
• Call function: result = add_numbers(5, 3)
• F-string in return: return f"Hello, {name}!"
• Don't forget the colon after def name():
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 6: String Manipulation
Intermediate
Coding Challenge
Your Task: Master Python string operations - one of the most common tasks in programming. Strings are immutable sequences of characters with powerful built-in methods.

Detailed Requirements:
1. Create a string variable - text = " Hello, Python World! "
   • Strings can use single or double quotes
   • Notice the extra spaces at the start and end

2. Use strip() to remove whitespace - cleaned = text.strip()
   • strip() removes leading AND trailing whitespace
   • lstrip() removes only leading (left) whitespace
   • rstrip() removes only trailing (right) whitespace
   • Returns a NEW string (strings are immutable)

3. Convert case - Use upper() and lower():
   • text.upper() → "HELLO, PYTHON WORLD!"
   • text.lower() → "hello, python world!"
   • text.title() → "Hello, Python World!"
   • text.capitalize() → "Hello, python world!"

4. Use replace() to substitute text:
   • text.replace("Python", "Java") → "Hello, Java World!"
   • Can specify max replacements: text.replace("l", "L", 1)

5. Use split() to break into a list:
   • "a,b,c".split(",")["a", "b", "c"]
   • "Hello World".split()["Hello", "World"] (splits on whitespace)

6. Use find() to locate substrings:
   • text.find("Python") returns the starting index
   • Returns -1 if not found
   • text.index("Python") is similar but raises ValueError if not found

💡 Pro Tips:
• String slicing: text[0:5] gets first 5 characters
• Reverse string: text[::-1]
• Check content: text.startswith("Hello"), text.endswith("!")
• Check type: text.isalpha(), text.isdigit(), text.isalnum()
• Join list to string: ", ".join(["a", "b", "c"]) → "a, b, c"

Expected Output:
Original: ' Hello, Python World! ' Stripped: 'Hello, Python World!' Uppercase: 'HELLO, PYTHON WORLD!' Lowercase: 'hello, python world!' Replaced: 'Hello, Java World!' Split: ['Hello,', 'Python', 'World!'] Find 'Python': 7

Requirements Checklist

Create a string variable with leading/trailing spaces
Use strip() to remove whitespace
Use upper() and/or lower() for case conversion
Use replace() to substitute text
Use split() to break string into list
Use find() to locate a substring
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Remove spaces: text.strip()
• Uppercase: text.upper()
• Lowercase: text.lower()
• Replace: text.replace("old", "new")
• Split to list: text.split() or text.split(",")
• Find position: text.find("substring") returns index or -1
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below