Python Programming Solutions

Practical code examples and solutions for all Python concepts

Code Examples Solutions Practice

1. Introduction to Python, Basic Syntax and Structure

Hello World Program
hello.py
# Simple Hello World program
print("Hello, World!")

The most basic Python program that outputs "Hello, World!" to the console.

Basic Program Structure
structure.py
# Python program structure example

# Import statements
import math

# Global variable
PI = 3.14159

# Function definition
def calculate_area(radius):
    """Calculate area of a circle."""
    return PI * radius ** 2

# Main program
if __name__ == "__main__":
    # Variable declaration
    radius = 5
    
    # Function call and output
    area = calculate_area(radius)
    print(f"Area of circle with radius {radius} is: {area:.2f}")
    
    # Using imported module
    print(f"Square root of 16 is: {math.sqrt(16)}")

Shows the basic structure of a Python program with comments explaining each part.

2. Variables and Data Types, Constants and Literals

Data Types Example
datatypes.py
# Python data types examples

# Numeric types
age = 25                    # Integer
price = 19.99              # Float
complex_num = 3 + 4j       # Complex number

# Sequence types
name = "Alice"             # String
numbers_list = [1, 2, 3]   # List
numbers_tuple = (1, 2, 3)  # Tuple

# Mapping type
person = {"name": "Alice", "age": 25}  # Dictionary

# Set types
unique_numbers = {1, 2, 3, 3}  # Set (duplicates removed)

# Boolean type
is_valid = True             # Boolean

# None type
result = None               # NoneType

# Output values and types
print("Type of age:", type(age))
print("Type of price:", type(price))
print("Type of name:", type(name))
print("Type of numbers_list:", type(numbers_list))
print("Type of person:", type(person))
print("Type of is_valid:", type(is_valid))
print("Type of result:", type(result))

# Set automatically removes duplicates
print("Unique numbers set:", unique_numbers)

Demonstrates different data types available in Python.

Constants and Literals
constants.py
# Constants and literals in Python

# Convention: Use uppercase for constants
PI = 3.14159
MAX_SIZE = 100

# Literals examples
decimal = 100              # Decimal literal
binary = 0b1100100        # Binary literal (100 in decimal)
octal = 0o144             # Octal literal (100 in decimal)
hexadecimal = 0x64        # Hexadecimal literal (100 in decimal)

# Float literals
float1 = 3.14
float2 = 3.14e-2          # Scientific notation (0.0314)

# String literals
single_quoted = 'Hello'
double_quoted = "World"
triple_quoted = '''Multi-line
string'''

# Boolean literals
true_value = True
false_value = False

# Collection literals
list_literal = [1, 2, 3]
tuple_literal = (1, 2, 3)
dict_literal = {"key": "value"}
set_literal = {1, 2, 3}

print("PI:", PI)
print("MAX_SIZE:", MAX_SIZE)
print("Binary 0b1100100:", binary)
print("Hexadecimal 0x64:", hexadecimal)
print("Scientific notation 3.14e-2:", float2)
print("Multi-line string:", triple_quoted)

Shows how to define constants and use different types of literals in Python.

3. Input and Output (I/O), Operators

Basic I/O Operations
io.py
# Basic input and output operations in Python

# Getting input from user
name = input("Enter your name: ")
age = int(input("Enter your age: "))
height = float(input("Enter your height (in meters): "))

# Displaying output
print("\n--- User Information ---")
print("Name:", name)
print("Age:", age)
print("Height:", height, "meters")

# Formatted output
print(f"\nFormatted: {name} is {age} years old and {height:.2f}m tall")

# Multiple values output
print("Name:", name, "Age:", age, "Height:", height)

# Output with separator
print(name, age, height, sep=" | ")

# Output to file
with open("output.txt", "w") as file:
    file.write(f"Name: {name}\nAge: {age}\nHeight: {height}\n")

print("\nData also written to output.txt file")

Demonstrates basic input and output operations in Python.

Operators in Python
operators.py
# Operators in Python

a = 10
b = 3

# Arithmetic operators
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)      # True division
print("a // b =", a // b)    # Floor division
print("a % b =", a % b)      # Modulus
print("a ** b =", a ** b)    # Exponentiation

# Assignment operators
c = a
c += b
print("c += b:", c)
c -= b
print("c -= b:", c)

# Comparison operators
print("a == b:", a == b)
print("a != b:", a != b)
print("a > b:", a > b)
print("a <= b:", a <= b)

# Logical operators
x = True
y = False
print("x and y:", x and y)
print("x or y:", x or y)
print("not x:", not x)

# Identity operators
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print("list1 is list2:", list1 is list2)  # False (different objects)
print("list1 is list3:", list1 is list3)  # True (same object)
print("list1 == list2:", list1 == list2)  # True (same content)

# Membership operators
numbers = [1, 2, 3, 4, 5]
print("3 in numbers:", 3 in numbers)
print("6 not in numbers:", 6 not in numbers)

# Bitwise operators
print("a & b (bitwise AND):", a & b)
print("a | b (bitwise OR):", a | b)
print("a ^ b (bitwise XOR):", a ^ b)
print("~a (bitwise NOT):", ~a)
print("a << 1 (left shift):", a << 1)
print("a >> 1 (right shift):", a >> 1)

Shows different types of operators available in Python.

4. Conditional Control Statements

If-Else Statements
ifelse.py
# If-else statements in Python

number = int(input("Enter a number: "))

# Simple if statement
if number > 0:
    print("The number is positive.")

# If-else statement
if number % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

# If-elif-else ladder
if number > 0:
    print("Positive number")
elif number < 0:
    print("Negative number")
else:
    print("Zero")

# Nested if statements
if number >= 0:
    if number == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")

# Conditional expressions (ternary operator)
result = "Even" if number % 2 == 0 else "Odd"
print(f"The number is {result}")

# Multiple conditions
if number > 0 and number % 2 == 0:
    print("Positive even number")
elif number > 0 and number % 2 != 0:
    print("Positive odd number")
elif number < 0:
    print("Negative number")
else:
    print("Zero")

Demonstrates different forms of if-else conditional statements.

Match Case Statement (Python 3.10+)
match_case.py
# Match case statement (Python 3.10+)

def process_grade(grade):
    """Process grade using match case."""
    grade = grade.upper()
    
    match grade:
        case "A":
            return "Excellent!"
        case "B":
            return "Well done!"
        case "C":
            return "Good job!"
        case "D":
            return "You passed, but could do better."
        case "F":
            return "Sorry, you failed."
        case _:
            return "Invalid grade entered."

# Get input from user
grade = input("Enter your grade (A, B, C, D, F): ")
result = process_grade(grade)
print(result)

# More complex pattern matching
def describe_value(value):
    """Describe value using pattern matching."""
    match value:
        case 0:
            return "Zero"
        case 1 | 2 | 3:
            return "Small number"
        case n if n > 3 and n < 10:
            return "Medium number"
        case n if n >= 10:
            return "Large number"
        case _:
            return "Not a number or negative"

# Test the function
print(describe_value(0))     # Zero
print(describe_value(2))     # Small number
print(describe_value(5))     # Medium number
print(describe_value(15))    # Large number

# Pattern matching with lists
def process_list(lst):
    """Process list using pattern matching."""
    match lst:
        case []:
            return "Empty list"
        case [x]:
            return f"Single element: {x}"
        case [x, y]:
            return f"Two elements: {x} and {y}"
        case [x, y, *rest]:
            return f"First two: {x}, {y}, rest: {rest}"
        case _:
            return "Not a list"

print(process_list([]))              # Empty list
print(process_list([1]))             # Single element: 1
print(process_list([1, 2]))          # Two elements: 1 and 2
print(process_list([1, 2, 3, 4]))    # First two: 1, 2, rest: [3, 4]

Shows how to use match case statements for pattern matching (Python 3.10+).

5. Loops

For Loop
forloop.py
# For loops in Python

# Basic for loop with range
print("Counting from 1 to 5:")
for i in range(1, 6):
    print(i, end=" ")
print("\n")

# For loop with list
fruits = ["apple", "banana", "cherry"]
print("Fruits:")
for fruit in fruits:
    print(fruit, end=" ")
print("\n")

# For loop with index and value
print("Fruits with index:")
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Nested for loop (multiplication table)
print("\nMultiplication Table (1-5):")
for i in range(1, 6):
    for j in range(1, 6):
        print(i * j, end="\t")
    print()

# For loop with dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
print("\nPerson details:")
for key, value in person.items():
    print(f"{key}: {value}")

# For loop with string
message = "Python"
print("\nCharacters in 'Python':")
for char in message:
    print(char, end=" ")
print()

# For loop with else clause
print("\nSearching for number 6:")
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 6:
        print("Number 6 found!")
        break
else:
    print("Number 6 not found in the list.")

# Using zip to iterate over multiple sequences
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
print("\nPeople and their ages:")
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

Demonstrates different uses of for loops in Python.

While and Do-While Loops
whileloop.py
# While loops in Python

# While loop example
print("While loop - counting from 1 to 5:")
i = 1
while i <= 5:
    print(i, end=" ")
    i += 1
print("\n")

# Python doesn't have a built-in do-while loop, but we can simulate it
print("Simulated do-while loop - counting from 1 to 5:")
j = 1
while True:
    print(j, end=" ")
    j += 1
    if j > 5:
        break
print("\n")

# Practical example: Sum of numbers until 0 is entered
total = 0
print("Enter numbers to sum (enter 0 to stop):")

while True:
    try:
        number = float(input("Enter a number: "))
        if number == 0:
            break
        total += number
    except ValueError:
        print("Please enter a valid number!")

print(f"Sum of entered numbers: {total}")

# While loop with else clause
print("\nSearching for number 6:")
numbers = [1, 2, 3, 4, 5]
index = 0
while index < len(numbers):
    if numbers[index] == 6:
        print("Number 6 found!")
        break
    index += 1
else:
    print("Number 6 not found in the list.")

# Using while loop for input validation
while True:
    age_input = input("\nPlease enter your age (positive number): ")
    if age_input.isdigit() and int(age_input) > 0:
        age = int(age_input)
        print(f"Your age is: {age}")
        break
    else:
        print("Invalid input. Please enter a positive number.")

# While loop with condition
print("\nCountdown from 5:")
count = 5
while count > 0:
    print(count, end=" ")
    count -= 1
print("Blastoff!")

Shows how to use while loops and simulate do-while loops in Python.

6. Lists, Tuples, and Dictionaries

Lists and List Operations
lists.py
# Lists and list operations in Python

# Creating lists
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]

# Accessing elements
print("First fruit:", fruits[0])
print("Last number:", numbers[-1])

# Slicing
print("First three numbers:", numbers[:3])
print("Last two fruits:", fruits[-2:])

# List operations
numbers.append(6)          # Add element
numbers.insert(2, 99)      # Insert at position
numbers.remove(99)         # Remove element
popped = numbers.pop()     # Remove and return last element
print("After operations:", numbers)

# List comprehension
squares = [x**2 for x in range(1, 6)]
print("Squares:", squares)

# Sorting
numbers.sort()
print("Sorted:", numbers)
numbers.sort(reverse=True)
print("Reverse sorted:", numbers)

Demonstrates list operations and list comprehensions in Python.

Tuples and Dictionaries
tuples_dicts.py
# Tuples and dictionaries in Python

# Tuples (immutable)
coordinates = (10, 20)
print("Coordinates:", coordinates)
print("X coordinate:", coordinates[0])

# Dictionary (key-value pairs)
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Accessing values
print("Name:", person["name"])
print("Age:", person.get("age"))

# Adding/updating
person["email"] = "alice@example.com"
person["age"] = 26

# Dictionary methods
print("Keys:", person.keys())
print("Values:", person.values())
print("Items:", person.items())

# Dictionary comprehension
squares = {x: x**2 for x in range(1, 6)}
print("Squares dictionary:", squares)

Shows how to work with tuples and dictionaries in Python.

More Content Coming Soon!

We're continuously adding more Python programming solutions. Check back soon for complete coverage of all Python concepts including functions, classes, file handling, and more!