Python Programming Fundamentals and Practical Lab Exercises

Posted by Anonymous and classified in Computers

Written on in English with a size of 6.88 KB

Lecture 1: Programming Logic and Structures

Pseudocode

  • Abbreviated plain English version of actual computer code
  • Symbols used in flowcharts replaced by English-like statements
  • Allows the programmer to focus on steps required to solve a problem

Hierarchy Chart

  • Shows the overall program structure
  • Depicts the organization of the program, omitting specific processing logic
  • Describes what each part, or module, of the program does
  • Each module is subdivided into a succession of submodules

Three Basic Structures

  • Sequence structure
  • Decision structure
  • Repetition/loop structure

Lecture 2: Python Functions and Error Handling

import math

  • abs(-23): 23
  • math.ceil(3.0001): Rounds up
  • round(4.5): Rounds to nearest
  • math.floor(3.9999): Rounds down
  • import random
  • random.randint(1, 100)
  • type(6): Integer
  • int(2.7): 2
  • float(2): 2.0

num = float(input("Input a number: "))

num += 1 is the same as num = num + 1

Three Types of Errors

  • Syntax Errors: Grammatical and punctuation errors. Example: Extra parentheses ) or wrong syntax like ;.
  • Runtime Errors: Errors discovered while the program is running, also called exceptions. Example: When invalid data is input or a file cannot be accessed.
  • Logic Errors: Occur when a program does not perform the way it was intended. Example: average = firstNum + secondNum / 2 should be average = (firstNum + secondNum) / 2.

Lecture 3: String Manipulation and Formatting

school = "CityU"
school[0]: 'C'

str1 = "spam & eggs"
str1[2:7]: 'am & '
str1.find('p'): 1
str1.rfind('gs'): 9
str1.find('huh'): -1

Slicing: str1[2:], str1[:8], str1[:]

Negative Index = Positive Index – Length

len(str1): 11

ref = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ref[::2]: 'ACEGIKMOQSUWY'
ref[::-1]: Reverses the string

String Functions and Methods (str1 = "Python")

  • len(str1): 6
  • str1.upper(): "PYTHON"
  • str1.lower(): "python"
  • str1.count('th'): 1
  • "coDE".capitalize(): "Code"
  • "beN hur".title(): "Ben Hur"
  • "ab ".rstrip(): "ab"

print("a", "b", "c", sep="!!!"): a!!!b!!!c!!!

print("a\tb".expandtabs(7)): a      b

print("a\nb"): Prints 'a' and 'b' on separate lines.

F-String Example:
school = "CityU"
year = 1984
print(f"{school} was founded in {year}.")

Lecture 4: Lists, Tuples, and Data Structures

List: [32, 32.0, "32", "TaiMan"]
Tuple: (32, 32.0, "32", "TaiMan")

lst = ["CityU", 1984, 83, "Tat Chee Ave"]

  • lst.index(83): 2
  • lst[3:2]: When the left index is greater than the right, it returns []
  • lst.reverse()
  • lst.append("Kowloon Tong"): Inserts object at the end of the list
  • lst.extend(["Kowloon", "Hong Kong"]): Inserts a new list
  • del lst[1], lst.remove(83), lst.clear()
  • max(lst), min(lst), sum(lst), sorted(lst), lst.sort()

"CityU was founded in 1984.".split(): ['CityU', 'was', 'founded', 'in', '1984.']

" ".join(['CityU', 'was', 'founded', 'in', '1984.']): 'CityU was founded in 1984.'

Tuples: Can be defined without parentheses (packing). list("CityU"): ['C', 'i', 't', 'y', 'U']

Similarities and Differences

  • Similarities: Items accessed by indices; support slicing, concatenation, and repetition. Python allows out-of-bound indices with slicing but not for individual items.
  • Differences: Tuples cannot be modified in place (no append, extend, or insert). Items cannot be deleted, sorted, or altered directly.

Lab 2: Financial Calculations

Future Value

FV = PV * (1 + r) ** n
r = float(input("Enter the annual interest rate (without the %): "))
futureValue = round(1000 * (1 + r) ** 5, 2)

Present Value

presentValue = round(100000 / (1 + r) ** 5, 2)

Future Value of an Ordinary Annuity

futureValue = round(1000 * ((1 + r) ** n - 1) / r)
print(f"With a monthly contribution of $1000, your MPF will be worth ${futureValue} after {n} months.")

Lab 3: Randomization and Encryption

Generate a Random Letter

import random
ref = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
num = random.randint(0, 25)
letter = ref[num]

Find Alphabet Position

letter = input("Pick one letter from A-Z: ").upper()
pos = ref.find(letter) + 1

Random Password Generation

l1 = random.choice(ref)
n1 = random.randint(0, 9)

Lab 4: List and String Processing

month = ["January", "February", "March"]
mon = [month[0][:3], month[1][:3], month[2][:3]]

Nested Lists:
lst[1][1][1][0] = "CityU"

Lab 5: Conditional Logic and Tax Calculation

Grade Checker:
if score >= 90: grade = 'A'
elif score >= 80: grade = 'B'

Salary Tax Calculation:
Calculates tax based on marital status, MPF contributions, and progressive tax brackets (2%, 6%, 10%, 14%, 17%).

Lab 6 & 7: Advanced Logic and Loops

Largest of Three Numbers

Uses if-elif-else to compare three user-inputted floats and determine the maximum value.

Present Value Loop

for t in range(1, n+1): pv += 1000 / ((1 + r) ** t)

Leap Year Check

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

Related entries: