Share
Explore

# python

input, output, conditional branching, math, exception handling, looping, functions

REPL

help()
look for every element in python
>>> help(str)
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("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 提供值給變數，再根據變數為賦予他們資料型態
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(除)
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!)

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
.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!)
list裡的variable也是可以直接assign的
.insert
↑讓list裡的第1個index的值是41
del & .pop(LIFO Last In First Out)

>>> er_temperature
[39, 36]
>>> store = er_temperature.pop()
>>> store
36
.split() ft. time.sleep()
ft. time.sleep()
.split() turns string into list
you can import time and use time.sleep() on your print
.join()
loop
.copy
wayⅡ
slice
loop for list remove
multidimensional list(lists inside lists / rows and columns)
sum()
tuples(immutable_list, more memory efficient than list)
#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
membership testing(in, not in)
🍄 it can be use in range!
concatenation
multiplication
sequence method
count
index
dictionary
a set of key:value pairs
(a pair of key & value equals item, I think 😛)
(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:
accessing key & value
.keys()
.values()
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

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

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

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
unpacking(for dictionary)

constants
Please set values that remain constant a constants
#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.

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)
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!

range(2, 2)⇒沒有值
range(3, 2)⇒沒有值
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
packing
moment: the need of function for receiving not-yet-known data
unpacking
can be use when pick up the first and last name(with split)
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
#repeat until right => first run + while loop
#3 times to exit => sys.exit
#there is a variable remaining constant => constants
import sys

attempt_count = 1

if (attempt_count > 3):
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
iterate in str
>>> 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
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()
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
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:
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 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
self.cars.append(car)

car_1 = Car("march", 2005)
car_2 = Car("santra", 2014)
car_3 = Car("teddybear", 2012)
my_dealership = Dealership()
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
timedelta
🍄 timedelta is object representing a gap of time

🔑 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

wiki_date(application of strftime & strptime)
import datetime