Chapter_3.프로그래밍_언어
by JB
https://hub.gke.mybinder.org/
print("Hellow wolrd")
Hellow wolrd
3/2
1.5
3//2
1
SALARY_RAISE_FACTOR = 0.05
STATE_CODE_MAP = {'AY' : 'An-Yang', 'OS' : 'OnSu', 'DB' : 'DaeBang'}
def update_employee_record(rec):
old_sal = rec['salary']
new_sal = old_sal * ( 1 + SALARY_RAISE_FACTOR)
rec['salary'] = new_sal
state_code = rec['state_code']
rec['state_name'] = STATE_CODE_MAP[state_code]
input_data = [
{'employee_name' : 'Jungwon', 'salary': 200000.0, 'state_code': 'AY'},
{'employee_name' : 'Jongbum', 'salary': 100000.0, 'state_code': 'OS'},
{'employee_name' : 'Sanggyeom', 'salary': 75000.0, 'state_code' : 'DB'}
]
for rec in input_data:
update_employee_record(rec)
name = rec['employee_name']
salary = rec['salary']
state = rec['state_name']
print(name + ' now lives in ' + state)
print(' and makes $' + str(salary))
Jungwon now lives in An-Yang
and makes $210000.0
Jongbum now lives in OnSu
and makes $105000.0
Sanggyeom now lives in DaeBang
and makes $78750.0
my_integer = 2
my_other_integer = 2 + 3
my_float = 2.0
print(str(my_integer) + "," + str(my_other_integer) + "," + str(my_float))
2,5,2.0
my_true_bool = 5
my_false_bool = 10
this_is_true = (0<100)
this_is_false = (0>100)
my_true_bool
my_false_bool
this_is_true
this_is_false == this_is_true
this_is_false
False
a_string = "hello"
same_as_previous = "hello"
an_empty_string = ""
w_a_single_quote = "Hello's"
multi_line_string = """line1
line2"""
multi_line_string
multi_line_string2 = "line1
line2"
multi_line_string2
File "<ipython-input-47-674bcc3d77e8>", line 5
multi_line_string2 = "line1
^
SyntaxError: EOL while scanning string literal
'ABCD'[0]
'A'
"ABCD"[0:6]
'ABCD'
"ABCD"[:-3]
'A'
def sqr(x):
"""입력받은 값을 제곱합니다
에헤라디야~"""
return x*x
print(sqr(5))
print(sqr.__doc__)
my_list = ["a", "b", "c"]
my_set = set(my_list)
my_tuple = tuple(my_list)
print("my_set : ", my_set)
print("my_tuple : ", my_tuple)
my_set
my_set : {'a', 'c', 'b'}
my_tuple : ('a', 'b', 'c')
{'a', 'b', 'c'}
dir(my_set)
['__and__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__iand__',
'__init__',
'__init_subclass__',
'__ior__',
'__isub__',
'__iter__',
'__ixor__',
'__le__',
'__len__',
'__lt__',
'__ne__',
'__new__',
'__or__',
'__rand__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__ror__',
'__rsub__',
'__rxor__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'__xor__',
'add',
'clear',
'copy',
'difference',
'difference_update',
'discard',
'intersection',
'intersection_update',
'isdisjoint',
'issubset',
'issuperset',
'pop',
'remove',
'symmetric_difference',
'symmetric_difference_update',
'union',
'update']
my_set.__repr__()
"{'a', 'c', 'b'}"
my_set.__str__()
my_list = ["a", "b", "c"]
print(my_list[0])
my_list[0] = "A "
my_list.append("d ")
mixed_list = ["A ", 5.7, "B ", [1,2,3]]
mixed_list[3][:-2]
a
[1]
original_list = [1,2,3,4,5,6,7,8]
squares = [x*x for x in original_list]
squares_of_evens = [x*x for x in original_list if x%2==0]
squares_of_test = [x*x for x in original_list if x*x<60]
print("squares_of_evens : ", squares_of_evens)
print("squares_of_test : ", squares_of_test)
squares_of_evens : [4, 16, 36, 64]
squares_of_test : [1, 4, 9, 16, 25, 36, 49]
[1, 4, 9, 16, 25, 36, 49]
my_list = ["a","b", "c"]
first_two_elements = my_list[0:3]
first_two_elements
['a', 'b', 'c']
all_but_last_element = my_list[:-1]
all_but_last_element
['a', 'b']
"ABC DEF".split()
['ABC', 'DEF']
"ABC \tDEF".split()
['ABC', 'DEF']
"ABC \tDEF".split()
['ABC', 'DEF']
"ABCABD".split("AB")
['', 'C', 'D']
",".join(["A","B","C"])
'A,B,C'
start, end, count_by = 1,7,2
"ABCDEFG"[start: end: count_by]
'BDF'
"ABCDEFASDFASEFASDFASDFASDF"[1:len('ABCDEFASDFASEFASDFASDFASDF'):2]
'BDFSFSFSFSFSF'
my_tuple = (1,2,"hellow wolrd")
print(my_tuple[2])
hellow wolrd
my_tuple = (1,2)
zeroth_field, first_field = my_tuple
first_field
2
my_dict = {"January":1, "February": 2}
print(my_dict["January"])
my_dict.items()
1
dict_items([('January', 1), ('February', 2)])
s = set()
5 in s
False
s.add(5)
5 in s
s.add(5)
s
{5}
def my_function(x):
y = x + 1
x_sqrd = x*x
return x_sqrd, y
five_plus_one_sqrd = my_function(5)
my_function(5)
(25, 6)
def my_raise(x, n=2):
return pow(x,n)
two_sqrd = my_raise(2)
two_cubed = my_raise(2, n=3)
two_cubed
pow(-1, 9)
-1
sqr = lambda x : x*x
five_sqrd = sqr(5)
sqr(5)
25
def apply_to_evens(a_list, a_func):
return [a_func(x) for x in a_list if x %2==0]
my_list = [1,2,3,4,5]
sqrs_of_evens = apply_to_evens(my_list, lambda x:x*x)
sqrs_of_evens
[4, 16]
my_list = [1,2,3]
for x in my_list:
print("the number is ", x)
the number is 1
the number is 2
the number is 3
for key, value, in my_dict.items():
print("the value for ", key, " is ", value)
the value for January is 1
the value for February is 2
def test(i):
if i < 3:
print("i은(는) 3보다 작다")
elif i < 5: print("i은(는) 3과 5 사이의 값이다.")
elif i == 5 : print("i은(는) 5다.")
else : print("i은(눈) 5보다 크다.")
test(5.1)
i은(눈) 5보다 크다.
i = 0
while i < 5:
print(i,"는(은) 5보다 작다.")
i = i+1
if i == 5 : print ("5다")
0 는(은) 5보다 작다.
1 는(은) 5보다 작다.
2 는(은) 5보다 작다.
3 는(은) 5보다 작다.
4 는(은) 5보다 작다.
5다
zip(["Sundat", "Monday", "Tuesdat"], range(3))
<zip at 0x7f8a5404b148>
for i in range(0,10):
print(i)
0
1
2
3
4
5
6
7
8
9
bool("")
bool(1<3)
True
mylist = [1,2,3,4,5]
for ind, val in enumerate(mylist):
print("인덱스 : %i" % ind)
print("값 : ", val)
인덱스 : 0
값 : 1
인덱스 : 1
값 : 2
인덱스 : 2
값 : 3
인덱스 : 3
값 : 4
인덱스 : 4
값 : 5
try:
lines = input_test.split("\n")
print("열 번째 줄: ", lines[9])
except:
print("이 파일엔 열 번째 줄이 없습니다.")
이 파일엔 열 번째 줄이 없습니다.
class Dog:
def __init__(self, name):
self.name = name
def respond_to_command(self, command):
if command == self.name: self.speak()
def speak(self):
print("멍멍!!")
fido = Dog("봉구")
fido.respond_to_command("야옹이")
fido.respond_to_command("봉구")
멍멍!!
import pandas as pd
df = pd.DataFrame({
"name": ["Jungwon", "Jongbum", "Sanggyeom"],
"age" : [36,34,28]
})
#other_df = pd.read_csv("myfile.csv")
df["age_plus_one"] = df["age"]+ 1
df["age_times_two"] = 2 * df["age"]
df["age_squared"] = df["age"] * df["age"]
df["over_30"] = df["age"].quantile(0.5)
df_below50 = df[df["age"] < 50]
df["age_squared"] = df["age"].apply(lambda x: x*x)
df_w_name_as_ind = df.set_index("name")
print(df_w_name_as_ind.index)
df
jongbum_row = df_w_name_as_ind.loc["Jongbum"]
print(jongbum_row["age"])
jongbum_row
Index(['Jungwon', 'Jongbum', 'Sanggyeom'], dtype='object', name='name')
34.0
age 34.0
age_plus_one 35.0
age_times_two 68.0
age_squared 1156.0
over_30 34.0
Name: Jongbum, dtype: float64
import pandas as pd
s = pd.Series([1,2,3])
s
0 1
1 2
2 3
dtype: int64
s+2
0 3
1 4
2 5
dtype: int64
s.index
RangeIndex(start=0, stop=3, step=1)
s + pd.Series([4,4,5])
0 5
1 6
2 8
dtype: int64
df_w_age = pd.DataFrame({
"name": ["Tom", "Tyrell", "Claire"],
"age": [60,25,33]
})
df_w_height = pd.DataFrame({
"name": ["Tom", "Tyrell", "Claire"],
"height": [6.2, 4.0, 5.5]
})
joined = df_w_age.set_index("name").join(
df_w_height.set_index("name"))
print(joined)
age height
name
Tom 60 6.2
Tyrell 25 4.0
Claire 33 5.5
print(joined.reset_index())
name age height
0 Tom 60 6.2
1 Tyrell 25 4.0
2 Claire 33 5.5
df = pd.DataFrame({
"name": ["Tom", "Tyrell", "Claire"],
"age": [60,25,33],
"height": [6.2, 4.0, 5.5],
"gender": ["M", "M", "F"]
})
print(df.groupby("gender").mean())
age height
gender
F 33.0 5.5
M 42.5 5.1
medians = df.groupby("gender").quantile(0.5)
medians
| 0.5 | age | height |
|---|---|---|
| gender | ||
| F | 33.0 | 5.5 |
| M | 42.5 | 5.1 |
def agg(ddf):
return pd.Series({
"name": max(ddf["name"]),
"oldest": max(ddf["age"]),
"mean_height": ddf["height"].mean()
})
print(df.groupby("gender").apply(agg))
name oldest mean_height
gender
F Claire 33 5.5
M Tyrell 60 5.1
Subscribe via RSS