Browsed by
Category: Python

Learning Python and PyQGIS

Python Course: Files

Python Course: Files

In this project, I worked with files using Python. This was part of the learning module on files, which is for the Python course I am taking.

import csv

#Retrieve usernames from a csv file
compromised_users = []
with open('passwords.csv') as password_file:
  password_csv = csv.DictReader(password_file, delimiter=',')
  for row in password_csv:
    password_row = row
    compromised_users.append(password_row['Username'])

#write usernames to a new file
with open('compromised_users.txt', 'w') as compromised_user_file:
  for user in compromised_users:
    compromised_user_file.write(user + "\n")

import json

#create a JSON file to notify the boss
with open('boss_message.json', 'w') as boss_message:
  boss_message_dict = {"recipient": "The Boss", "message": "Mission Success"}
  json.dump(boss_message_dict, boss_message)

#remove the original passwords file and replace with rival hacker's signature.
with open("new_passwords.csv", 'w') as new_passwords_obj:
  slash_null_sig = """ _  _     ___   __  ____             
/ )( \   / __) /  \(_  _)            
) \/ (  ( (_ \(  O ) )(              
\____/   \___/ \__/ (__)             
 _  _   __    ___  __ _  ____  ____  
/ )( \ / _\  / __)(  / )(  __)(    \ 
) __ (/    \( (__  )  (  ) _)  ) D ( 
\_)(_/\_/\_/ \___)(__\_)(____)(____/ 
        ____  __     __   ____  _  _ 
 ___   / ___)(  )   / _\ / ___)/ )( \
(___)  \___ \/ (_/\/    \\___ \) __ (
       (____/\____/\_/\_/(____/\_)(_/
 __ _  _  _  __    __                
(  ( \/ )( \(  )  (  )               
/    /) \/ (/ (_/\/ (_/\             
\_)__)\____/\____/\____/
"""
  new_passwords_obj.write(slash_null_sig)
Python Course: Dictionaries

Python Course: Dictionaries

In this project, I wrote a script to keep track of point totals for people playing a game of scrabble. This project was to practice what I learned about dictionaries in Python.

letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]

#combined into a dictionary that maps a letter to its point value.
letter_to_points = {letters:points for letters, points in zip(letters, points)}
letter_to_points[" "] = 0 #for blank tiles

#a function that takes a word, loops through its letters, returns the points for that word.
def score_word(word):
  point_total = 0
  for i in word:
    point_total += letter_to_points.get(i, 0)
  return point_total

#testing the score_word function
brownie_points = score_word("BROWNIE")
#print(brownie_points)

#Each player's words
player_to_words = {"player1": ["BLUE", "TENNIS", "EXIT"], "wordNerd": ["EARTH", "EYES", "MACHINE"], "Lexi Con": ["ERASER", "BELLY", "HUSKY"], "Prof Reader": ["ZAP", "COMA", "PERIOD"]}

#Loops through the words of each player and adds up each player's points
player_to_points = {} #the score
for player, words in player_to_words.items():
  player_points = 0
  for word in words:
    player_points += score_word(word)
  player_to_points[player] = player_points
print(player_to_points)

#a function that would take in a player and a word, and add that word to the list of words they’ve played
def play_word(player, word):
  player_to_words[player].append(word)
Python course: modules

Python course: modules

In this project, I created a Python script which generates a personalized message for a time traveler. The message will read, Today’s date is: 2025-02-02 The current time is: 04:04:19.913236 Pack your bags! You’re traveling to Tokyo in the year 1343. The cost of this trip will be $2387.00.

In this project, I used the decimal, random and datetime modules in Python.

import datetime as dt
from decimal import Decimal
from random import randint
from random import choice
import random

#print the current date and time for reference
current_date = dt.datetime.today().date()  # get the current date
current_time = dt.datetime.now().time()  # Get the current time
print(f"Today's date is: {current_date}")
print(f"The current time is: {current_time}")

#Randomly determine the destination year and calculate the cost
base_cost = Decimal('3.50') #cost per year to time travel
current_year = dt.datetime.now().year #get current year
target_year = random.randint(1, 2024) #select a random year
year_difference = abs(current_year - target_year) #years traversed
final_cost = base_cost * year_difference
final_cost_round = round(final_cost, 2) #rounded to 2 decimal places

#Randomly determine a destination
destinations = ["Bellingham", "Tokyo", "Albuquerque", "Vancouver", "Daejeon", "Berea", "Da Nang", "Thai Nguyen"]
destination = random.choice(destinations)

#create a message about the time travel experience.
def generate_time_travel_message(year, destination, cost):
  return f"Pack your bags! You're traveling to {destination} in the year {year}. The cost of this trip will be ${cost}."
print(generate_time_travel_message(target_year, destination, final_cost_round))
Python Course Project: Strings

Python Course Project: Strings

For this project, I used string methods to extract information from sales data which was stored as one huge string. I extracted customer names, sales amounts, and product colors. I calculated the total sales and counted the number of each product color sold.

#replace the artifact between each piece of data within a transaction with something without a comma
daily_sales_replaced = daily_sales.replace(';,;', ';')

# split up daily_sales into a list of individual transactions
daily_transactions = daily_sales_replaced.split(',')
#print(daily_transactions)

#split each individual transaction into a list of its data points.
daily_transactions_split = []
for elem in daily_transactions:
  daily_transactions_split.append(elem.split(';'))
#print(daily_transactions_split)

#strip off any whitespace from each data item
transactions_clean = []
for elem in daily_transactions_split:
  new_list2 = []
  for point in elem:
    new_list2.append(point.replace("\n", "").strip(" "))
  transactions_clean.append(new_list2)
#print(transactions_clean)

#collect the individual data points for each transaction in these 3 lists.
customers = []
sales = []
thread_sold = []

for elem in transactions_clean:
  customers.append(elem[0])
  sales.append(elem[1])
  thread_sold.append(elem[2])
#print(customers)
#print(sales)
#print(thread_sold)

# how much money was made in a day
total_sales = 0
for value in sales:
  total_sales += float(value.strip('$'))
#print(total_sales)

#determine how many of each color thread we sold today.  Separate any strings for multiple colors separated by an &.
thread_sold_split = []
for item in thread_sold:
  if '&' not in item:
    thread_sold_split.append(item)
  else:
    for color in (item.split('&')):
      thread_sold_split.append(color)
#print(thread_sold_split)

#function which returns the number of entries in the list that match the argument.
def color_count(color):
  return thread_sold_split.count(color)
#print(color_count('white'))

colors = ['red', 'yellow', 'green', 'white', 'black', 'blue', 'purple']

msg = "There were {} {} sold today"
msg2 = "The total value of all sales is {}"

#print statements about the total number of each color sold.
for item in colors:
  print(msg.format((color_count(item)), item))
Codecademy Python Course Update 4

Codecademy Python Course Update 4

In this guided project, I implemented functions to do physics calculations: converting temperatures, calculating force, energy, and work.

train_mass = 22680
train_acceleration = 10
train_distance = 100
bomb_mass = 1

# function to convert fahrenheit to celsius 
def f_to_c(f_temp):
  c_temp = (f_temp - 32) * 5/9
  return c_temp

#testing the f_to_c function
f100_in_celsius = f_to_c(100)
print(f100_in_celsius)

# function to convert celsius to fahrenheit
def c_to_f(c_temp):
  f_temp = (c_temp * 9/5) + 32
  return f_temp

#testing the c_to_f function
c0_in_fahrenheit = c_to_f(0)
print(c0_in_fahrenheit)

# function to calculate force using mass and acceleration
def get_force(mass, acceleration):
  return mass * acceleration

# Calculate the force exerted by the GE train
train_force = get_force(train_mass, train_acceleration)
print(train_force)
print("The GE train supplies", train_force, " Newtons of force.")

# function to calculate energy using mass and c constant
def get_energy(mass, c = 3*10**8):
  return mass * c**2

# calculating the energy produced by a  1kg bomb
bomb_energy = get_energy(bomb_mass)
print(bomb_energy)
print("A 1kg bomb supplies", bomb_energy, " Joules.")

# function to calculate work using mass, acceleration and distance
def get_work(mass, acceleration, distance):
  return (get_force(mass, acceleration)) * distance

# calculating the work exerted by a train
train_work = (get_work(train_mass, train_acceleration, train_distance))
print("The GE train does", train_work, "Joules of work over", train_distance, "meters.")

CodeCademy Python Course Update 3

CodeCademy Python Course Update 3

In this guided project, I analyzed data for a hair salon.

hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]

prices = [30, 25, 40, 20, 20, 35, 50, 35]

last_week = [2, 3, 5, 8, 4, 4, 6, 2]

# Calculate total price of all haircuts
total_price = 0
for price in prices:
  total_price += price

# Calculate average price of a haircut
average_price = (total_price / len(prices))
print("Average Haircut Price:", average_price)

# Reduce each price by $5
new_prices = [price - 5 for price in prices]
print("New Prices", new_prices)

# Calculate total weekly and daily revenue
total_revenue = 0
for i in range(len(hairstyles)):
  total_revenue += (prices[i] * last_week[i])
print("Total Revenue", total_revenue)
print("Average Daily Revenue", (total_revenue / 7))

# Find haircuts under 30
cuts_under_30 = [hairstyles[i] for i in range(len(hairstyles)) if new_prices[i] < 30]
print("Haircuts Under $30", cuts_under_30)


CodeCademy Python Course Update 2

CodeCademy Python Course Update 2

I am learning about lists in Python, and this code I wrote for my latest project in the course I’m taking.

toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]

prices = [2, 6, 1, 3, 2, 7, 2]

#find out how many $2 slices we have
num_two_dollar_slices = prices.count(2)
#print(num_two_dollar_slices)

#how many kinds of pizza do we have?
num_pizzas = len(toppings)
#print("we sell", num_pizzas, "different kinds of pizza!")

#two dimensional list of pizzas and prices
pizza_and_prices = [[2, "pepperoni"], [6, "pineapple"], [1, "cheese"], [3, "sausage"], [2, "olives"], [7, "anchovies"], [2, "mushrooms"]]
#print(pizza_and_prices)

#sort the pizzas in order of ascending price
pizza_and_prices = sorted(pizza_and_prices)
#print(pizza_and_prices)

#store the cheapest pizza
cheapest_pizza = pizza_and_prices[0]
#print(cheapest_pizza)

#store the most expensive pizza
priciest_pizza = pizza_and_prices[-1]
#print(priciest_pizza)

#remove a slice from list
pizza_and_prices.pop(-1)
#print(pizza_and_prices)

#add a slice to the list
pizza_and_prices.insert(4, [2.5, "peppers"])
#print(pizza_and_prices)

#slice the three lowest-price pizzas
three_cheapest = pizza_and_prices[:3]
print(three_cheapest)
CodeCademy Python Course Update 1

CodeCademy Python Course Update 1

last_semester_gradebook = [["politics", 80], ["latin", 96], ["dance", 97], ["architecture", 65]]

# Your code below: 
subjects = ["physics", "calculus", "poetry", "history"]

grades = [98, 97, 85, 88]

gradebook = [["physics", 98], ["calculus", 97], ["poetry", 85], ["history", 88]]

#print(gradebook)

gradebook.append(["computer science", 100])
gradebook.append(["visual arts", 93])

#modify the visual arts grade +5
#print(gradebook[-1][-1])
gradebook[-1][-1] = 98
#print(gradebook[-1][-1])

#changing poetry to a pass/fail class
#print(gradebook)
gradebook[2].remove(85)
#print(gradebook)
gradebook[2].append("pass")
#print(gradebook)

full_gradebook = [[last_semester_gradebook]+[gradebook]]

print(full_gradebook)