Python Programming

A Hands-On Lab Tutorial

EGN 1273 | Created by Dr. Bashar Alrjoub

February 17, 2025

Welcome to this comprehensive, hands-on introductory Python lab tutorial. This guide is designed to help you learn Python programming through practical examples and exercises.

Table of Contents

Review

In this guide, you will:

  • Write your first Python programs
  • Learn basic programming concepts
  • Explore Python's core data structures
  • Work on practical exercises

Setting Up Your Environment

What You Need:

  • Python (version 3.x) - Download from python.org
  • A text editor or IDE (VS Code recommended)
  • Terminal/Command Prompt access

Check Your Installation:

python --version

Your First Python Program

Let's start with some simple print statements:

1. Simple Print Statement

print("Hello, World!")
print("Welcome to Python!")
print("Programming is fun!")

Output:

Hello, World!
Welcome to Python!
Programming is fun!

2. Printing Numbers

print(42)
print(3.14)
print("The number is:", 42)
print("Pi is approximately:", 3.14)

Output:

42
3.14
The number is: 42
Pi is approximately: 3.14

3. Printing Multiple Items

name = "Alice"
age = 20
print("Name:", name, "Age:", age)
print(f"My name is {name} and I am {age} years old")  # f-string
print("My name is {} and I am {} years old".format(name, age))  # format method

Output:

Name: Alice Age: 20
My name is Alice and I am 20 years old
My name is Alice and I am 20 years old

Variables and Data Types

Let's explore different ways to use variables and understand data types:

1. Simple Variables

# String variables
first_name = "John"
last_name = "Doe"

# Number variables
age = 25
height = 5.9

# Boolean variable
is_student = True

# Printing all variables
print("Full name:", first_name, last_name)
print("Age:", age)
print("Height:", height, "feet")
print("Is student?", is_student)

Output:

Full name: John Doe
Age: 25
Height: 5.9 feet
Is student? True

Practice Questions

  1. Declare a variable named city and assign it the value "New York". Print the variable.

  2. Create two variables, x and y, and assign them the values 10 and 5 respectively. Print the sum of x and y.

  3. Declare a boolean variable called is_raining and set it to False. Print a message based on the value of is_raining, such as "Remember your umbrella!" if it's True, or "Enjoy the sunny day!" if it's False.

2. Working with Variables

# String concatenation
full_name = first_name + " " + last_name
print("Full name:", full_name)

# Number operations
birth_year =  - age
print("Birth year:", birth_year)

# Converting between types
age_str = str(age)
print("Age as string:", age_str)
print("Type of age_str:", type(age_str))

# Multiple assignments
x, y, z = 1, 2, 3
print("x:", x, "y:", y, "z:", z)

Output:

Full name: John Doe
Birth year: 1999
Age as string: 25
Type of age_str: <class 'str'>
x: 1 y: 2 z: 3

Practice Questions

  1. Using the variables first_name and last_name from the previous example, create a new variable called initials that holds the first letter of the first name and the first letter of the last name, separated by a dot. For example, if first_name is "John" and last_name is "Doe", initials should be "J.D". Print the initials variable.

  2. Declare two variables, num1 and num2, and assign them the values 15 and 4 respectively. Calculate the integer division and modulo of num1 and num2, and print the results in the format: "15 // 4 = 3 and 15 % 4 = 3".

  3. Create a variable named temperature and assign it a float value representing a temperature in Fahrenheit. Convert the temperature to Celsius using the formula: celsius = (fahrenheit - 32) * 5/9. Print the original Fahrenheit temperature and the converted Celsius temperature, rounded to 2 decimal places.

3. Type Conversion Examples

# String to number
text_number = "42"
number = int(text_number)
print("Converted number:", number)

# Float to integer
price = 19.99
whole_dollars = int(price)
print("Price:", price)
print("Whole dollars:", whole_dollars)

# Number to string
count = 100
count_str = str(count)
print("Count as string:", count_str)
print("Is it a string?", isinstance(count_str, str))

Output:

Converted number: 42
Price: 19.99
Whole dollars: 19
Count as string: 100
Is it a string? True

4. Advanced String Operations

# String methods and operations
text = "Python Programming"
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())
print("Length:", len(text))
print("Contains 'gram'?", "gram" in text)
print("Replace:", text.replace("Python", "Basic"))
print("Split words:", text.split())
print("First 6 chars:", text[:6])
print("Last 6 chars:", text[-6:])

Output:

Uppercase: PYTHON PROGRAMMING
Lowercase: python programming
Length: 18
Contains 'gram'? True
Replace: Basic Programming
Split words: ['Python', 'Programming']
First 6 chars: Python
Last 6 chars: mming

5. Working with Multiple Types

# Combining different types
items = 3
price = 19.99
product = "Widget"
in_stock = True

# Format string with multiple types
summary = f"""
Product Details:
---------------
Name: {product}
Price: {price:.2f}
Quantity: {items}
Available: {'Yes' if in_stock else 'No'}
Total Value: {items * price:.2f}
"""

print(summary)

# Type checking
print("\nType Information:")
print(f"items is {'{type(items)}'}")
print(f"price is {'{type(price)}'}")
print(f"product is {'{type(product)}'}")
print(f"in_stock is {'{type(in_stock)}'}")

Output:

Product Details:
---------------
Name: Widget
Price: $19.99
Quantity: 3
Available: Yes
Total Value: $59.97

Type Information:
items is <class 'int'>
price is <class 'float'>
product is <class 'str'>
in_stock is <class 'bool'>

This advanced example demonstrates:

  • Working with multiple variable types together
  • Using f-strings for complex formatting
  • Conditional expressions in string formatting
  • Type checking and type information
  • Multi-line string formatting

Basic Operations and Expressions

Python supports various arithmetic operations for calculations.

operations.py

a = 10
b = 3

print("Addition:", a + b)       # 13
print("Subtraction:", a - b)    # 7
print("Multiplication:", a * b) # 30
print("Division:", a / b)       # 3.333...
print("Modulus:", a % b)        # 1
print("Exponent:", a ** b)      # 1000

Control Structures: Conditionals

Conditional statements let your program make decisions.

conditionals.py

number = 15

if number > 10:
    print("Number is greater than 10")
elif number == 10:
    print("Number is exactly 10")
else:
    print("Number is less than 10")

Control Structures: Loops

Python provides two main types of loops:

for_loop.py

# For Loop
for i in range(5):
    print(f"Count: {i}")

# While Loop
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1

Functions

Functions are one of the fundamental building blocks in Python programming. They allow you to encapsulate a set of instructions into a reusable unit, making your code more organized, maintainable, and efficient. Think of functions as small, specialized machines in a factory - each one performs a specific task and can be used whenever that task needs to be done.

In Python, functions are defined using the def keyword, followed by the function name and parentheses containing any parameters the function needs. Functions can accept inputs (parameters), process them, and return results. They can also include documentation strings (docstrings) that explain what the function does, making it easier for others to understand and use your code.

Basic Function Structure

Let's look at how to create and use functions, starting with simple examples and building up to more complex ones:

1. Basic Function Definition

def greet(name):
    """Return a personalized greeting message.
    
    Args:
        name (str): The name of the person to greet
    Returns:
        str: A greeting message
    """
    return f"Hello, {name}!"

# Using the function
print(greet("Alice"))
print(greet("Bob"))

Output:

Hello, Alice!
Hello, Bob!

In this example:

  • The function is named greet and takes one parameter (name)
  • It includes a docstring explaining its purpose and parameters
  • It uses an f-string to create a personalized message
  • The function is called twice with different arguments

2. Functions with Multiple Parameters

def calculate_rectangle_area(length, width):
    """Calculate the area of a rectangle.
    
    Args:
        length (float): The length of the rectangle
        width (float): The width of the rectangle
    Returns:
        float: The area of the rectangle
    """
    area = length * width
    return area

# Using the function with different values
print("Area 1:", calculate_rectangle_area(5, 3))
print("Area 2:", calculate_rectangle_area(2.5, 4))
print("Area 3:", calculate_rectangle_area(10, 10))

Output:

Area 1: 15
Area 2: 10.0
Area 3: 100

This example demonstrates:

  • A function that takes multiple parameters
  • Performing calculations with the parameters
  • Returning numerical results
  • Using the function with different types of numbers

3. Functions with Default Parameters

def create_profile(name, age, city="Unknown", occupation=None):
    """Create a user profile with optional parameters.
    
    Args:
        name (str): User's name
        age (int): User's age
        city (str, optional): User's city. Defaults to "Unknown"
        occupation (str, optional): User's occupation. Defaults to None
    Returns:
        dict: A dictionary containing the user's profile
    """
    profile = {
        "name": name,
        "age": age,
        "city": city,
        "occupation": occupation
    }
    return profile

# Using the function with different combinations
print("Profile 1:", create_profile("Alice", 25))
print("Profile 2:", create_profile("Bob", 30, "New York"))
print("Profile 3:", create_profile("Charlie", 35, "London", "Engineer"))

Output:

Profile 1: {'name': 'Alice', 'age': 25, 'city': 'Unknown', 'occupation': None}
Profile 2: {'name': 'Bob', 'age': 30, 'city': 'New York', 'occupation': None}
Profile 3: {'name': 'Charlie', 'age': 35, 'city': 'London', 'occupation': 'Engineer'}

This advanced example shows:

  • Using default parameter values
  • Optional parameters in functions
  • Creating and returning complex data structures
  • Different ways to call the same function

Best Practices

  • Give your functions clear, descriptive names that indicate what they do
  • Include docstrings to document your functions
  • Keep functions focused on a single task (Single Responsibility Principle)
  • Use meaningful parameter names
  • Consider using type hints for better code clarity

Data Structures

Lists

fruits = ["apple", "banana", "orange"]
fruits.append("grape")
print(fruits[0])  # First item
print(fruits[-1]) # Last item

Dictionaries

person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}
print(person["name"])

Modules and Importing

Python modules allow you to organize and reuse code:

math_operations.py

import math

print(math.sqrt(16))  # Square root
print(math.pi)        # Pi constant

File I/O Basics

Reading and writing files in Python:

# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, File!")

# Reading from a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

Project: Text-Based Calculator

Let's build a simple calculator:

def calculator():
    print("Simple Calculator")
    print("1: Add")
    print("2: Subtract")
    
    choice = input("Choose operation (1/2): ")
    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))
    
    if choice == "1":
        print(f"Result: {num1 + num2}")
    elif choice == "2":
        print(f"Result: {num1 - num2}")

calculator()

Exercises and Lab Challenges

Challenge 1:

Write a program that asks the user for their name and age, then prints a message telling them the year they will turn 100.

Challenge 2:

Modify the calculator project to include an option for exponentiation.