Python
Lesson01
greeting = 'Hello World!'
print(greeting)
Lesson02
line01 = "********************" # header / footer
line02 = "* *" # re-use
line03 = "* WELCOME! *"
# starts with a blank line
print('')
print(line01)
print(line02)
print(line03)
print(line02)
print(line01)
Lesson03
meaning = 42
print('')
# if meaning > 10:
# print('Right on!')
# else:
# print('Not today')
# Ternary Operator
print('Right on!') if meaning > 10 else print('Not today')
Lesson04
import math
# String data type
# literal assignment
first = "Mike"
last = "Yom"
print(type(first))
print(type(first) == str)
print(isinstance(first, str))
# constructor function
pizza = str("Pepperoni")
print(type(pizza))
print(type(pizza) == str)
print(isinstance(pizza, str))
# Concatenation
fullname = first + " " + last
print(fullname)
fullname += "!"
print(fullname)
# Casting a number to a string
decade = str(1980)
print(type(decade))
print(decade)
statement = "I like rock music from the " + decade + "s."
print(statement)
# Multiple lines
multiline = '''
Hey, how are you?
I was just checking in.
All good?
'''
print(multiline)
# Escaping special characters
sentence = 'I\'m back at work!\tHey!\n\nWhere\'s this at\\located?'
print(sentence)
# String Methods
print(first)
print(first.lower())
print(first.upper())
print(first)
print(multiline.title())
print(multiline.replace("good", "ok"))
print(multiline)
print(len(multiline))
multiline += " "
multiline = " " + multiline
print(len(multiline))
print(len(multiline.strip()))
print(len(multiline.lstrip())) # left side
print(len(multiline.rstrip())) # right side
# Build a menu
title = "menu".upper()
print(title.center(20, "="))
print("Coffee".ljust(16, ".") + "$1".rjust(4))
print("Muffin".ljust(16, ".") + "$2".rjust(4))
print("Cheesecake".ljust(16, ".") + "$4".rjust(4))
print("")
# string index values
print(first[1]) # 2nd letter
print(first[-1]) # last letter
print(first[1:-1]) # 2nd to last
print(first[1:]) # 2nd and all after 2nd
# Some methods return boolean data
print(first.startswith("M")) # Start with M. Mike so True
print(first.endswith("Z")) # Starts with Z which is not False
# Boolean data type
myvalue = True
x = bool(False) # Constructor method
print(type(x))
print(isinstance(myvalue, bool))
# Numeric data types
# integer type
price = 100
best_price = int(80) # constructor function
print(type(price))
print(isinstance(best_price, int))
# float type
gpa = 3.28
y = float(1.14)
print(type(gpa))
# complex type
comp_value = 5+3j
print(type(comp_value))
print(comp_value.real) # real number
print(comp_value.imag) # imagineary number
# Built-in functions for numbers
print(abs(gpa))
print(abs(gpa * -1))
print(round(gpa)) # nearest
print(round(gpa, 1)) #near decimal point
print(math.pi)
print(math.sqrt(64))
print(math.ceil(gpa)) # ceiling
print(math.floor(gpa)) # floor
# Casting a string to a number
zipcode = "10001"
zip_value = int(zipcode) #cast string into integer
print(type(zip_value))
# Error if you attempt to cast incorrect data
# zip_value = int("New York")
Lesson05
import sys
import random
from enum import Enum
class RPS(Enum):
ROCK = 1
PAPER = 2
SCISSORS = 3
print("")
# print(RPS(2))
# print(RPS.ROCK)
# print(RPS['ROCK'])
# print(RPS.ROCK.value)
# sys.exit()
# User enters option
playerchoice = input(
"Enter...\n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n")
player = int(playerchoice)
# If user enters less than 1 or greater than 3 exit
if player < 1 or player > 3:
sys.exit("You must enter 1, 2, or 3.")
# Computer choice random number between 1-3
computerchoice = random.choice("123")
computer = int(computerchoice)
print("")
print("You chose " + str(RPS(player)).replace('RPS.', '') + ".")
print("Python chose " + str(RPS(computer)).replace('RPS.', '') + ".")
print("")
if player == 1 and computer == 3:
print("🎉 You win!")
elif player == 2 and computer == 1:
print("🎉 You win!")
elif player == 3 and computer == 2:
print("🎉 You win!")
elif player == computer:
print("😲 Tie game!")
else:
print("🐍 Python wins!")
Lesson06
users = ['Dave', 'John', 'Sara']
data = ['Dave', 42, True]
emptylist = []
print("Dave" in emptylist)
# print("Dave" in users)
print(users[0])
print(users[-2])
print(users.index('Sara'))
print(users[0:2])
print(users[1:])
print(users[-3:-1])
print(len(data))
users.append('Elsa')
print(users)
users += ['Jason'] # make sure it's list
print(users)
users.extend(['Robert', 'Jimmy'])
print(users)
# users.extend(data)
# print(users)
users.insert(0, 'Bob') # add to 1st position
print(users)
print("")
users[2:2] = ['Eddie', 'Alex'] # does not replace value
print(users)
print("")
users[1:3] = ['Robert', 'JPJ'] # this replace the value
print(users)
print("")
users.remove('Bob')
print(users)
print("")
print(users.pop()) # Remove last item
print(users)
print("")
del users[0]
print(users)
print("")
# # del data
# data.clear() # this will empty the list
# print(data)
print("")
users[1:2] = ['dave'] #insert
users.sort()
print(users)
users.sort(key=str.lower)
print(users)
nums = [4, 42, 78, 1, 5]
nums.reverse()
print(nums)
nums.sort(reverse=True)
print(nums)
print(sorted(nums, reverse=True))
print(nums)
numscopy = nums.copy()
mynums = list(nums)
mycopy = nums[:]
print("")
print(numscopy)
print(mynums)
mycopy.sort()
print(mycopy)
print(nums)
print(type(nums))
mylist = list([1, "Neil", True])
print(mylist)
# # Tuples order data in will not change
mytuple = tuple(('Dave', 42, True))
anothertuple = (1, 4, 2, 8, 2, 2)
print("")
print(mytuple)
print(type(mytuple))
print(type(anothertuple))
print("")
newlist = list(mytuple)
newlist.append('Neil')
newtuple = tuple(newlist)
print(newtuple)
(one, two, *hey) = anothertuple
print(one)
print(two)
print(hey)
print("")
(one, *two, hey) = anothertuple
print(one)
print(two)
print(hey)
print("")
print(anothertuple.count(2))
Lesson07
# Dictionaries
band = {
"vocals": "Plant",
"guitar": "Page"
}
band2 = dict(vocals="Plant", guitar="Page")
print(band)
print("")
print(band2)
print(type(band))
print(len(band))
print("")
# # Access items
print(band["vocals"])
print(band.get("guitar"))
# # list all keys
print(band.keys())
# # list all values
print(band.values())
# # list of key/value pairs as tuples
print(band.items())
# # verify a key exists
print("guitar" in band)
print("triangle" in band)
# # Change values
band["vocals"] = "Coverdale"
band.update({"bass": "JPJ"})
print("")
print(band)
# # Remove items
print(band.pop("bass"))
print(band)
band["drums"] = "Bonham"
print(band)
# print(band.popitem()) # tuple
print(band)
# # Delete and clear
band["drums"] = "Bonham"
del band["drums"]
print(band)
band2.clear()
print(band2)
del band2
# # Copy dictionaries
# band2 = band # create a reference
# print("Bad copy!")
# print(band2)
# print(band)
# band2["drums"] = "Dave"
# print(band)
band2 = band.copy()
band2["drums"] = "Dave"
print("Good copy!")
print(band)
print ("")
print(band2)
# or use the dict() constructor function
band3 = dict(band)
print("Good copy!")
print(band3)
# Nested dictionaries
member1 = {
"name": "Plant",
"instrument": "vocals"
}
member2 = {
"name": "Page",
"instrument": "guitar"
}
band = {
"member1": member1,
"member2": member2
}
print("")
print(band)
print("")
print(band["member1"]["name"])
# Sets
nums = {1, 2, 3, 4}
nums2 = set((1, 2, 3, 4))
print(nums)
print(nums2)
print(type(nums))
print(len(nums))
# No duplicate allowed
nums = {1, 2, 2, 3}
print(nums)
# True is a dupe of 1, False is a dupe of zero
# 1 is front of True so 1 is printed and False is front of 0 so False
# is printed
nums = {1, True, 2, False, 3, 4, 0, 3, 5}
print("")
print(nums)
# check if a value is in a set
print(2 in nums)
# # but you cannot refer to an element in the set with an index position or a key
# Add a new element to a set
nums.add(8)
print(nums)
# Add elements from one set to another
morenums = {5, 6, 7}
nums.update(morenums)
print("")
print(nums)
# # you can use update with lists, tuples, and dictionaries, too.
# Merge two sets to create a new set
one = {1, 2, 3}
two = {5, 6, 7}
mynewset = one.union(two)
print(mynewset)
# Keep only the duplicates
one = {1, 2, 3}
two = {2, 3, 4}
one.intersection_update(two)
print(one)
# Keep everything except the duplicates
one = {1, 2, 3}
two = {2, 3, 4}
one.symmetric_difference_update(two)
print(one)
Lesson 8
2.42 mins
Brute force forloop
a = 8
b = 7
c = 38
d = 3
e = -5
f = -1
# 8x + 7y = 38
# 3x - 5y = -1
found = False
for x in range(-10, 11):
for y in range(-10, 11):
ans1 = (8 * x) + (7 * y)
ans2 = (3 * x) - (5 * y)
if (ans1 == 38) and (ans2 == -1):
print('The x is', x)
print('The y is', y)
found = True
if found == False:
print('No solution')
Check Order
def in_order(nums):
print(nums)
my_max = len(nums) -1
print(my_max)
for i in range(my_max):
print("This is i:",i)
print("This is number",nums[i])
print("")
if(nums[i] > nums[i+1]):
return True
break
return False
nums1 = [5, 6, 7, 8, 3]
#nums1 = [5, 6, 7, 8, 10]
if in_order(nums1):
print("Not in Order")
else:
print("In Order")
Check Remote Port 22
#!/bin/python3
# mikeyom@gmail.com 08-2023
import socket
import sys
socket.setdefaulttimeout(5)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('sftp.mikeyom.com',22))
if result == 0:
print ("AS SFTP Port 22 is open")
exit(0)
else:
print ("AS SFTP Port 22 is closed")
exit(2)
sock.close()
Convert an integer to binary
number = int(input())
number_list =[]
while number > 0:
number_list.append(number)
number = number // 2
for num in number_list:
if num % 2 == 0:
print('0', end='')
else:
num % 2 == 1
print('1', end='')
Dictionary For Loop
mystr = "Mike,123-4567 Jenny,443-1234 Alec,331-1234"
contact_list = mystr.split()
print(contact_list)
my_dict = {}
for pair in contact_list:
split_pair = pair.split(',')
key = str(split_pair[0])
my_dict[key]=str(split_pair[1])
print("This is pair:",pair)
print("This is split pair:",split_pair)
print ("")
print(my_dict)
#name = input()
name = "Jenny"print(my_dict[name])
Email Script
import smtplib
from email.mime.text import MIMEText
# Set the SMTP server and login credentials
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your@email.com"
password = "yourpassword"
# Set the email parameters
recipient = "recipient@email.com"
subject = "Test email from Python"
body = "This is a test email sent from Python."
# Create the email message
msg = MIMEText(body)
msg["Subject"] = subject
msg["To"] = recipient
msg["From"] = username
# Send the email
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.send_message(msg)
server.quit()
Exception
def fat_burning_heart_rate(age):
heart_rate = (220-age)*.7
return heart_rate
def get_age():
# age = int(input())
age = 35
if ((age < 18) or (age > 75)):
raise ValueError('Invalid age.')
return age
if __name__ == "__main__":
try:
age = get_age()
heart_rate = fat_burning_heart_rate(age)
print('Fat burning heart rate for a', age, 'year-old:',heart_rate, 'bpm')
except ValueError as e:
print(e)
print('Could not calculate heart rate info.')
Exception an Integer
# Input
# Lee 18
# Lua 21
# Mary Beth 19
# Stu 33
# -1
# Output
# Lee 19
# Lua 22
# Mary 0
# Stu 34
parts = input().split()
name = parts[0]
while name != '-1':
try:
age = int(parts[1]) + 1
print('{} {}'.format(name, age))
parts = input().split()
name = parts[0]
except ValueError as e:
age = 0
print('{} {}'.format(name, age))
parts = input().split()
name = parts[0]
File Transfer
import socket
# create socket
s = socket.socket()
# bind socket to a address and port
s.bind(('localhost', 12345))
# put the socket into listening mode
s.listen(5)
print('Server listening...')
# forever loop to keep server running
while True:
# establish connection with client
client, addr = s.accept()
print(f'Got connection from {addr}')
# receive the file name
file_name = client.recv(1024).decode()
try:
# open the file for reading in binary
with open(file_name, 'rb') as file:
# read the file in chunks
while True:
chunk = file.read(1024)
if not chunk:
break
# send the chunk to the client
client.sendall(chunk)
print(f'File {file_name} sent successfully')
except FileNotFoundError:
# if file not found, send appropriate message
client.sendall(b'File not found')
print(f'File {file_name} not found')
# close the client connection
client.close()
Integer to Binary
def string_reverse(input_string):
str_to_list = list(input_string)
reverse_list = str_to_list[::-1]
list_to_str = ''.join(reverse_list)
return list_to_str
string_reverse('12345')
def int_to_reverse_binary(integer_value):
binary_num = ""
while integer_value > 0:
binary_num = binary_num + str(integer_value % 2)
integer_value = integer_value // 2
return binary_num
print(int_to_reverse_binary(6))
def string_reverse(input_string):
str_to_list = list(input_string)
reverse_list = str_to_list[::-1]
list_to_str = ''.join(reverse_list)
return list_to_str
def int_to_reverse_binary(integer_value):
binary_num = ""
while integer_value > 0:
binary_num = binary_num + str(integer_value % 2)
integer_value = integer_value // 2
return binary_num
if __name__ == '__main__':
integer_value = int(input())
a = int_to_reverse_binary(integer_value)
print(string_reverse(a))
int_to_reverse_binary(19)
Name List
str="Mike Sung Yom"
#str="Jenny Yom"
name=str.split()
mylen = len(name)
if mylen == 3:
result = name[2]+". "+name[0][0]+". "+name[1][0]+"."
else:
result = name[1]+". "+name[0][0]+". "
print(result)
Odd and Event Numbers
size = 5
def get_numbers(num):
numbers = []
user_input = input(f'Enter {num} integers:\n')
i = 0
for token in user_input.split():
number = int(token) # Convert string input into integer
numbers.append(number) # Add to numbers list
print(i, number)
i += 1
return numbers
def print_all_numbers(numbers):
# Print numbers
my_num = ' '.join(str(e) for e in numbers)
print('Numbers:', my_num)
def print_odd_numbers(numbers):
odd_num=[]
for num in numbers:
if num % 2 != 0:
odd_num.append(num)
# Print all odd numbers
my_odd = ' '.join(str(f) for f in odd_num)
print('Odd numbers:',my_odd)
def print_negative_numbers(numbers):
neg_num=[]
for num in numbers:
if num < 0:
neg_num.append(num)
my_neg = ' '.join(str(g) for g in neg_num)
# Print all negative numbers
print('Negative numbers:',my_neg)
nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)
# 5 99 -44 0 12
# Numbers: 5 99 -44 0 12
# Odd numbers: 5 99
# Negative numbers: -44
# size = 5
Swap String
System Monitor
import psutil
# Get the current CPU usage
cpu_usage = psutil.cpu_percent()
# Get the current memory usage
memory_usage = psutil.virtual_memory().percent
# Get the current disk usage
disk_usage = psutil.disk_usage("/").percent
# Get the network activity
# Get the current input/output data rates for each network interface
io_counters = psutil.net_io_counters(pernic=True)
for interface, counters in io_counters.items():
print(f"Interface {interface}:")
print(f" bytes sent: {counters.bytes_sent}")
print(f" bytes received: {counters.bytes_recv}")
# Get a list of active connections
connections = psutil.net_connections()
for connection in connections:
print(f"{connection.laddr} <-> {connection.raddr} ({connection.status})")
# Print the collected data
print(f"CPU usage: {cpu_usage}%")
print(f"Memory usage: {memory_usage}%")
print(f"Disk usage: {disk_usage}%")
Triangle Area
a = 3.0
b = 4.0
c = 5.0
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print(f'The area of the triangle is: {area:.3f}')
import math
a = 3.0
b = 4.0
c = 5.0
s = (a + b + c) / 2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
print(f'The area of the triangle is: {area:.3f}')
Web Scraping
import requests
from bs4 import BeautifulSoup
# Fetch a web page
page = requests.get("http://www.example.com")
# Parse the HTML content
soup = BeautifulSoup(page.content, "html.parser")
# Find all the links on the page
links = soup.find_all("a")
# Print the links
for link in links:
print(link.get("href"))
While loop join string
num_rows = int(input())
3
num_cols = int(input())
4
Output
1A 1B 1C 1D
2A 2B 2C 2D
3A 3B 3C 3D
num_rows = int(input())
num_cols = int(input())
num = 0
while num < num_rows:
num += 1
start = 65
last_chr = 65 + num_cols
while start < last_chr:
print(f'{num}{chr(start)}', end=' ')
start += 1
print(f"\n")
# String Methods
print(first)
print(first.lower())
print(first.upper())
print(first)