黃芝晴 / Hedi Huang

python

input, output, conditional branching, math, exception handling, looping, functions
終端機開啟python
%E6%88%AA%E5%9C%96_2022-07-21_%E4%B8%8B%E5%8D%884.27.52.png

REPL
Read-Eval-Print Loop
讀取 求值 輸出 循環
help()
look for every element in python
>>> help(str)
%E6%88%AA%E5%9C%96_2022-07-21_%E4%B8%8B%E5%8D%884.37.48.png
print()
>>> health = "water and good foods"
>>> print("health is" + health)
health iswater and good foods
>>> print("health is" , health)
health is water and good foods
如果要 print 的內容有換行
可以分成多個print來執行
print("I " + verb + " everyday.\n" + noun.capitalize() + " is my favorite.\nIt make me feel " + adjective + ".")
print("I " + verb + " everyday.")
print(noun.capitalize() + " is my favorite.")
print("It make me feel " + adjective + ".")
input()
>>> favorite_color = input("What is your favorite color? ")
>>> print(favorite_color + " is a good color.")
What is your favorite color? blue
blue is a good color.

data type
int(integer)
float
str(string)

literal
Literals 提供值給變數,再根據變數為賦予他們資料型態
Untitled.png
round()
to the closest integer
ex.
>>> round(5.551115123125783e-17)
0

>>> round(11.9)
12

>>> round(”11.9”)
12
int()
to the closest integer which is under the number
>>> int(11.9)
11

>>> int(”11.9”)
11
float()
>>> float(11)
11.0

>>> float(”11”)
11.0
str()
>>> str(24)
'24'
operation
order(PEMDAS)
PEMDAS_Please Excuse My Dear Aunt Sally
PEMDAS_
Parenthesis(小括號)
Exponent(指數)
Multiplication(乘)
Division(除)
Addition(加)
subtraction(減)
sequence
string—>immutable
to print
>>> print(”I can’t.\nJust can’t.”)
I can't
Just can't

>>> print("""She said,
... "I can't,
... Just can't." """)
She said,
"I can't,
Just can't."

#if use """ (triple quotes), just press enter, \n is no need

>>> print("""She said,\n"I can't." """)
She said,
"I can't."

>>> health = "water" + " and good food" + "!" * 3
>>> health += " Isn't it?"
>>> print(health)
water and good food!!!

#there are no -= if wanting doing subtraction, just assign again.
#str is immutable(不可變)
to len
>>> len("Hedi Huang")
10
# space is included.

>>> name = input("name: ")
name: Hedi Huang
>>> len(name)
10
method
method is a function that is owned by an object. You can access these by using dot notation.
.upper() & .lower()
>>> name.upper()
'HEDI HUANG'
>>> name
'Hedi Huang'
>>> print(name.upper())
HEDI HUANG
>>> name.lower()
'hedi huang'
index(for string!)
Untitled 1.png

booleans
>>> bool(0)
False

>>> bool(1)
True

>>> bool("")
False

>>> bool(not(0 and 1))
True

>>> "he" in "hedi"
>>> true

>>> list = ["hedi, hide"]
>>> "hedi" in list
>>> true

#If there is a value, then it's True.
#Otherwise, it's False.
#Only all are true is true.
comparison
>>> "hedi">"tina"
False
>>> "four">"one"
False
#compare the order of the words' first alphabet
#the later order is bigger

>>> "cosmos" != "cosmos"
False
# != not the same
list—>mutable
Untitled 2.png
.append & .extend
>>> temperature = []
>>> temperature.append(36.5)
>>> temperature.append(36.8)
>>> temperature
[36.5, 36.8]
>>> er_temperature = [39, 40, 38]
>>> temperature.extend(er_temperature)
>>> temperature
[36.5, 36.8, 39, 40, 38]

#append => 在集合a裡新增項目
#extend => 在集合a裡加進集合b 故集合a的內容已變更,集合b內容不變
index(for list!)
Untitled 3.png
Untitled 4.png
list裡的variable也是可以直接assign的
Untitled 5.png
.insert
Untitled 6.png
↑讓list裡的第1個index的值是41
del & .pop(LIFO Last In First Out)
但其實都是從list裡刪掉 不過.pop可以不指定,還可以暫存
Untitled 7.png
>>> er_temperature
[39, 36]
>>> store = er_temperature.pop()
>>> store
36
.split() ft. time.sleep()
Untitled 8.png
ft. time.sleep()
Untitled.gif
.split() turns string into list
you can import time and use time.sleep() on your print
.join()
Untitled 9.png
loop
.copy
Untitled 10.png
Untitled 11.png
wayⅡ
slice
Untitled 12.png
Untitled 13.png
Untitled 14.png
loop for list remove
Untitled 15.png
multidimensional list(lists inside lists / rows and columns)
sum()
Untitled 16.png
tuples(immutable_list, more memory efficient than list)
Untitled 17.png
Untitled 18.png
#Tuple might contain data about a person (hetrogeneous type mixure)
person_a = (name, age, occupation, address)

#List might contain a list of people (homogenous type mixure - all tuples!)
people = [person_a, person_b, person_c]
sequence operation(method)
slice
len
min
max
Untitled 19.png
membership testing(in, not in)
🍄 it can be use in range!
Untitled 20.png
Untitled 21.png
concatenation
multiplication
Untitled 22.png
sequence method
count
index
Untitled 23.png
Untitled 24.png
Untitled 25.png
Untitled 26.png
Untitled 27.png
dictionary
a set of key:value pairs
(a pair of key & value equals item, I think 😛)
Untitled 28.png
(key is kind of label)
🍄 KEY should be immutable type, VALUE has no limitation
(but only if every item in tuple is immutable)
immutable type:
string
integer
tuple

🍄 basic rules of lexicographical order in python:
Untitled 29.png
accessing key & value
.keys()
.values()
Untitled 30.png
sorted()
🍄 sorted() can return copy of the past list back in lexicographical order
sorted()⇒ change the original list
sort()⇒don’t change the original list
Untitled 31.png

update & mutate dictionary
add
🍄 call the key I want to add into the dictionary and assign the value corresponding to the key
Untitled 32.png

del
🍄 pass in the value you want to delete by calling the key into del() function
Untitled 33.png

iterate over dictionary
.items()
Huang_1 = {'name':'Hedi', 'gender':'female', 'age':24}

Huang_2 = {'name':'Tina', 'gender':'female', 'age':56}

Huang_families = [Huang_1, Huang_2]

print("Helllo, we are family Huang!\N{yellow heart}")
for index,i in enumerate(Huang_families, 1):
print()
print(f'member({index}:')
print("==========")
for key, value in i.items():
print(f'{key}: {value}')
(console)
Helllo, we are family Huang!💛

member(1:
==========
name: Hedi
gender: female
age: 24

member(2:
==========
name: Tina
gender: female
age: 56
packing(for dictionary)
variable argument aka keyword argument aka named argument:
position argument ⇒ pass into function in order
Untitled 34.png
unpacking(for dictionary)
Untitled 35.png


constants
Please set values that remain constant a constants
MASTER_PASSWORD = "opensesame"
#uppercase
#put on the top of script
function
parameter & argument (send to function)(vs return)
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that are sent to the function when it is called.
Untitled 36.png
Untitled 37.png
Untitled 38.png

the time to create function:
repeat doing something
action? ⇒print
calculation? ⇒ return

= vs ==
= to assign
== to compare

scope
global & local scope
global & local context

return (from function) (vs parameter & argument)
Untitled 39.png
range(start, stop, step)
Ranges help iterating over numbers.
Commonly be used to repeat a behavior a certain number of times.
start is the starting index, default is 0
stop is the ending index, is excluded from range
step represents how much the index increase, default is 1, negative value is OK!

Untitled 40.png
range(2, 2)⇒沒有值
range(3, 2)⇒沒有值
Untitled 41.png
Untitled 42.png
enumerate
It can help us showing index of the current element in loop.
Or we want some kind of counter
enumerate function will return enumerate object(應該是將iterable的每個element製作一個包含index跟element的tuple
Untitled 43.png
packing
moment: the need of function for receiving not-yet-known data
Untitled 44.png
unpacking
can be use when pick up the first and last name(with split)
Untitled 45.png
if elif else
favorite_color = input("What is your favorite color? ")
if favorite_color == "blue":
print("You must love the sky!")
elif favorite_color == "red":
print("Are you enthusiastic?")
else:
print("It's a nice color!")
factor & common factor_intersection
#the strictist condition should set on the first if
#use variables to store boolean value of condition!

method
.format() & template
>>> introduce_templete = "I am {}, I am {} years old."
>>> name = input("name: ")
name: Hedi Huang
>>> yr = input("yr: ")
yr: 24
>>> print(introduce_templete.format(name, yr))
I am Hedi Huang, I am 24 years old.

>>> print("I need {} {}.".format(3, "pens"))
I need 3 pens.

#argument can be any type

True False
"He" in "Hedi"
True
"he" in "Hedi"
False

module
import module
#set at the top
math
math.ceil() #the nearest bigger integer

error
TypeError: can only concatenate str (not "int") to str

while loop(co→sys.exit)
use it when you want code to repeat until a condition is no longer true
#Please enter the password:
#repeat until right => first run + while loop
#3 times to exit => sys.exit
#there is a variable remaining constant => constants
import sys

MASTER_PASSWORD = "opensesame"

password = input("Please enter the password: ")
attempt_count = 1

while (password != MASTER_PASSWORD):
if (attempt_count > 3):
sys.exit("Too many invalid password s")
password = input("Invalid password, try again: ")
attempt_count += 1

print("Welcome")
for loop
use it when you want to iterate through a set of values(start to finish)
iterable可迭代者 ⇒ str, list
Untitled 46.png
iterate in str
%E6%88%AA%E5%9C%96_2022-07-23_%E4%B8%8A%E5%8D%8810.23.43.png
>>> for letter in "You got this!":
... if letter in "oh":
... print(letter)
...
o
o
h
iterate in list
>>> list = ["Hedi", "Mandy", "Jacky"]
>>> for i in range(len(list)):
... print("Player {}: {}".format(i+1, list[i]))
...
Player 1: Hedi
Player 2: Mandy
Player 3: Jacky
good example
Untitled 47.png
named unicode
>>> you = "\N{pig nose}"
>>> you
'🐽'
OOP(Object-Oriented Programming)
🍄 a way of structuring your code into groups of properties and behaviors
🍄 in python, attribute is the property; method is the behavior
python object
Everything in python is object.
instantiate(instance)
class instantiate object ⇒ object is an instance of class
class is the blueprint of object
So you can create class to be your object’s blueprint
isinstance()
Untitled 48.png
attribute
class attribute
class Car:
wheels = 4
doors = 2
engine = True

car_1 = Car()
car_2 = Car()

car_1.doors = 4
Car.doors = 6

print(f'car_1 {car_1.doors}')
print(id(car_1.doors))
print(f'car_2 {car_2.doors}')
print(id(car_2.doors))
print(f'Car {Car.doors}')
print(id(Car.doors))
console
hedihuang@HediHuang-MBA OOP % python3 attribute.py
car_1 4
4373659984 #different
car_2 6
4373660048 #same
Car 6
4373660048 #same
🍄 Once object’s attribute has been changed, it won’t change with the class attribute change.
instance attribute
Untitled 49.png
class Car:
#class attribute
wheels = 4
doors = 2
engine = True

#instance attribute
def __init__(self, model, year, make = "Ford"):
self.model = model
self.year = year
self.make = make

car_1 = Car("Model T", 1908)
car_2 = Car("Phantom", 2020, "Rolls Royce")

car_1.year = 2015
print(car_1.__dict__)
print(car_2.__dict__)
print(Car.__dict__)
console
hedihuang@HediHuang-MBA OOP % python3 attribute.py
{'model': 'Model T', 'year': 2015, 'make': 'Ford'}
{'model': 'Phantom', 'year': 2020, 'make': 'Rolls Royce'}
{'__module__': '__main__', 'wheels': 4, 'doors': 2, 'engine': True, '__init__': <function Car.__init__ at 0x102d0a7a0>, '__dict__': <attribute '__dict__' of 'Car' objects>, '__weakref__': <attribute '__weakref__' of 'Car' objects>, '__doc__': None}
method
class Car:
wheels = 4
doors = 4

def __init__(self, model, year, make = "Nissan"):
self.model = model
self.year = year
self.make = make
self.ismoving = False
self.gas = 150
def stop(self):
if self.ismoving:
self.ismoving = False
print("The car has stopped.")
else:
print("The car has already stopped.")
def go(self, speed):
if self.use_gas():
if not self.ismoving:
self.ismoving = True
print("The car starts moving.")
print(f'The car is going {speed}.')
else:
print(f'The car now is going {speed}.')
else:
print("The car is running out of gas.")
self.stop()

def use_gas(self):
self.gas -= 50
if self.gas < 0:
return False
else:
return True
car_1 = Car("march", 2005)
car_1.go("slow")
car_1.go("fast")
car_1.stop()
car_1.stop()
car_1.go("slow")
car_1.go("fast")
console
hedihuang@HediHuang-MBA OOP % python3 method.py
The car starts moving.
The car is going slow.
The car now is going fast.
The car has stopped.
The car has already stopped.
The car starts moving.
The car is going slow.
The car is running out of gas.
The car has stopped.

🔑 callenge
💡 Create a method called eat. It should only take self as an argument. Inside of the method, set the is_hungry attribute to False, since the Panda will no longer be hungry when it eats. Also, return a string that says 'Bao Bao eats bamboo.' where 'Bao Bao' is the name attribute and 'bamboo' is the food attribute.
class Panda:
species = 'Ailuropoda melanoleuca'
food = 'bamboo'

def __init__(self, name, age):
self.is_hungry = True
self.name = name
self.age = age
def eat(self):
self.is_hungry = False
return f'{self.name} eats {self.food}.'
Solve:
To put class attribute in method, add self. before the class attribute.

print(__str__)
class Car:
.
.
.
def __str__(self)
print(f'{make} {model} {year}')

car_1 = Car("march", 2005)
print(car_1)
console
Nissan march 2005

iterate(__iter__)
create a class for iterate
create a instance to iterate
use yield from to iterate a iteration
class Dealership:
def __init__(self):
self.cars = []
def __iter__(self):
yield from self.cars
def add_car(self, car):
self.cars.append(car)

car_1 = Car("march", 2005)
car_2 = Car("santra", 2014)
car_3 = Car("teddybear", 2012)
my_dealership = Dealership()
my_dealership.add_car(car_1)
my_dealership.add_car(car_2)
my_dealership.add_car(car_3)
for car in my_dealership:
print(car)
console
hedihuang@HediHuang-MBA OOP % python3 method.py
Nissan march 2005
Nissan santra 2014
Nissan teddybear 2012
__eq__
class Car:
.
.
.
def __eq__(self, other):
return self.make == other.make and self.model == other.model

car_1 = Car("march", 2005)
car_2 = Car("santra", 2014)

if car_1 == car_2
print("Equal")
else:
print("Not equal")
console
Not equal
class Car:
.
.
.
def __eq__(self, other):
return self.make == other.make and self.model == other.model

car_1 = Car("march", 2005)
car_2 = Car("march", 2014)

if car_1 == car_2
print("Equal")
else:
print("Not equal")
console
Equal
datetime(library)
🍄 You should avoid to name your doc name the same as the library
Untitled 50.png
timedelta
🍄 timedelta is object representing a gap of time
Untitled 51.png

Untitled 52.png
🔑 callenge
💡 Write a function named time_machine that takes an integer and a string of "minutes", "hours", "days", or "years". This describes a timedelta. Return a datetime that is the timedelta's duration from the starter datetime.
import datetime
starter = datetime.datetime(2022, 9, 14, 12, 57)
# Remember, you can't set "years" on a timedelta!
# Consider a year to be 365 days.
def time_machine(num, unit):
if unit == 'years':
num *= 365
unit = 'days'

return starter + datetime.timedelta(**{num: unit})
strftime
Untitled 53.png

wiki_date(application of strftime & strptime)
import datetime
answer_format = '%m/%d'
link_format = '%b_%d'
link = 'https://en.wikipedia.org/wiki/{}'

while True:
answer = input("What date would you like? Please use the MM/DD format. Enter 'quit' to quit.")
if answer.upper() == 'QUIT':
break
try:
date = datetime.datetime.strptime(answer, answer_format)
output = link.format(date.strftime(link_format))