0% found this document useful (0 votes)
2 views10 pages

Lab Exercises Python

The document outlines a series of lab exercises for a course on Programming for Data Analysis and Science Computing, focusing on Python fundamentals, control flow, loops, strings, collections, and functions. Each section includes specific exercises with requirements and expected outputs, covering topics such as variable types, arithmetic operations, conditional statements, loops, string manipulation, and function definitions. The exercises are designed to enhance practical programming skills through hands-on coding tasks.

Uploaded by

overvoid2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Lab Exercises Python

The document outlines a series of lab exercises for a course on Programming for Data Analysis and Science Computing, focusing on Python fundamentals, control flow, loops, strings, collections, and functions. Each section includes specific exercises with requirements and expected outputs, covering topics such as variable types, arithmetic operations, conditional statements, loops, string manipulation, and function definitions. The exercises are designed to enhance practical programming skills through hands-on coding tasks.

Uploaded by

overvoid2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lab Exercises Programming for Data Analysis and Science Computing

PROGRAMMING FOR DATA ANALYSIS


AND SCIENCE COMPUTING

LAB EXERCISES
Python Fundamentals, Control Flow, Data Types & Functions

Page 1
Lab Exercises Programming for Data Analysis and Science Computing

Part 1: Variables, Types & Operators


Exercise 1.1 — Personal Info Card
Requirements
Create variables to store your personal information:
• name (str), age (int), height in meters (float), is_student (bool)
• Print all values and their types using f-strings
• Calculate and print your birth year

Expected Output:
Name: Nguyen Van Hoang
Age: 20
Height: 1.75 m
Student: True
Birth year: 2005

Exercise 1.2 — Arithmetic Calculator


Requirements
Given two numbers a = 17 and b = 5, calculate and print:
• Sum (+), Difference (-), Product (*), Division (/)
• Floor division (//), Modulus (%), Power (**)
• Format output neatly with labels

Expected Output:
a = 17, b = 5
Sum: 17 + 5 = 22
Difference: 17 - 5 = 12
Product: 17 * 5 = 85
Division: 17 / 5 = 3.4
Floor div: 17 // 5 = 3
Modulus: 17 % 5 = 2
Power: 17 ** 5 = 1419857

Exercise 1.3 — Type Casting & Input


Requirements
Write a program that:
• Asks the user for a temperature in Celsius (use input())
• Converts it to Fahrenheit: F = C * 9/5 + 32
• Converts it to Kelvin: K = C + 273.15

Page 2
Lab Exercises Programming for Data Analysis and Science Computing

• Prints all three values rounded to 2 decimal places

Hint: Use float(input("...")) to read a decimal number


Use int(input("...")) to read a integer number

Sample Input
# Sample interaction:
# Enter temperature in Celsius: 37.5

Expected Output:
Celsius: 37.50
Fahrenheit: 99.50
Kelvin: 310.65

Part 2: Control Flow — Branching


Exercise 2.1 — Grade Classifier
Requirements
Write a program that:
• Asks the user for a score (0–100)
• Prints the letter grade using if/elif/else:
A: 90–100 | B: 80–89 | C: 70–79 | D: 60–69 | F: below 60
• Also prints 'PASS' if grade is D or above, 'FAIL' otherwise

Expected Output:
Enter your score: 85
Grade: B
Status: PASS

Exercise 2.2 — Leap Year Checker


Requirements
Write a program that checks if a year is a leap year.
Rules (use and, or, not):
• Divisible by 4 AND not divisible by 100 → leap year
• Divisible by 400 → also a leap year
Test with: 2000 (leap), 1900 (not leap), 2024 (leap), 2023 (not leap)

Test Cases

Page 3
Lab Exercises Programming for Data Analysis and Science Computing

# Test cases:
# is_leap(2000) -> True (divisible by 400)
# is_leap(1900) -> False (divisible by 100 but not 400)
# is_leap(2024) -> True (divisible by 4, not by 100)
# is_leap(2023) -> False (not divisible by 4)

Exercise 2.3 — BMI Calculator with Categories


Requirements
Ask the user for weight (kg) and height (m), then:
• Calculate BMI = weight / height²
• Classify using if/elif/else:
Underweight: BMI < 18.5 | Normal: 18.5–24.9
Overweight: 25–29.9 | Obese: BMI >= 30
• Print BMI rounded to 1 decimal and the category

Expected Output:
Enter weight (kg): 70
Enter height (m): 1.75
BMI: 22.9 -> Normal weight

Part 3: Loops — for & while


Exercise 3.1 — Multiplication Table
Requirements
Ask the user for a number n (1–12).
Print its multiplication table from 1 to 10 using a for loop.
Format the output neatly with alignment.

Expected Output:
Enter a number: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70

Exercise 3.2 — Sum & Count with Conditions


Requirements

Page 4
Lab Exercises Programming for Data Analysis and Science Computing

Given N positive numbers entered from keyboard (one by one):


• Count how many are divisible by both 2 AND 5
• Calculate the average of those numbers
• Stop input when user enters 0 or a negative number (use while)
Hint: A number divisible by both 2 and 5 is divisible by 10

Sample Input
# Sample interaction:
# Enter a number (0 to stop): 20
# Enter a number (0 to stop): 15
# Enter a number (0 to stop): 30
# Enter a number (0 to stop): 7
# Enter a number (0 to stop): 0

Expected Output:
Numbers divisible by both 2 and 5: 2 (which are: 20, 30)
Average of those numbers: 25.0

Exercise 3.3 — Fibonacci Sequence


Requirements
Print the first N numbers of the Fibonacci sequence.
Fibonacci: each number is the sum of the two preceding ones.
Sequence starts: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Ask user for N, then print the sequence using a while or for loop.

Expected Output:
Enter N: 10
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Part 4: Strings — Slicing & Methods


Exercise 4.1 — String Explorer
Requirements
Given: s = "Hello, World!"
Print the following using indexing and slicing:
• The first character
• The last character
• Characters from index 7 to 11 (inclusive)
• The string reversed (Hint: s[::-1])

Page 5
Lab Exercises Programming for Data Analysis and Science Computing

• Every other character (Hint: s[::2])


• The length of the string

Exercise 4.2 — Name Processor


Requirements
Write a program that:
• Asks user to enter a full name (e.g., 'nguyen van hoang')
• Removes leading/trailing whitespace (.strip())
• Converts to title case (.title())
• Separates into family name, middle name(s), and given name
• Prints the email format: [Link]@[Link]
Hint: Use .split() and indexing on the resulting list

Sample Input
# Sample interaction:
# Enter full name: nguyen van hoang

Expected Output:
Full name: Nguyen Van Hoang
Family name: Nguyen
Middle name: Van
Given name: Hoang
Email: [Link]@[Link]

Exercise 4.3 — Text Statistics


Requirements
Given: text = "Python is amazing. Python is powerful. I love Python programming."
Calculate and print:
• Number of characters (including spaces)
• Number of words
• Number of sentences (count '.')
• Number of times 'Python' appears (case-sensitive)
• The text with 'Python' replaced by 'Java'
• A list of all unique words (lowercase, no punctuation)

Page 6
Lab Exercises Programming for Data Analysis and Science Computing

Part 5: Collections — List, Dict, Tuple


Exercise 5.1 — List Operations
Requirements
Given: numbers = [12, 45, 7, 23, 89, 34, 56, 3, 67, 41]
Without using built-in min/max/sum/sorted, write code to find:
• The largest number
• The smallest number
• The sum of all numbers
• The average
Then use list comprehension to create a new list containing
only the even numbers from the original list.

Expected Output:
Max: 89
Min: 3
Sum: 377
Average: 37.7
Even numbers: [12, 34, 56]

Exercise 5.2 — Student Dictionary


Requirements
Create a list of 5 student dictionaries, each with keys:
"name" (str), "id" (str), "math" (float), "physics" (float), "chemistry" (float)
Then write code to:
• Add an 'average' key to each student (mean of 3 subjects)
• Find the student with the highest average
• Print a formatted report of all students sorted by average (descending)
Hint: Use sorted() with key=lambda

Expected Output:
====== CLASS REPORT ======
Rank Name Avg
1 Nguyen An 9.07
2 Tran Binh 8.50
3 Le Chi 7.83
...

Page 7
Lab Exercises Programming for Data Analysis and Science Computing

Exercise 5.3 — Word Frequency Counter


Requirements
Given: sentence = "the cat sat on the mat the cat ate the rat"
Use a dictionary to count the frequency of each word.
• Print each word and its count, sorted by frequency (highest first)
• Use dict comprehension or a loop
• Find the most common word and the least common word
Bonus: Try using only a dict comprehension with .count()

Expected Output:
Word frequencies:
the : 4
cat : 2
sat : 1
on : 1
mat : 1
ate : 1
rat : 1
Most common: 'the' (4 times)

Part 6: Functions
Exercise 6.1 — Basic Functions
Requirements
Write the following functions:
• find_max(a, b, c): returns the largest of 3 numbers (no built-in max)
• is_prime(n): returns True if n is a prime number, False otherwise
• factorial(n): returns n! using a loop (no recursion needed)
Test each function with at least 3 different inputs and print results.

Test Cases
# Test cases:
print(find_max(3, 7, 5)) # Expected: 7
print(find_max(-1, -5, -3)) # Expected: -1
print(is_prime(7)) # Expected: True
print(is_prime(12)) # Expected: False
print(is_prime(1)) # Expected: False
print(factorial(5)) # Expected: 120
print(factorial(0)) # Expected: 1

Page 8
Lab Exercises Programming for Data Analysis and Science Computing

Exercise 6.2 — Default Parameters & Keyword Args


Requirements
Write a function calculate_salary(hours, rate=50000, overtime_multiplier=1.5):
• Base pay: hours * rate (for first 8 hours)
• Overtime: extra hours * rate * overtime_multiplier
• Returns total salary
Test with different combinations of positional and keyword arguments.

Test Cases
# Test cases:
print(calculate_salary(8)) # 400,000
print(calculate_salary(10)) # 550,000
print(calculate_salary(10, rate=60000)) # 660,000
print(calculate_salary(12, overtime_multiplier=2.0))
# 800,000

Exercise 6.3 — Scope & Lambda


Requirements
Part A — Scope: Predict the output WITHOUT running the code first,
then verify by running it:

Predict the output


x = 10

def func_a():
x = 20
print('A:', x)

def func_b():
print('B:', x)

func_a()
func_b()
print('Global:', x)

Part B — Lambda
Use lambda with sorted() to sort the following data:
1. students = [("An", 8.5), ("Binh", 7.0), ("Chi", 9.2), ("Dung", 6.8)]
Sort by score ascending, then by score descending
2. words = ["banana", "apple", "cherry", "date"]
Sort by word length (shortest first)

Page 9
Lab Exercises Programming for Data Analysis and Science Computing

Exercise 6.4 — Scale Function


Requirements
Write a function scale(val, src, dst=(-1, 1)) that maps a value
from source range src to destination range dst.
Formula: (val - src[0]) / (src[1] - src[0]) * (dst[1] - dst[0]) + dst[0]

Test Cases
# Test cases:
print(scale(49, (-100, 100), (-50, 50))) # Expected: 24.5
print(scale(49, (-100, 100))) # Expected: 0.49
print(scale(0, (0, 100), (0, 1))) # Expected: 0.0
print(scale(50, (0, 100), (0, 1))) # Expected: 0.5
print(scale(100, (0, 100), (0, 1))) # Expected: 1.0

Page 10

You might also like