2018, 10, 22 일 ~ 2018,3,31 토 끝 (10 hours)

 

파이썬은 대소문자를 구분한다.

파이썬은 ;(세미콜론)을 하지 않고도 인식한다.

위에서 아래로 결과가 읽힌다.

파이썬은 대부분 패키지를 이용해서 사용하는데 자주 사용되는 함수를 "내장함수"라는 이름으로 기본적으로 제공한다.

 

주의할 점

반복문이나 함수를 불러올 때 : 를 반드시 사용해야 한다.

 

 

 

파생 클래스, 서브 클래스, 파이선의 내장된 슈퍼 클래스

 

 

True, False 참 거짓.

 

1. 파이썬 변수 담기

variable = 10

print variable

출력 결과 : 10

 

2. 변수를 재선언해서 담으면 그 변수 값으로 변경된다.

예)

variable = 10

variable = 47

print variable

출력 결과 : 47

 

3. 함수 사용 방법.

틀)

def 함수(입력 변수):

함수 내용

예)

def spam():

eggs = 12

return eggs

(한칸 띄움)

(두칸 띄움)

print spam()

출력 결과 : 12

설명: spam(): 이라는 함수 선언.

eggs 라는 변수 선언과 동시에 12라는 값을 넣음.

eggs를 return하여 spam(): 함수에 담음.

spam(): 함수를 print 하여 출력

 

-----

def spam():

print "blablabla"

 

spam()

 

출력 결과: blablabla

-----

 

4. 거듭제곱

틀) 변수 = 거듭제곱할 숫자 ** 횟수

예)

variable = 10 ** 3

출력 결과 : 1000

이유 : (10 x 10 x 10)

variable = 2 ** 4

출력 결과 : 16

이유 : (2 x 2x 2x 2)

 

5. + 연산자(안에 Space bar도 포함.)

print "spam " + "eggs " + "rice"

출력 결과: sapm eggs rice

 

 

def : 함수 선언할 때 사용.

파이썬은 변수 선언할 때 자료형을 자동으로 정해주므로 자료형 선언이 필요 없다.

int, char 사용 안해도 됨.

 

입력 할 수 있는 공간을 만들어 준다.

raw_input("입력")

사용 예) variable = raw_input("Prompt")

print variable

 

산술 연산자 줄여서 사용하기. 산술 연산자 다 사용 가능.

a = a + 1

a += 1

 

 

함수

sqrt()는 루트를 씌워서 계산하라는 뜻이다.

sqrt(25) == 5이다.

 

abs() 절대값을 반환하는 함수

예) abs(-5)

>> 5

abs(-6.01)

>> 6.01

abs('oxo')

>> Type Error : str

 

round() 실수를 반올림 해주는 함수.

소수점 첫째 자리가 5 이고 정수가 홀수일 때는 반올림, 짝수일 때는 반내림? 한다.

 

type() 데이터 타입을 알려주는 함수

예) print(35)

print(3.5)

print('ok')

>> <type 'int'>

>> <type 'float'>

>> <type 'str'>

 

리스트 함수

append() 자료 끝 부분에 추가

예) suitcase = ["bag", "Money", "cloth"]

suitcase.append("sunglasses")

>> ['bag', 'Money', 'cloth', 'sunglasses']

 

insert(자릿수, "변경할 값이나 문자")

예) animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]

duck_index = animals.index("duck")

여기서 # duck_index == 2 이다.(.index 속성)

animals.insert(duck_index,"cobra")

 

sort() 낮은 숫자가 왼쪽부터 정렬.(오름차순 정렬)

예) number = [20, 500, 1, 7, 44]

number.sort()

print number

>> 1, 7, 20, 44, 500

 

reverse() 역순으로 정렬

예) number = [20, 500, 1, 7, 44]

number.reverse()

print number

>> 44, 7, 1, 500, 20

 

.join() 리스트에 특정 구분자를 추가하여 문자열로 변환함. 특정 구분자 포함 기능.

예) ",".join("asd")

>> "a,s,d"

"".join("a,s,d")

>> "asd"

 

enumerate() - 인덱스와 값이 분리되어 나옴.

# for 인덱스, 자료값 in enumerate(리스트):

choices = ['pizza', 'pasta', 'salad', 'nachos']

 

for index, item in enumerate(choices):

print index, item

>> 0 pizza

>> 1 pasta

>> 2 salad

>> 3 nachos

 

 

 

A. items() - 변수 뒤에 .items()를 붙이면 키와 값 목록이 모두 출력된다.

my_dict = {

"Name": "Creator",

"Age": 59,

"BDFL": True

}

print my_dict.items()

>> [('BDFL', True), ('Age', 59), ('Name', 'Creator')]

 

B. keys() - key 목록만 반환시킨다.

print my_dict.keys()

>> ['BDFL', 'Age', 'Name']

 

C. values() - 값 목록만 반환시킨다.

print my_dict.values()

>> [True, 59, 'Creator']

 

 

lambda(), 람다 - 함수를 생성할 때 사용하는 예약어 def와 동일한 역할을 하며 def를 사용할 정도로 복잡하지 않거나 def를 사용할 수 없는 곳에 사용됨.

형식: (lambda 함수 안에서의 사용할 변수: 조건, 실제 불러올 변수)

 

아래 두 예제(A)는 서로 같다.

 

A) sum = lambda a,b: a + b

 

A) def sum(a, b):

return a + b

 

사용 예)

B) my_list = range(16)

print filter(lambda x: x % 3 == 0, my_list)

>> [0, 3, 6, 9, 12, 15]

 

B) languages = ["HTML", "JavaScript", "Python", "Ruby"]

print filter(lambda x: x == "Python", languages)

>> ['Python']

 

filter() -

filter(함수, 리스트)

 

 

randint - 두 정수 사이의 어떤 랜덤한 정수(난수)를 리턴시켜주는 함수

uniform - 두 수 사이의 랜덤한 소수(난수)를 리턴시켜주는 함수

 

=================================================================

주석 사용법

# : 한 줄 커멘트(주석)

''' 내용 ''' 여러 줄 커멘트(주석)

=================================================================

 

=================================================================

나눗셈

모든 홀수 %2로 나누면 나머지가 1이 된다.

# %는 나머지 반환한다.

# /는 몫을 반환한다.

 

print 8 % 2

>> 0

print 8 / 2

>> 4

 

// 나눗셈을 찾으면서 뭘까 하고 찾아보다 floor division 이라는 단어와 연결되는 것 같다.

floor division은 몫 의외의 값은 내리는 나눗셈을 말한다.

 

ex)

4/3 => 1.3333333333...... => 1

 

29/10=> 2.9 => 2

 

사담이다만. Floor Function

하듯이,

Floor Division 이라고 말하는 것 같다..[출처] Floor division|작성자 코딩하는기계

소수점 나누기
6.75 / 100 = 0.0675(0이 왼쪽으로 이동)
=================================================================

=================================================================
문자열
This isn't flying, this is falling with style!
라는 문자열을 추가하고 싶다.
print 'This isn't flying, this is falling with style!' ← 오류
'(작은 따옴표)전에 \(백슬래시)를 사용하면 문자로 인식한다. '\
print 'This isn\'t flying, this is falling with style!' 이후 정상 출력

문자열을 사용할 때 %를 붙여 사용하여야 한다.
예)
class Car(object): 
  condition = "new" 
  def __init__(self, model, color, mpg): 
    self.model = model 
    self.color = color 
    self.mpg   = mpg 
    
# color와, model은 문자열이여서 %s로 그대로 사용하면 되고 mpg는 정수이기 때문에 str()을 사용하여 문자열로 변환한다.
  def display_car(self): 
    print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg)) 

my_car = Car("DeLorean", "silver", 88) 

my_car.display_car()
>> This is a silver DeLorean with 88 MPG.

=================================================================

=================================================================
문자열의 각 문자에는 숫자가 할당된다. 0부터 시작함에 유의!
+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
  0   1   2   3   4   5

variable = "Abocado"[4]
print variable 결과는 a다.
variable = "Abocado"[6]
print variable 결과는 o다.
=================================================================

=================================================================
배열
j = [4, 5, 6]
자릿수 = j[0], j[1], j[2]
#배열명[숫자]
j[1] = 7
print (j)
[4, 7, 6]
=================================================================

=================================================================
FOR IN
for 변수 in 배열:
   내용
# 이해하기 좋은 예제
d = {'x': 9, 'y': 10, 'z': 20} 
for key in d: 
    if d[key] == 10: 
      print "This dictionary has the value 10!"

----------------------------------------------------------------
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'} 

형식: key 불러오기 → for 안에 변수. value 불러오기 → in 안에꺼[key]
for key in d: 
  print key, d[key]

>> a apple
>> c cherry
>> b berry

목록에 대한 이해. (for 앞의 값이 출력된다.)

x = 1일 때 *2를 하므로 x == 2 나누고 나서 나머지 값 1
x = 2일 때 *2를 하므로 x == 4 나누고 나서 나머지 값 2
x = 3일 때 *2를 하므로 x == 나누고 나서 나머지 값 0 요게 참 값
x = 4일 때 *2를 하므로 x == 나누고 나서 나머지 값 1

x = 5일 때 *2를 하므로 x == 10 나누고 나서 나머지 값 2

 

 

=================================================================

 

=================================================================

range

#range(시작, 끝전, 증감)

range(6) => [0, 1, 2, 3, 4, 5]

range(1, 6) => [1, 2, 3, 4, 5]

range(1, 6, 3) => [1, 4] # 1에서 5까지 3씩 증가된 데이터를 for ~ in에 의해 데이터를 순차적으로 변수에 할당

=================================================================

 

=================================================================

리스트 반복 사용 방법

1. Method 1

for item in list:

print item

 

2. Method 2

for i in range(len(list)):

print list[i]

=================================================================

 

=================================================================

문자열 함수(String methods)

1. len() -- 길이 측정할 때 사용

2. lower() -- 모든 문자열을 소문자로 만들어준다.

3. upper() -- 모든 문자열을 대문자로 만들어준다.

4. str() -- 숫자 실수 등을 문자열로 사용 가능.

 

사용 예)

parrot = "Nyang Haha"

print len(parrot)

출력 결과 : 10 (빈공간까지 숫자로 인식한다.)

 

print parrot.lower()

출력 결과 : nyang haha

 

print parrot.upper()

출력 결과 : NYANG HAHA

 

pi를 실수로 저장.

pi = 3.14

print str(pi)

출력 결과 : 3.14(숫자이나 문자열로 변환되어 출력)

=================================================================

 

=================================================================

진법, 진수 변환

2진법은 0, 1로 구성되어 있다. 0b로 표시된다. ex) 0b1 0b10

8진법은 0 ~ 9로 구성되어 있다. 0o로 표시된다. ex) 0o1 0o10

16진법은 0 ~ 9ABCDEF로 구성되어있다. 0x로 표시된다. ex) 0x1 0x10

 

2진수값으로 변환하려면 bin()를 쓴다.

8진수값으로 변환하려면 oct()를 쓴다.

16진법값으로 변환하려면 hex()를 쓴다.

참고 링크: http://blog.naver.com/ninjadesyo/221005203776

 

정수→ 진수 값 변환

print bin(201) → 0b11001001

 

2진법 8진법 16진법으로 표시된 것을 10진수 정수로 알고 싶다면 print 해보면 안다.

ex) print 0b11001001 → 201

 

========================

int('x', n) : n진수 x를 10진수로 변환

========================

 

BIT AND 연산자

a: 00101010 42

b: 00001111 15

===================

a & b: 00001010 10

 

0 & 0 = 0

0 & 1 = 0

1 & 0 = 0

1 & 1 = 1

 

Therefore,

0b111 (7) & 0b1010 (10) = 0b10

 

BIT OR 연산자

a: 00101010 42

b: 00001111 15

================

a | b: 00101111 47

 

0 | 0 = 0

0 | 1 = 1

1 | 0 = 1

1 | 1 = 1

 

110 (6) | 1010 (10) = 1110 (14)

 

BIT XOR 연산자

a: 00101010 42

b: 00001111 15

================

a ^ b: 00100101 37

 

0 ^ 0 = 0

0 ^ 1 = 1

1 ^ 0 = 1

1 ^ 1 = 0

111 (7) ^ 1010 (10) = 1101 (13)

 

BIT NOT 연산자

print ~1

print ~2

print ~3

print ~42

print ~123

>> -2

>> -3

>> -4

>> -43

>> -124

=================================================================

 

=================================================================

비트 연산자

비트를 지정된 수만큼 왼쪽으로 이동시킨다.

# Left Bit Shift (<<)

0b000001 << 2 == 0b000100 (1 << 2 = 4)

0b000101 << 3 == 0b101000 (5 << 3 = 40)

 

비트를 지정된 수만큼 오른쪽으로 이동시킨다.

# Right Bit Shift (>>)

0b0010100 >> 3 == 0b000010 (20 >> 3 = 2)

0b0000010 >> 2 == 0b000000 (2 >> 2 = 0)

=================================================================

 

=================================================================

from datetime import datetime

 

datetime.now() 시간 확인 가능. 변수에 담아서 사용 가능.

now = datetime.now()

 

print now.month

print now.day

print now.year

 

print '%s/%s/%s' % (now.month, now.day, now.year)

=================================================================

 

=================================================================

pyg = 'ay'

 

original = raw_input('Enter a word:')

 

if len(original) > 0 and original.isalpha():

word = original.lower()

first = word[0]

new_word = word + first + pyg

new_word = new_word[1:len(new_word)]

print new_word

else:

print 'empty'

 

해석

original 변수에 입력 값을 받는다. AsD 입력 하였을 때

original 변수에 최소 하나 이상 담아야 하고 알파벳일 때

word 변수에 original 변수를 소문자화 하여 담는다. word == asd

first 변수에 word 변수에 0번째 문자를 담는다. first == a

new_word 변수에 word + first + pyg 변수를 담는다. new_word == asdaay

 

new_word == new_word[1:len(new_word)]

new_word == new_word[1:6]

new_word == sdaay

 

 

추가 사용법과 예) List Slicing [:]

시작:끝:항목간 공간

 

Variable1 = YamyXcol

 

print Variable1[0] == Y

 

prunt Variable[1:] == amyXcol

print Variable1[:4] == Yamy

print Variable1[1:4] == amy

print Variable1 [3:6] == yXc

 

 

=================================================================

 

=================================================================

=================================================================

5. Lists & Dictionaries

1. Python Lists and Dictionaries

1-1. Introduction to Lists

list_name = [item_1, item_2]

list_name = [자릿수[0], 자릿수[1]]

예) zoo_animals = ["pangolin", "cassowary", "sloth"]

if len(zoo_animals) > 2:

print "The first animal at the zoo is the " + zoo_animals[0]

print "The second animal at the zoo is the " + zoo_animals[1]

print "The third animal at the zoo is the " + zoo_animals[2]

 

1-2. Access by Index

number = [5, 6, 7, 8]

print number[0] + number[2]

출력 결과: 12

print number[1] + number[3]

출력 결과: 14

 

1-8 For One and All

my_list = [1,9,3,8,5,7]

for number in my_list:

print 2 * number

>> 2

>>18

>>6

>>16

>>10

>>14

 

1-9 More with 'for'

start_list = [5, 3, 1, 2, 4]

square_list = []

 

for number in start_list:

square_list.append(number ** 2)

 

square_list.sort()

print square_list

>> [1, 4, 9, 16, 25]

 

설명: start_list 변수를 반복문으로 쓰기 위해 number 라는 또다른 변수 이름을 사용한다.

square_list에 start_list를 제곱해서 반복 받아 추가한다.

sort()를 사용하여 오름차순 정렬을 한다.

 

 

1-10 This Next Part is Key

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

 

print residents['Puffin']

print residents['Sloth']

print residents['Burmese Python']

>>104

>>105

>>106

 

 

1-11 New Entries

menu = {} # Empty dictionary

menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair

print menu['Chicken Alfredo']

 

menu['Rice'] = 5.0

menu['fish'] = 7.5

menu['kimchi'] = 10.0

 

print "There are " + str(len(menu)) + " items on the menu."

print menu

>> 14.5

>> There are 4 items on the menu.

>> {'Chicken Alfredo': 14.5, 'fish': 7.5, 'Rice': 5.0, 'kimchi': 10.0}

 

 

1-12 Chainging Your Mind

# key - animal_name : value - location

zoo_animals = { 'Unicorn' : 'Cotton Candy House',

'Sloth' : 'Rainforest Exhibit',

'Bengal Tiger' : 'Jungle House',

'Atlantic Puffin' : 'Arctic Exhibit',

'Rockhopper Penguin' : 'Arctic Exhibit'}

 

del zoo_animals['Unicorn']

del zoo_animals['Sloth']

del zoo_animals['Bengal Tiger']

 

# 여기선 key_name이 아니라 이미 key가 되버림.

zoo_animals['Rockhopper Penguin'] = 'Plains Exhibit'

 

print zoo_animals

>> {'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper Penguin': 'Plains Exhibit'}

 

1-13 Remove a Few Things

backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']

backpack.remove('dagger')

print backpack

>> backpack = ['xylophone', 'tent', 'bread loaf']

 

 

1-14 It's Dangerous to Go Alone! Take this

inventory = {

'gold' : 500,

'pouch' : ['flint', 'twine', 'gemstone'],

'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']

}

 

# Adding a key 'burlap bag' and assigning a list to it

inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

 

# Sorting the list found under the key 'pouch'

inventory['pouch'].sort()

 

# Your code here

inventory['pocket'] = ['seashell', 'strange berry', 'lint']

inventory['backpack'].sort()

inventory['backpack'].remove('dagger')

 

inventory['gold'] += 50

 

print inventory

 

>> {'pocket': ['seashell', 'strange berry', 'lint'], 'backpack': ['bedroll', 'bread loaf', 'xylophone'], 'pouch': ['flint', 'gemstone', 'twine'], 'burlap bag': ['apple', 'small ruby', 'three-toed sloth'], 'gold': 600}

 

 

2. A Day at the Supermarket

2-1. BeFOR We Begin

names = ["Adam","Alex","Mariah","Martine","Columbus"]

for elements in names:

print elements

 

>> Adam

>> Alex

>>Mariah

>> Martine

>> Columbus

 

 

2-2. This is KEY!

webster = {

"Aardvark" : "A star of a popular children's cartoon show.",

"Baa" : "The sound a goat makes.",

"Carpet": "Goes on the floor.",

"Dab": "A small amount."

}

 

for word in webster:

print webster[word]

 

>> A star of a popular children's cartoon show.

>> Goes on the floor.

>> A small amount.

>> The sound a goat makes.

 

 

2-3. Control Flow and Looping

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

 

for number in a:

if number % 2 == 0: #나머지가 0이 되면 출력하라. 즉 짝수만 고르는 프로그램.

print number

>> 0

>> 2

>> 4

>> 6

>> 8

>> 10

>> 12

 

 

2-4. Lists + Functions

# 공통

def fizz_count(x):

count = 0

for item in x:

if item == "fizz":

count += 1

return count

 

1. 첫번째 방법

fizz_count(["fizz", "cat", "fizz"])

print fizz_count

>> <function fizz_count at 0x7f94785a2320>

 

2. 두번째 방법

variable = ("fizz", "D", "ok", "fizz", "fizz")

v2 = fizz_count(variable)

print v2

>> 3

 

 

2-5. String Looping

for letter in "Codecademy":

print letter

 

# 빈 공간 출력

print

print

 

word = "Programming is fun!"

 

for letter in word:

if letter == "i":

print letter

>> C

>> o

>> d

>> e

>> c

>> a

>> d

>> e

>> m

>> y

>> (빈 공간)

>> (빈 공간)

>> i

>> i

 

 

2-6. Your Own Store!,

prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}

 

 

2-7. Investing in Stock

prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}

stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}

 

 

2-8. Keeping Track of the Produce

prices= {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}

stock= {"banana": 6, "apple": 0, "orange": 32, "pear": 15}

 

for food in prices:

print food

print "price: %s" % prices[food]

print "stock: %s" % stock[food]

 

>> orange

>> price: 1.5

>> stock: 32

>> pear

>> price: 3

>> stock: 15

>> banana

>> price: 4

>> stock: 6

>> apple

>> price: 2

>> stock: 0

 

설명: prices를 food라는 이름으로 반복하여 사용.

print food는 prices안에 들어있는 걸 모두 나열하라는 뜻.

prices[자료] 반복해서 빼내기.

stock[자료] 반복해서 빼내기.

 

예시 문을 보고 똑같이 만들라는 줄 알았다.

prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}

stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}

for key in prices:

if key == "apple":

print "apple"

print "price: %s" % prices[key]

print "stock: %s" % stock[key]

>> apple

>> price: 2

>> stock: 0

 

 

2-9. Something of Value

prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}

stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}

 

total = 0

 

for food in prices:

print prices[food] * stock[food]

total = total + prices[food] * stock[food]

 

print total

 

>>48.0

>>45

>>24

>>0

>>117.0

 

설명: price[값] 와 stock[값] 의 똑같은 이름의 값을 곱해서 반복 출력.

이 4개의 각각의 값들을 total에 더한다.

print 한다.

 

 

2-10. Shopping at the Market

groceries = ["banana", "orange", "apple"]

 

 

2-11. Making a Purchase

shopping_list = ["banana", "orange", "apple"]

 

stock = {

"banana": 6,

"apple": 0,

"orange": 32,

"pear": 15

}

 

prices = {

"banana": 4,

"apple": 2,

"orange": 1.5,

"pear": 3

}

 

# Write your code below!

def compute_bill(food):

total = 0

for item in food:

total = total + prices[item]

return total

 

내가 한거

def compute_bill(food):

total = 0

for f2 in food:

total += prices[f2]

return total

 

설명: compute_bill 이라는 함수를 만들고 food 라는 인자 값을 받는다.

total 변수 선언 및 초기화

반복문 for 새로운 변수명 in 배열값 받아 쓸 실제 변수

total = total + prices[f2] total에 prices[반복해서 받음.]값을 받는다.

total 값 리턴!

 

 

2-12. Stocking Out

shopping_list = ["banana", "orange", "apple"]

 

stock = {

"banana": 6,

"apple": 0,

"orange": 32,

"pear": 15

}

 

prices = {

"banana": 4,

"apple": 2,

"orange": 1.5,

"pear": 3

}

 

# Write your code below!

def compute_bill(food):

total = 0

for item in food:

if stock[item] > 0:

total = total + prices[item]

stock[item] = stock[item] - 1

return total

 

설명: 만약 stock에 배열값이 0 초과이면, total에 prices 배열값을 받는다.

 

 

2-13. Let's Check Out!

shopping_list = ["banana", "orange", "apple"]

 

stock = {

"banana": 6,

"apple": 0,

"orange": 32,

"pear": 15

}

 

prices = {

"banana": 4,

"apple": 2,

"orange": 1.5,

"pear": 3

}

 

# Write your code below!

def compute_bill(food):

total = 0

for item in food:

if stock[item] > 0:

total = total + prices[item]

stock[item] = stock[item] - 1

return total

 

print compute_bill(shopping_list)

>> 5.5

 

설명: banana는 stock 6 이므로 total에 prices 바나나 값 4를 더한다.

orange는 stock 32 이므로 total에 prices 오렌지 값 1.5를 더한다.

apple은 stock 값 0 이므로 0 > 0 조건은 성립하지 않는다. 고로 안됨.

total값 return에서 출력 하면 4 + 1.5 = 5.5

 

6. Student Becomes the Teacher

1. Student Becomes the Teacher

1-1. Lesson Number One

lloyd = {

"name" : "Lloyd",

"homework" : [],

"quizzes" : [],

"tests" : []

}

 

alice = {

"name" : "Alice",

"homework" : [],

"quizzes" : [],

"tests" : []

}

 

tyler = {

"name" : "Tyler",

"homework" : [],

"quizzes" : [],

"tests" : []

}

 

 

1-2. What's the Score?

lloyd = {

"name": "Lloyd",

"homework": [90.0, 97.0, 75.0, 92.0],

"quizzes": [88.0, 40.0, 94.0],

"tests": [75.0, 90.0]

}

alice = {

"name": "Alice",

"homework": [100.0, 92.0, 98.0, 100.0],

"quizzes": [82.0, 83.0, 91.0],

"tests": [89.0, 97.0]

}

tyler = {

"name": "Tyler",

"homework": [0.0, 87.0, 75.0, 22.0],

"quizzes": [0.0, 75.0, 78.0],

"tests": [100.0, 100.0]

}

 

 

1-3. Put It Together

lloyd = {

"name": "Lloyd",

"homework": [90.0, 97.0, 75.0, 92.0],

"quizzes": [88.0, 40.0, 94.0],

"tests": [75.0, 90.0]

}

alice = {

"name": "Alice",

"homework": [100.0, 92.0, 98.0, 100.0],

"quizzes": [82.0, 83.0, 91.0],

"tests": [89.0, 97.0]

}

tyler = {

"name": "Tyler",

"homework": [0.0, 87.0, 75.0, 22.0],

"quizzes": [0.0, 75.0, 78.0],

"tests": [100.0, 100.0]

}

 

students = [lloyd, alice, tyler]

 

 

1-4. For the Record

lloyd = {

"name": "Lloyd",

"homework": [90.0, 97.0, 75.0, 92.0],

"quizzes": [88.0, 40.0, 94.0],

"tests": [75.0, 90.0]

}

alice = {

"name": "Alice",

"homework": [100.0, 92.0, 98.0, 100.0],

"quizzes": [82.0, 83.0, 91.0],

"tests": [89.0, 97.0]

}

tyler = {

"name": "Tyler",

"homework": [0.0, 87.0, 75.0, 22.0],

"quizzes": [0.0, 75.0, 78.0],

"tests": [100.0, 100.0]

}

 

students = [lloyd, alice, tyler]

 

for student in students:

print student["name"]

print student["homework"]

print student["quizzes"]

print student["tests"]

 

>> Lloyd

>> [90.0, 97.0, 75.0, 92.0]

>> [88.0, 40.0, 94.0]

>> [75.0, 90.0]

>> Alice

>> [100.0, 92.0, 98.0, 100.0]

>> [82.0, 83.0, 91.0]

>> [89.0, 97.0]

>> Tyler

>> [0.0, 87.0, 75.0, 22.0]

>> [0.0, 75.0, 78.0]

>> [100.0, 100.0]

 

설명: 변수 3개의 name, homework, quizzes, tests의 정수형 값이 들어가 있다.

students로 이 학생 3명의 정보를 묶어서 관리한다.

for 써먹을 자료 대신명 in 실제 변수

이 반복구문 형식으로 자료를 차례로 뽑아라.

 

 

1-5. It's Okay to be Average

lloyd = {

"name": "Lloyd",

"homework": [90.0, 97.0, 75.0, 92.0],

"quizzes": [88.0, 40.0, 94.0],

"tests": [75.0, 90.0]

}

alice = {

"name": "Alice",

"homework": [100.0, 92.0, 98.0, 100.0],

"quizzes": [82.0, 83.0, 91.0],

"tests": [89.0, 97.0]

}

tyler = {

"name": "Tyler",

"homework": [0.0, 87.0, 75.0, 22.0],

"quizzes": [0.0, 75.0, 78.0],

"tests": [100.0, 100.0]

}

 

def average(numbers):

total = sum(numbers)

total = float(total)

return total / len(numbers)

 

1-6. Just Weight and See

lloyd = {

"name": "Lloyd",

"homework": [90.0, 97.0, 75.0, 92.0],

"quizzes": [88.0, 40.0, 94.0],

"tests": [75.0, 90.0]

}

alice = {

"name": "Alice",

"homework": [100.0, 92.0, 98.0, 100.0],

"quizzes": [82.0, 83.0, 91.0],

"tests": [89.0, 97.0]

}

tyler = {

"name": "Tyler",

"homework": [0.0, 87.0, 75.0, 22.0],

"quizzes": [0.0, 75.0, 78.0],

"tests": [100.0, 100.0]

}

 

def average(numbers):

total = sum(numbers)

total = float(total)

return total / len(numbers)

 

def get_average(student):

homework = average(student["homework"])

quizzes = average(student["quizzes"])

tests = average(student["tests"])

 

total = homework *.1 + quizzes * .3 + tests * .6

return total

 

 

1-7. Sending a Letter

lloyd = {

"name": "Lloyd",

"homework": [90.0, 97.0, 75.0, 92.0],

"quizzes": [88.0, 40.0, 94.0],

"tests": [75.0, 90.0]

}

alice = {

"name": "Alice",

"homework": [100.0, 92.0, 98.0, 100.0],

"quizzes": [82.0, 83.0, 91.0],

"tests": [89.0, 97.0]

}

tyler = {

"name": "Tyler",

"homework": [0.0, 87.0, 75.0, 22.0],

"quizzes": [0.0, 75.0, 78.0],

"tests": [100.0, 100.0]

}

 

# Add your function below!

def average(numbers):

total = sum(numbers)

total = float(total)

return total / len(numbers)

 

def get_average(student):

homework = average(student["homework"])

quizzes = average(student["quizzes"])

tests = average(student["tests"])

 

total = homework *.1 + quizzes * .3 + tests * .6

return total

 

def get_letter_grade(score):

if score >= 90:

return "A"

elif score >= 80:

return "B"

elif score >= 70:

return "C"

elif score >= 60:

return "D"

else:

return "F"

 

print get_letter_grade(get_average(lloyd))

 

 

1-8. Part of the Whole

lloyd = {

"name": "Lloyd",

"homework": [90.0, 97.0, 75.0, 92.0],

"quizzes": [88.0, 40.0, 94.0],

"tests": [75.0, 90.0]

}

alice = {

"name": "Alice",

"homework": [100.0, 92.0, 98.0, 100.0],

"quizzes": [82.0, 83.0, 91.0],

"tests": [89.0, 97.0]

}

tyler = {

"name": "Tyler",

"homework": [0.0, 87.0, 75.0, 22.0],

"quizzes": [0.0, 75.0, 78.0],

"tests": [100.0, 100.0]

}

 

# Add your function below!

def average(numbers):

total = sum(numbers)

total = float(total)

return total/len(numbers)

 

def get_average(student):

homework = average(student["homework"])

quizzes = average(student["quizzes"])

tests = average(student["tests"])

return 0.1 * homework + 0.3 * quizzes + 0.6 * tests

 

def get_class_average(class_list):

results = []

for student in class_list:

student_avg = get_average(student)

results.append(student_avg)

return average(results)

 

 

1-9. How is Everybody Doing?

lloyd = {

"name": "Lloyd",

"homework": [90.0, 97.0, 75.0, 92.0],

"quizzes": [88.0, 40.0, 94.0],

"tests": [75.0, 90.0]

}

alice = {

"name": "Alice",

"homework": [100.0, 92.0, 98.0, 100.0],

"quizzes": [82.0, 83.0, 91.0],

"tests": [89.0, 97.0]

}

tyler = {

"name": "Tyler",

"homework": [0.0, 87.0, 75.0, 22.0],

"quizzes": [0.0, 75.0, 78.0],

"tests": [100.0, 100.0]

}

 

def average(numbers):

total = sum(numbers)

total = float(total)

return total/len(numbers)

 

def get_average(student):

homework = average(student["homework"])

quizzes = average(student["quizzes"])

tests = average(student["tests"])

return 0.1 * homework + 0.3 * quizzes + 0.6 * tests

 

def get_letter_grade(score):

if score >= 90:

return "A"

elif score >=80:

return "B"

elif score >=70:

return "C"

elif score >=60:

return "D"

else:

return "F"

 

def get_class_average(class_list):

results = []

for student in class_list:

student_avg = get_average(student)

results.append(student_avg)

return average(results)

 

students = [lloyd, alice, tyler]

class_avg = get_class_average(students)

print class_avg

print get_letter_grade(class_avg)

>> 83.8666666667

>> B

 

7. Lists and Functions

1. Lists and Functions

1-1. List accessing

n = [1, 3, 5]

print n[1] #자릿수

>> 3

 

1-2. List element modification

n = [1, 3, 5]

 

n[1] = n[1] * 5

print n

>> [1, 15, 5]

 

 

1-3. Appending to a List

n = [1, 3, 5]

n.append(4)

print n

>> [1, 3, 5, 4]

 

 

1-4. Removing elements from lists

목록에 요소 제거 하는 방법 3가지

n = [1, 3, 5]

 

1. n.remove(1)

print n

>> [3, 5]

n의 항목 중 1이라는 요소를 찾아 제거한다.

2. n.pop(1)

print n

>> [3, 5]

n의 항목 중 1을 제외시키고 나머지를 출력 시킨다.

3. del(n[0])

print n

>> [3, 5]

n의 항목 중 0번째 목록을 제거하고 출력시킨다.

 

 

1-5. Chainging the Functionality of a function

number = 5

 

def my_function(x):

return x * 3

 

print my_function(number)

>> 15

 

 

1-6. More than one argument

m = 5

n = 13

 

def add_function(x, y):

return x + y

 

print add_function(m, n)

>> 18

 

 

1-7. String in functions

n = "Hello"

 

def string_function(s):

s += "world"

return s

 

print string_function(n)

>> Helloworld

 

 

1-8. Passing a list to a function

def list_function(x):

return x

 

n = [3, 5, 7]

print list_function(n)

>> [3, 5, 7]

 

 

1-9. Using an element from a list in a function

def list_function(x):

return x[1]

 

n = [3, 5, 7]

print list_function(n)

>> 5

 

 

1-10. Modifying an element of a list in a function

def list_function(x):

x[1] = x[1] + 3

return x

 

n = [3, 5, 7]

print list_function(n)

>> [3, 8, 7]

 

 

1-11. List manipulation in functions

n = [3, 5, 7]

 

def list_extender(lst):

lst.append(9)

return lst

 

print list_extender(n)

>> [3, 5, 7, 9]

 

 

1-12. Printing out a list item by item in a function

n = [3, 5, 7]

 

def print_list(x):

for i in range(0, len(x)):

print x[i]

 

print_list(n)

>> 3

>> 5

>> 7

 

 

1-13. Modifying each element in a list in a function

n = [3, 5, 7]

 

def double_list(x):

for i in range(0, len(x)):

x[i] = x[i] * 2

return x

 

print double_list(n)

>> [6, 10, 14]

 

설명: range(5), range(0,5) 는 같다.

range(5) = 0,1,2,3,4 == range(0,5) = 0,1, 2, 3, 4

n == 3 일 때 range(0,3) == 3 # n이 3인 이유는 len 내장 함수를 사용하고 n 안에 3개의 숫자가 들어가 있기 때문.

x[3] = x[3] * 2 == x[6] 3 값 자체를 직접 지정해서 바꿀 수도 있나보다. 또는 for 문이라 순차적으로 바꾸는 것 같다.

return 6

해서 10, 14도 이와 같은 원리로 들어간다.

 

 

1-14. Passing a range into a function

n = [0, 1, 2]

 

def my_function(x):

for i in range(0, len(x)):

x[i] = x[i] * 2

return x

 

print my_function(n)

>> [0, 2, 4]

 

 

1-15. Iterating over a list in a function

리스트 반복 사용 방법

1. Method 1

for item in list:

print item

 

2. Method 2

for i in range(len(list)):

print list[i]

---------------

n = [3, 5, 7]

 

def total(numbers):

result = 0

for i in range(0,len(numbers)):

result += numbers[i]

return result

 

print total(n)

>> 15

 

# 이 방법은 왜 안될까?

n = [3, 5, 7]

 

def total(numbers):

result = 0

for item in numbers:

result += numbers[item]

return result

 

 

1-16. Using strings in in lists in functions

n = ["Michael", "Lieberman"]

 

def join_strings(words):

result = ""

for i in range(0,len(words)):

result = result + words[i]

return result

 

print join_strings(n)

>> MichaelLieberman

 

설명 : 이 형식을 사용하면 맞게끔 결과가 출력된다.

result에 숫자를 담는다면 0으로 초기화.

result에 문자로 담는다면 ""으로 초기화.

result에 배열로 담는다면 []으로 초기화.

 

 

1-17. Using two lists as two arguments in a function

m = [1, 2, 3]

n = [4, 5, 6]

 

def join_lists(x, y):

return x + y

 

print join_lists(m, n)

>> [1, 2, 3, 4, 5, 6]

 

 

1-18. Using a list of lists in a function

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

 

def flatten(lists):

results = []

for numbers in lists:

for number in numbers:

results.append(number)

return results

 

print flatten(n)

>> [1, 2, 3, 4, 5, 6, 7, 8, 9]

 

설명 : def flatten 이라는 함수에 n이라는 정수의 값을 입력받는다.

이 n 값을 lists라는 다른 이름으로 대신 받아서 함수 안에서 작동한다.

lists 값을 numbers 라는 변수에 넣어서 사용한다.

다시 numbers의 값을 number 라는 변수에 넣어서 사용한다.

results number 를 추가한다.

하나 하나 풀어줌으로써 마지막에 results에 담고 이 값을 return 해준다.

 

 

2. Battleship!

2-2. Getting Our Feet Wet

board = []

 

 

2-3. Make a List

board = []

for i in range(5):

board.append(['O'] * 5)

 

 

2-4. Check it Twice

board = []

for i in range(5):

board.append(['O'] * 5)

print board

>>[['O', 'O', 'O', 'O', 'O']]

>> [['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]

>> [['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]

>> [['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']] [['O', 'O', 'O', 'O', 'O'], >> ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]

 

 

2-5. Custom Print

board = []

 

for i in range(5):

board.append(["O"] * 5)

 

def print_board(board_in):

for row in board:

print row

 

print_board(board)

 

>> ['O', 'O', 'O', 'O', 'O']

>> ['O', 'O', 'O', 'O', 'O']

>> ['O', 'O', 'O', 'O', 'O']

>> ['O', 'O', 'O', 'O', 'O']

>> ['O', 'O', 'O', 'O', 'O']

설명: 여기서 range 수를 늘리면 행이 증가하고 .append(["O"] * 5)는 열이 늘어난다.

 

 

2-6. Printing Pretty

board = []

 

for i in range(5):

board.append(["O"] * 5)

 

def print_board(board_in):

for row in board:

print " ".join(row)

 

print_board(board)

>> O O O O O

>> O O O O O

>> O O O O O

>> O O O O O

>> O O O O O

 

 

2-7. Hide...

from random import randint

board = []

 

for x in range(0, 5):

board.append(["O"] * 5)

 

def print_board(board_in):

for row in board:

print " ".join(row)

 

def random_row(board_in):

return randint(0, len(board_in) - 1)

 

def random_col(board_in):

return randint(0, len(board_in) - 1)

 

random_row(board)

random_col(board)

 

 

2-8. ...and seek!

from random import randint

 

board = []

 

for x in range(0, 5):

board.append(["O"] * 5)

 

def print_board(board):

for row in board:

print " ".join(row)

 

def random_row(board):

return randint(0, len(board) - 1)

 

def random_col(board):

return randint(0, len(board[0]) - 1)

 

ship_row = random_row(board)

ship_col = random_col(board)

 

guess_row = int(raw_input("Guess Row: ")) # 입력받을 수 있음.

guess_col = int(raw_input("Guess Col: ")) # 입력받을 수 있음.

 

 

2-9. It's Not Cheating-It's Debugging!

from random import randint

 

board = []

 

for x in range(0, 5):

board.append(["O"] * 5)

 

def print_board(board):

for row in board:

print " ".join(row)

 

def random_row(board):

return randint(0, len(board) - 1)

 

def random_col(board):

return randint(0, len(board[0]) - 1)

 

ship_row = random_row(board)

ship_col = random_col(board)

 

print ship_row

print ship_col

 

guess_row = int(raw_input("Guess Row: "))

guess_col = int(raw_input("Guess Col: "))

>> 무작위로 숫자나옴1(1,2 합 5 이하)

>> 무작위로 숫자나옴2(1, 2 합 5 이하)

>> Guess Row: 입력

>> Guess Col: 입력

 

 

2-10. You win!

from random import randint

 

board = []

 

for x in range(0, 5):

board.append(["O"] * 5)

 

def print_board(board):

for row in board:

print " ".join(row)

 

print_board(board)

 

def random_row(board):

return randint(0, len(board) - 1)

 

def random_col(board):

return randint(0, len(board[0]) - 1)

 

ship_row = random_row(board)

ship_col = random_col(board)

print ship_row

print ship_col

 

guess_row = int(raw_input("Guess Row: "))

guess_col = int(raw_input("Guess Col: "))

 

if guess_row == ship_row and guess_col == ship_col:

print "Congratulations! You sank my battleship!"

#0행 ~ 4행, 0열 ~ 4열.

>> O O O O O

>> O O O O O

>> O O O O O

>> O O O O O

>> O O O O O

>> 4

>> 2

>> Guess Row: 4

>> Guess Col: 2

>> Congratulations! You sank my battleship!(똑같이 숫자를 내가 입력했을 때 나옴.)

 

 

2-11. Danger, Will Robinson!!

from random import randint

 

board = []

 

for x in range(0, 5):

board.append(["O"] * 5)

 

def print_board(board):

for row in board:

print " ".join(row)

 

print_board(board)

 

def random_row(board):

return randint(0, len(board) - 1)

 

def random_col(board):

return randint(0, len(board[0]) - 1)

 

ship_row = random_row(board)

ship_col = random_col(board)

print ship_row

print ship_col

guess_row = int(raw_input("Guess Row: "))

guess_col = int(raw_input("Guess Col: "))

 

if guess_row == ship_row and guess_col == ship_col:

print "Congratulations! You sank my battleship!"

else:

print "You missed my battleship!"

board[guess_row][guess_col] = "X"

print_board(board)

>> O O O O O

>> O O O O O

>> O O O O O

>> O O O O O

>> O O O O O

>> 3

>> 1

>> Guess Row: 1

>> Guess Col: 2

>> You missed my battleship!

>> O O O O O

>> O O X O O

>> O O O O O

>> O O O O O

>> O O O O O

# 숫자를 정확히 3,1 과 맞게 입력하면 그냥 콩그레츄로 끝남.

 

 

2-12. Bad Aim

# else안에 추가해줬다.

if guess_row == ship_row and guess_col == ship_col:

print "Congratulations! You sank my battleship!"

else:

if guess_row not in range(5) or \

guess_col not in range(5):

print "Oops, that's not even in the ocean."

else:

print "You missed my battleship!"

board[guess_row][guess_col] = "X"

print_board(board)

 

 

2-13. Not Again!

# elif를 추가했다. ()으로 묶어줘야 한다.

if guess_row == ship_row and guess_col == ship_col:

print "Congratulations! You sank my battleship!"

else:

if guess_row not in range(5) or \

guess_col not in range(5):

print "Oops, that's not even in the ocean."

elif (board[guess_row][guess_col] == 'X'):

print "You guessed that one already."

else:

print "You missed my battleship!"

board[guess_row][guess_col] = "X"

print_board(board)

 

 

2-14. Test Run

Test Turn

 

 

2-15. Play It, Sam

#for를 추가해 주었다.

for turn in range(4):

print "Turn", turn + 1

guess_row = int(raw_input("Guess Row: "))

guess_col = int(raw_input("Guess Col: "))

 

if guess_row == ship_row and guess_col == ship_col:

print "Congratulations! You sank my battleship!"

else:

if guess_row not in range(5) or \

guess_col not in range(5):

print "Oops, that's not even in the ocean."

elif board[guess_row][guess_col] == "X":

print( "You guessed that one already." )

else:

print "You missed my battleship!"

board[guess_row][guess_col] = "X"

print_board(board)

 

 

2-16. Game Over

#else에 else에 if를 추가해 주었다.

for turn in range(4):

print "Turn", turn + 1

guess_row = int(raw_input("Guess Row: "))

guess_col = int(raw_input("Guess Col: "))

 

if guess_row == ship_row and guess_col == ship_col:

print "Congratulations! You sank my battleship!"

else:

if guess_row not in range(5) or \

guess_col not in range(5):

print "Oops, that's not even in the ocean."

elif board[guess_row][guess_col] == "X":

print( "You guessed that one already." )

else:

print "You missed my battleship!"

board[guess_row][guess_col] = "X"

if turn == 3:

print "Game Over"

 

print_board(board)

 

 

2-17. A Real Win

# break 추가. if 조건 맞으면 출력 후 더 이상 진행 안함.

# 상대 전함 좌표 값 나오고 그에 맞게 입력하면 침몰. 아니면 루프로 계속 반복해서 찾음.

from random import randint

 

board = []

 

for x in range(0, 5):

board.append(["O"] * 5)

 

def print_board(board):

for row in board:

print " ".join(row)

 

print_board(board)

 

def random_row(board):

return randint(0, len(board) - 1)

 

def random_col(board):

return randint(0, len(board[0]) - 1)

 

ship_row = random_row(board)

ship_col = random_col(board)

print ship_row

print ship_col

 

for turn in range(4):

print "Turn", turn + 1

guess_row = int(raw_input("Guess Row: "))

guess_col = int(raw_input("Guess Col: "))

 

if guess_row == ship_row and guess_col == ship_col:

print "Congratulations! You sank my battleship!"

break

else:

if guess_row not in range(5) or \

guess_col not in range(5):

print "Oops, that's not even in the ocean."

elif board[guess_row][guess_col] == "X":

print( "You guessed that one already." )

else:

print "You missed my battleship!"

board[guess_row][guess_col] = "X"

if (turn == 3):

print "Game Over"

 

print_board(board)

 

8. Loops

1. Loops

1-1. While you're here

#while문은 반복되지만 if문은 반복되지 않는다.

count = 0

 

if count < 5:

print "Hello, I am an if statement and count is", count

 

while count < 10:

print "Hello, I am a while and count is", count

count += 1

 

>> Hello, I am an if statement and count is 0

>> Hello, I am a while and count is 0

>> Hello, I am a while and count is 1

>> Hello, I am a while and count is 2

>> Hello, I am a while and count is 3

>> Hello, I am a while and count is 4

>> Hello, I am a while and count is 5

>> # ... 9 까지 반복됩니다.

 

 

1-2. Condition

loop_condition = True

 

while loop_condition:

print "I am a loop"

loop_condition = False

>> I am a loop

# 변수 값을 참으로 하고 while문을 돌렸다. print 하고 나서 변수 값을 거짓으로 바꾸지 않으면

무한 반복 되기 때문에 마지막 줄엔 False로 해 두었다. 항상 참이라면 계속 실행해야 하기 때문이다.

 

 

1-3. While you're at it

num = 1

 

while num <= 10:

print num ** 2

num += 1

>> 1

>> 4

>> 9

>> 16

>> 25

>> 36

>> 49

>> 64

>> 81

>> 100

# num 변수를 1 ~ 10 까지 반복하면서 num의 제곱값을 프린트한다.

그리고 num을 1씩 증가한다.

 

 

1-4. Simple errors

choice = raw_input('Enjoying the course? (y/n)')

 

while choice != 'y' and choice != 'n':

choice = raw_input("Sorry, I didn't catch that. Enter again: ")

설명: y와 n 중 선택. choice 변수가 y 그리고 n 과 다르다면 choice에 다시 입력해야 한다.

 

 

1-5. Infinite loops

count = 0

 

while count < 10:

print count

count += 1

# -= 로 바꾸면 사이트가 렉 걸려서 계정에 혼란이 온다.

 

 

1-6. Break

count = 0

 

while True:

print count

count += 1

if count >= 10:

break

>> 0

>> 1

>> ..

>> 9 까지 출력 됨.

설명: count 는 0. while 값은 무조건 참. 계속 실행.

count 출력하고 1씩 더한다. count가 10이상이면 브레이크.

 

 

1-7. While / else

import random

 

print "Lucky Numbers! 3 numbers will be generated."

print "If one of them is a '5', you lose!"

 

count = 0

while count < 3:

num = random.randint(1, 6)

print num

if num == 5:

print "Sorry, you lose!"

break

count += 1

else:

print "You win!"

 

설명: while 조건으로 3번에 한정한다. 3번 반복 가능.

num 변수에 1 ~ 6 사이 랜덤한 정수 값을 담는다.

print한다. 만약 num이 5와 같으면 내가 졌다고 출력이 되고 break 된다.

5가 아닐 경우 count가 1씩 올라가서 다음 반복을 시작한다. 3번 안에 5가 안 나오면 내 승이다.

 

 

1-8. Your own while / else

from random import randint

 

random_number = randint(1, 10)

 

guesses_left = 3

 

while guesses_left > 0:

guess = int(raw_input("Your guess: "))

if guess == random_number:

print "You win!"

break

guesses_left -= 1

else:

print "You lose."

 

설명: random 모듈에 randint 함수를 쓴다.

randint: 두 정수 사이의 어떤 랜덤한 정수(난수)를 리턴시켜주는 함수

random_number 라는 변수에 1 ~10 사이의 난수 값을 받는다.

guesses_left 할당 값은 3이고 3 > 0 보다 크니 guess 변수에 int 값으로 입력을 받는다.

만약 내가 직접 입력한 guess 값이 random_number 변수에 난수값과 일치한다면 나의 승리고 break 된다.

아닐 경우 -1 씩 추가해서 3번의 기회에서 떨어지면 나의 패배다. 추측 값과 내 값 비교해서 맞춰보기.

 

 

1-9. For your health

print "Counting..."

 

for i in range(20):

print i

>> 0

>> 1

>> ..

>> 19 까지 출력.

 

 

1-10. For your hobbies

hobbies = []

 

for i in range(3):

hobby = raw_input(">>: ")

hobbies.append(hobby)

 

print hobbies

설명: for에 range 사용해서 3번(?) 입력 받는다.

hobby 변수에 입력 값을 받을 수 있게 한다.

내가 입력한 값을 hobbies 배열에 .append로 추가한다.

print

 

 

1-11. For your strings

thing = "spam!"

 

for c in thing:

print c

 

word = "eggs!"

 

for character in word:

print character

>> s

>> p

>> a

>> m

>> !

>> e

>> g

>> g

>> s

>> !

 

 

1-12. For your A

phrase = "A bird in the hand..."

 

for char in phrase:

if char == "A" or char == "a":

print "X",

else:

print char,

 

#Don't delete this print statement!

print

>> X b i r d i n t h e h X n d . . .

설명: print 하고 문자 뒤에 , 를 붙였더니 X로 대체가 된다. tip: ,

 

 

1-13. For your lists

numbers = [7, 9, 12, 54, 99]

 

print "This list contains: "

 

for num in numbers:

print num

 

for num in numbers:

print num ** 2

>> 7

>> 9

>> 12

>> 54

>> 99

>> 49

>> 81

>> 144

>> 2916

>> 9801

설명: 반복문을 통해 리스트 숫자를 나열한다.

두번째 반복문은 제곱값을 이용하여 나열한다.

 

 

1-14. Looping over a dictionary

# 예제

d = {'x': 9, 'y': 10, 'z': 20}

for key in d:

if d[key] == 10:

print "This dictionary has the value 10!"

----------------------------------------------------------------

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

 

for key in d:

print key, d[key]

>> a apple

>> c cherry

>> b berry

설명: key는 a, b, c이고

d[key]는 apple, berry, cherry이다.

 

 

1-15. Counting as you go

choices = ['pizza', 'pasta', 'salad', 'nachos']

 

print 'Your choices are:'

for index, item in enumerate(choices):

print index + 1, item

>> Your choices are:

>> 1 pizza

>> 2 pasta

>> 3 salad

>> 4 nachos

 

 

1-16. Multiple lists

list_a = [3, 9, 17, 15, 19]

list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

# max 두 정수 값 중 최대값 비교하여 출력.

for a, b in zip(list_a, list_b):

print max(a, b)

>> 3

>> 9

>> 17

>> 15

>> 30

 

 

1-17. For / else

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

# tomato 뒤 부터는 출력이 나오지 않는다. pear와 grape를 tomato 앞으로 이동 시켜서 출력해 보았더니 그제서야 나온다.

print 'You have...'

for f in fruits:

if f == 'tomato':

print 'A tomato is not a fruit!' # (It actually is.)

break

print 'A', f

else:

print 'A fine selection of fruits!'

 

>> You have...

>> A banana

>> A apple

>> A orange

>> A tomato is not a fruit!

 

 

1-18. Change it up

# else가 출력되게 하라는 것 같다. if 의 조건 값을 바꿔주었다.

 

 

1-19. Create your own

N = {'k': 'korea', 'c': 'china', 'j': 'japan'}

 

for key in N:

if N[key] == "korea":

print "123"

elif key == 'c':

print "456"

else:

print "789"

 

>> 123

>> 789

>> 456

 

 

2. Practice Makes Perfect

2-2. is_even

def is_even(x):

if x % 2 == 0:

return True

else:

return False

 

 

2-3. is_int (No 이해)

def is_int(x):

absolute = abs(x)

rounded = round(absolute)

return absolute - rounded == 0

 

 

2-4. digit_sum (No 이해)

def digit_sum(x):

total = 0

while x > 0:

total += x % 10

x = x // 10

print x

return total

 

digit_sum(1234)

>> 123

>> 12

>> 1

>> 0

 

 

2-5. factorial (No 이해 하는 의도 모름.)

def factorial(x):

total = 1

while x > 0:

total *= x

x -= 1

return total

 

# 팩토리얼 설명

factorial(4) would equal 4 * 3 * 2 * 1, which is 24.

factorial(1) would equal 1.

factorial(3) would equal 3 * 2 * 1, which is 6.

 

 

2-6. is_prime (No 이해)

def is_prime(x):

if x < 2:

return False

else:

for n in range(2, x-1):

if x % n == 0:

return False

return True

 

 

2-7. reverse (No 이해)

def reverse(text):

word = ""

l = len(text) - 1

while l >= 0:

word = word + text[l]

l -= 1

return word

 

 

2-8. anti_vowel(영어에서 모음을 제거해서 출력해준다.)

def anti_vowel(text):

t=""

for c in text:

for i in "ieaouIEAOU":

if c==i:

c=""

else:

c=c

t=t+c

return t

 

print anti_vowel("Good boy")

>>Gd by

 

설명

1. text 입력 값이 C라는 변수 이름으로 통제한다.

2. 아에이오유(모음) 소문자, 대문자를 for in 을 사용하여 텍스트 하나하나 비교 할 수 있다.

3. c 값이 i 와 같다면(모음이) c를 공백으로 출력하라.

4. 아닐 경우 c에 c 값을 그대로 넣는다.

 

모음이 들어 있다면 c 값에 공백을 넣어라.(제거)

모음이 없으면 c에 값을 그대로 c에 넣는다.(유지)

빈 텍스트 공간인 t에 모음값을 제거한 c를 넣어준다.

return 하면 모음 값을 제거해서 출력해준다.

 

 

2-9. scrabble_score

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,

"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,

"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,

"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,

"x": 8, "z": 10}

 

def scrabble_score(text):

text = text.lower()

total = 0

for t in text:

for sc in score:

if sc == t:

total += score[sc]

return total

 

print scrabble_score("freedom")

>> 13

 

설명: 내가 영어를 입력하면(대소문자 구분 없게) 그에 맞게 값을 합해서 더해주는 기능을 한다. 스크래블 게임?

score 배열 안에 영어 소문자에 정수값이 들어가 있다.

def 함수를 만들어준다.

영어 대소문자 구분 없게 만들려면 내가 입력한 값을 소문자화 시켜주어야 한다.(.lower()사용)

total에 담을 공간을 만들어준다. 변수 선언 초기화.

내가 입력한 text 값을 t 라는 변수로 사용한다.

t 안에서 score에 값을 sc로 사용한다.

만약 sc의 앞에 영어와 내가 입력한 text 값이 같다면

total에 그 값을 더해서 담는다. score에 정수 값을 다 담는거 아니냐라고 생각할 수도 있는데,

for in은 하나하나 비교 하는 것이기 때문에 하나씩 알맞게 score[sc]가 담아준다.(모르면 FOR IN 참고.)

값을 반환해준다.

 

 

2-10. censor

def censor(text, word):

words = text.split()

result = ''

stars = '*' * len(word)

count = 0

for i in words:

if i == word:

words[count] = stars

count += 1

result =' '.join(words)

 

return result

 

print censor("this hack is wack hack", "hack")

>> this **** is wack ****

 

설명: hack이란 단어를 모자이크 처리할 것이다.

censor 함수에 text와 word 변수 2개를 받는다.

words인 2번째 변수를 모자이크 값으로 받을 것이다.(.split() 사용법 참고!)

result 빈 문자 공간 확보.

stars 변수는 모자이크 변수다. word가 "hack"일시 len(word) == 4. 내가 처리 요청한 것에 맞게 *이 나온다.

count 해야 하기 때문에 변수 선언 및 0으로 초기화.

word를 모자이크 해야 하니 in의 변수로 사용한다.

words 문자 번호마다 카운트하며 별을 넣는다.

카운트 1씩 증가.

결과를 담은 후 리턴한다.

 

 

2-11. count

def count(sequence, item):

count = 0

for i in sequence:

if i == item:

count += 1

return count

 

print count([1, 2, 1, 1], 1)

>> 3

설명: count라는 함수에 sequence와 item 이라는 두 변수 값을 받는다.

count 변수 0으로 선언 및 초기화.

sequence 배열 사용한다.

만약 i의 변수(sequence 자료)가 item과 같다면

count를 1씩 증가해서 저장한다. 다 끝나면 리턴하여 반환한다.

item에 1과 sequence에 1이 3개 같으니 카운트가 하나씩 증가하여 3을 반환했다.

 

 

2-12. purify

# 배열 중 짝수만 뽑아내서 출력.

def purify(lst):

res = []

for ele in lst:

if ele % 2 == 0:

res.append(ele)

return res

 

print purify([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

>> [2, 4, 6, 8, 10]

 

설명: purify 함수에 변수로 받는다.

res변수 안 배열에 따로 저장해서 출력할 것이다.

lst 배열을 ele라는 변수로 사용한다. lst 값 하나하나가 ele라는 변수로 사용된다.

만약 ele를 2로 나누어서 딱 맞아 떨어지면 짝수다.

res.append(ele)로 ele에 추가한다.

return 한다.

 

 

2-13. product

def product(num):

result = 1

for hap in num:

result = result * hap

return result

 

print product([4, 5, 5])

>> 100

 

설명: 내가 입력한 모든 값을 곱해주는 기능을 한다.

product라는 함수를 만들고 num이라는 함수 안에서의 가상의 변수를 만든다.

result 를 1로 초기화 하였다. 0으로 초기화 할시 0과 곱셈하면 결과 값이 안나오기 때문이다.

내가 입력한 값 하나 하나 나와야 하기 때문에 for in 을 사용 하였다.

배열 값인 num을 hap이라는 변수 하나하나로 사용할 수 있게 한다.

result에 값을 저장하고 return한다.

 

 

2-14. remove_duplicates(No 이해)

# 중복 값 제거.

def remove_duplicates(inputlist):

if inputlist == []:

return []

 

 

inputlist = sorted(inputlist)

 

outputlist = [inputlist[0]]

 

 

for i in inputlist:

if i > outputlist[-1]:

outputlist.append(i)

 

return outputlist

print remove_duplicates([1, 1, 2, 2])

>> [1, 2]

 

 

2-15. median

def median(lst):

sorted_list = sorted(lst)

if len(sorted_list) % 2 != 0:

index = len(sorted_list)//2

return sorted_list[index]

 

elif len(sorted_list) % 2 == 0:

index_1 = len(sorted_list)/2 - 1

index_2 = len(sorted_list)/2

mean = (sorted_list[index_1] + sorted_list[index_2])/2.0

return mean

 

print median([1, 2, 3, 4, 5])

print median([3, 4, 5, 6, 7, 8, 9])

>> 3

>> 6

 

 

9. Exam Statistics

1. Exam Statistics

1-2. Print those grades

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

 

def print_grades(grades_input):

for grade in grades_input:

print grade

 

print_grades(grades)

>> 100

>> 100

>> 90

>> .. 차례대로 계속 나열

>> 50.5

설명: grades를 순서대로 나열한다. grades_input의 배열을 변수 하나 하나 받아 사용한다. print.

 

 

1-4. The sum of scores (정수 함수 만들기.)

# 정수를 다 합하는 함수.

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

 

def grades_sum(scores):

result = 0

for su in scores:

result += su

return result

 

print grades_sum(grades)

>> 1045.5

설명: grades를 인자 값으로 사용하여 for에 사용한다. scores의 배열을 변수 하나하나로 사용하기 위해 su 변수 만듬.

 

 

1-5. Computing the Average (나누기 함수 만들기.)

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

# 합해주는 함수.

def grades_sum(scores):

result = 0

for su in scores:

result += su

return result

print grades_sum(grades)

 

# 평균값을 내주는 함수.

def grades_average(grades_input):

hap = grades_sum(grades_input)

avg = hap / float(len(grades_input))

return avg

print grades_average(grades)

 

>> 1045.5

>> 80.4230769231

 

설명: 합해주는 함수를 이용해서 평균값을 내려고 한다.

grades_sum이라는 함수를 만들고 인자 값을 grades로 받는다.

hap이라는 새로운 변수에 grades_sum 함수를 이용하고 grades_input(받은 값 = grades)를 받으면 정수 값이 합쳐진다.

avg에 hap 나누기 실수형으로 grades_input의 길이(여기서 길이 == 등급 수)를 이용하여 나눈다.

avg에 계산된 값이 들어가고 리턴 시킨다.

 

 

1-7. The Variance(분산 함수 만들기.)

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

 

def grades_sum(scores):

total = 0

for score in scores:

total += score

return total

 

def grades_average(grades_input):

sum_of_grades = grades_sum(grades_input)

average = sum_of_grades / float(len(grades_input))

return average

 

def grades_variance(scores):

average = grades_average(scores)

variance = 0

for score in scores:

variance += (average - score) ** 2

return variance / len(scores)

 

print grades_variance(grades)

>> 334.071005917

설명: 평균(average) 변수를 만들고 함수로 값을 받게 한다.

분산(variance) 변수를 0으로 선언 및 초기화.

반복문을 사용하여 분산 공식을 사용해 저장한다.

 

 

1-8. Standard Deviation

이건 되고

def grades_std_deviation(variance):

return variance ** 0.5

 

variance = grades_variance(grades)

 

print grades_std_deviation(variance)

 

이건 안된다.

def grades_std_deviation(variance):

return variance ** 0.5

 

variance = grades_variance(variance)

 

print grades_std_deviation(grades)

 

내가 생각한건 2번째 경우다. grades 값을 받아서 함수를 실행 시키기 때문에 variance라는 함수 안에서의 변수가 grades의 값을

받아서 사용이 되니 grades_variance에 들어가는 값도 variance라고 생각을 했다.

하지만 variance는 grades_variance 함수에서 사용되는 변수 이름과 같기 때문에 오류가 나는 것 같다.

 

그런데 print grades_std_deviation(variance) 에서 variance 값의 출처를 모르겠다 ㅜㅜ.

 

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

 

def print_grades(grades_input):

for grade in grades_input:

print grade

 

def grades_sum(scores):

total = 0

for score in scores:

total += score

return total

 

def grades_average(grades_input):

sum_of_grades = grades_sum(grades_input)

average = sum_of_grades / float(len(grades_input))

return average

 

def grades_variance(grades):

variance = 0

for number in grades:

variance += (grades_average(grades) - number) ** 2

return variance / len(grades)

 

def grades_std_deviation(variance):

return variance ** 0.5

 

variance = grades_variance(grades)

 

print grades_std_deviation(variance)

>> 18.2776094147

 

 

1-9. Review

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

 

def print_grades(grades_input):

for grade in grades_input:

print grade

 

print_grades(grades)

 

def grades_sum(scores):

total = 0

for score in scores:

total += score

return total

 

print grades_sum(grades)

 

def grades_average(grades_input):

sum_of_grades = grades_sum(grades_input)

average = sum_of_grades / float(len(grades_input))

return average

 

print grades_average(grades)

 

def grades_variance(grades):

variance = 0

for number in grades:

variance += (grades_average(grades) - number) ** 2

return variance / len(grades)

 

print grades_variance(grades)

 

def grades_std_deviation(variance):

return variance ** 0.5

 

variance = grades_variance(grades)

 

print grades_std_deviation(variance)

>> 100

>> 100

>> 90

>> 40

>> 80

>> 100

>> 85

>> 70

>> 90

>> 65

>> 90

>> 85

>> 50.5

>> 1045.5

>> 80.4230769231

>> 334.071005917

>> 18.2776094147

 

 

10. Advanced Topics in Python

1. Advanced Topics in Python

1-1. Iterators for Dictionaries

my_dict = {

"Name": "Creator",

"Age": 59,

"BDFL": True

}

print my_dict.items()

>> [('BDFL', True), ('Age', 59), ('Name', 'Creator')]

 

 

1-2. keys() and values()

my_dict = {

"Name": "Creator",

"Age": 59,

"BDFL": True

}

print my_dict.keys()

print my_dict.values()

 

>> ['BDFL', 'Age', 'Name']

>> [True, 59, 'Creator']

 

 

1-3. The 'in' Operator

my_dict = {

"Name": "Creator",

"Age": 59,

"BDFL": True

}

 

for key in my_dict:

print key, my_dict[key]

 

>> BDFL True

>> Age 59

>> Name Creator

 

 

1-4. Building Lists

evens_to_50 = [i for i in range(51) if i % 2 == 0]

print evens_to_50

>> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]

설명: range 함수로 인해 0 ~ 50 까지 정수가 들어간다. for 전에 i가 있는데 변수를 선언 해준 것 같다.

if문을 통해 비교한다. 나눴을 때 나머지가 0으로 딱 맞아 떨어진다면 프린트 하는 것이다.

for in과 range 함수를 통해 0 ~ 50 까지 반복되며 비교해서 프린트한다.

 

 

1-5. List Comprehension Syntax

doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0]

x = 1 일 때 2 X

x = 2 일 때 4 X

x = 3 일 때 6 O

x = 4 일 때 8 X

x = 5 일 때 10 X

 

 

even_squares = [x ** 2 for x in range(1, 12) if x % 2 == 0]

 

print even_squares

>> [4, 16, 36, 64, 100]

 

x = 2일 때 제곱값 4, 나머지 값 0 O

x = 3일 때 제곱값 9, 나머지 값 1 X

x = 4일 때 제곱값 16, 나머지 값 0 O

x = 5일 때 제곱값 25, 나머지 값 1 X

x = 6일 때 제곱값 36, 나머지 값 0 O

x = 7일 때 제곱값 49, 나머지 값 1 X

x = 8일 때 제곱값 64, 나머지 값 0 O

x = 9일 때 제곱값 81, 나머지 값 1 X

x = 10일 때 제곱값 100, 나머지 값 0 O

x = 11일 때 제곱값 121, 나머지 값 1 X

 

 

1-6. Now You Try!

예) c = ['C' for x in range(5) if x < 3]

print c

>> ['C', 'C', 'C']

 

cubes_by_four = [x ** 3 for x in range(1, 11) if ((x ** 3) % 4) == 0]

print cubes_by_four

x = 2, 4, 6, 8, 10

>> [8, 64, 216, 512, 1000]

 

 

1-7. List Slicing Syntax

l = [i ** 2 for i in range(1, 11)]

# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print l[2:9:2]

>> [9, 25, 49, 81]

설명: 2번째 순서부터(0부터 시작.) 시작 해서 9번째에 끝. 2번 뛴다.

 

 

1-8. Omitting Indices

my_list = range(1, 11) # List of numbers 1 - 10

 

# print my_list[9:]

# print my_list[:5]

# print my_list[2:10:3]

print my_list[::2]

# >> [10]

# >> [1, 2, 3, 4, 5]

# >> [3, 6, 9]

>> [1, 3, 5, 7, 9]

 

 

1-9. Reversing a List

my_list = range(1, 11)

backwards = my_list[::-1]

 

print backwards

>> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

 

 

1-10. Stride Length

to_one_hundred = range(101)

 

backwards_by_tens = to_one_hundred[::-10]

print backwards_by_tens

 

>> [100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0]

 

1-11. Practice Makes Perfect

# 조건. to_21 범위 1 ~21, 2번째 변수 만들어서 1, 3, 5 순으로 정렬, 3번째 변수 만들어서 8 ~ 14 까지 출력.

to_21 = range(1,22)

odds = to_21[::2]

middle_third = to_21[7:14]

 

print to_21

print odds

print middle_third

 

>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]

>> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]

>> [8, 9, 10, 11, 12, 13, 14]

 

 

1-12. Anonymous Functions (람다 함수 첫 등장.)

my_list = range(16)

 

print filter(lambda x: x % 3 == 0, my_list)

>> [0, 3, 6, 9, 12, 15]

 

 

1-13. Lambda Syntax

languages = ["HTML", "JavaScript", "Python", "Ruby"]

 

print filter(lambda x: x == "Python", languages)

>> ['Python']

 

 

1-14. Try it!

squares = [x ** 2 for x in range(1, 11)]

 

print filter(lambda x: x >= 30 and x <= 70, squares)

>> [36, 49, 64]

설명: squares의 범위를 1 ~ 10으로 정하고 제곱을 받는다.

30 이상 70 이하의 범위의 조건을 만족하는 수를 뽑아라.

1 ** 2 == 1,  6 ** 2 == 36

2 ** 2 == 4,  7 ** 2 == 49

3 ** 2 == 9,  8 ** 2 == 64

4 ** 2 == 16,  9 ** 2 == 81

5 ** 2 == 25, 10 ** 2 == 100

 

 

1-15. Iterating Over Dictionaries

movies = {

"Monty Python and the Holy Grail": "Great",

"Monty Python's Life of Brian": "Good",

"Monty Python's Meaning of Life": "Okay"

}

 

print movies(틀이랑 자료 값 전부 출력.)

>> {"Monty Python's Life of Brian": 'Good', "Monty Python's Meaning of Life": 'Okay', 'Monty Python and the Holy Grail': 'Great'}

 

print movies.items()(그 안에 자료값만 출력.)

>> [("Monty Python's Life of Brian", 'Good'), ("Monty Python's Meaning of Life", 'Okay'), ('Monty Python and the Holy Grail', 'Great')]

 

 

1-16. Comprehending Comprehensions

# 1 ~ 15 사이 3 또는 5의 배수

threes_and_fives = [x for x in range(1, 16) if x % 3 == 0 or x % 5 == 0]

print threes_and_fives

>> [3, 5, 6, 9, 10, 12, 15]

 

# 람다 이용

threes_and_fives = [x for x in range(1, 16)]

print filter(lambda x: x % 3 == 0 or x % 5 == 0, threes_and_fives)

>> [3, 5, 6, 9, 10, 12, 15]

 

 

1-17. List Slicing (신기)

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"

 

message = garbled[::-2]

 

print message

>> I am the secret message!

 

# message = garbled[-1::-2]

# print message

# >> I am the secret message!

 

message = garbled[-1::-2] 와 message = garbled[::-2] 왜 둘이 같은지 이해가 안간다.

 

 

1-18. Lambda Expressions

garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"

# 필터 기능을 이용하여 조건문을 통해 X와 다른 것만 출력시키게 한 것이다.

message = filter(lambda x: x != "X", garbled)

print message

>> I am another secret message!

 

 

2. Introduction to Bitwise Operators

이번 코스는 비트 연산자의 계산 방법을 배우게 된다.

2-1. Just a Little BIT

print 5 >> 4 # Right Shift

print 5 << 1 # Left Shift

print 8 & 5 # Bitwise AND

print 9 | 4 # Bitwise OR

print 12 ^ 42 # Bitwise XOR

print ~88 # Bitwise NOT

>> 0

>> 10

>> 0

>> 13

>> 38

>> -89

 

 

2-2. Lesson I0: The Base 2 Number System

8's bit 4's bit 2's bit 1's bit

1 0 1 0

8 + 0 + 2 + 0 = 10

----------------------------------------------------------------

print 0b1, #1

print 0b10, #2

print 0b11, #3

print 0b100, #4

print 0b101, #5

print 0b110, #6

print 0b111 #7

print "******"

print 0b1 + 0b11

print 0b11 * 0b11

>> 1 2 3 4 5 6 7

>> ******

>> 4

>> 9

 

 

2-3. I Can Count to 1100!(파이썬 이진법)

# 컴퓨터는 이진법으로 생각한다.

ex)

2 ** 0 = 1

2 ** 1 = 2

2 ** 2 = 4

2 ** 3 = 8

2 ** 4 = 16

2 ** 5 = 32

2 ** 6 = 64

2 ** 7 = 128

2 ** 8 = 256

2 ** 9 = 512

2 ** 10 = 1024

----------------------

one = 0b1

two = 0b10

three = 0b11

four = 0b100

five = 0b101

six = 0b110

seven = 0b111

eight = 0b1000

nine = 0b1001

ten = 0b1010

eleven = 0b1011

twelve = 0b1100

 

 

print one

print two

print three

print four

print five

print six

print seven

print eight

print nine

print ten

print eleven

print twelve

 

>> 1

>> 2

>> 3

>> 4

>> 5

>> 6

>> 7

>> 8

>> 9

>> 10

>> 11

>> 12

 

 

2-4. The bin() Function

# bin(): 문자열의 이진수 표현을 반환.

print bin(2)

print bin(3)

print bin(4)

print bin(5)

 

>> 0b10

>> 0b11

>> 0b100

>> 0b101

 

 

2-5. int()'s Second Parameter

# int('x', n) : n진수 x를 10진수로 변환

print int("1",2)

print int("10",2)

print int("111",2)

print int("0b100",2)

print int(bin(5),2)

 

print int("11001001", 2)

>> 1

>> 2

>> 7

>> 4

>> 5

>> 201

 

 

2-6. Slide to the Left! Slide to the Right!

<< : 비트를 지정된 수만큼 왼쪽으로 이동시킨다.

>> : 비트를 지정된 수만큼 오른쪽으로 이동시킨다.

shift_right = 0b1100

shift_left = 0b1

 

# Your code here!

shift_right = shift_right >> 2

shift_left = shift_left << 2

 

print bin(shift_right)

print bin(shift_left)

>>0b11

>>0b100

 

 

2-7. A BIT of This AND That

a: 00101010 42

b: 00001111 15

===================

a & b: 00001010 10

 

0 & 0 = 0

0 & 1 = 0

1 & 0 = 0

1 & 1 = 1

 

Therefore,

0b111 (7) & 0b1010 (10) = 0b10

================================

print bin(0b1110 & 0b101)

>> 0b100

 

0b 1110

0b 101

0b 100

1은 상쇄?

 

 

2-8. A BIT of This OR That

a: 00101010 42

b: 00001111 15

================

a | b: 00101111 47

 

0 | 0 = 0

0 | 1 = 1

1 | 0 = 1

1 | 1 = 1

 

110 (6) | 1010 (10) = 1110 (14)

==========================

print bin(0b1110 | 0b101)

>> 0b1111

 

0b1110

0b 101

 

 

2-9. This XOR That?

a: 00101010 42

b: 00001111 15

================

a ^ b: 00100101 37

 

0 ^ 0 = 0

0 ^ 1 = 1

1 ^ 0 = 1

1 ^ 1 = 0

111 (7) ^ 1010 (10) = 1101 (13)

================================

print bin(0b1110 ^ 0b101)

>> 0b1011

 

0b1110

0b 101

0b1011

 

 

2-10. See? This is NOT That Hard!

print ~1

print ~2

print ~3

print ~42

print ~123

>> -2

>> -3

>> -4

>> -43

>> -124

 

 

2-11. The Man Behind the Bit Mask (무슨 의도?)

def check_bit4(input):

mask = 0b1000

desired = input & mask

if desired > 0:

return "on"

else:

return "off"

 

check_bit4(0b1) # ==> "off"

check_bit4(0b11011) # ==> "on"

check_bit4(0b1010) # ==> "on"

 

 

2-12. Turn It On (무슨 의도?)

a = 0b110 # 6

mask = 0b11 # 3

desired = a | mask

 

print bin(desired)

>> 0b10111111 # 191

 

 

2-13. Just Flip Out (무슨 의도?)

a = 0b11101110

 

mask = 0b11111111

desired = a ^ mask

 

print bin(desired)

>> 0b10001 #17

 

 

2-14. Slip and Slide (무슨 동작?)

#모범 답안

def flip_bit(number, n):

bit_to_flip = 0b1 << (n -1)

result = number ^ bit_to_flip

return bin(result)

 

============================

#내가 한거

def flip_bit(number, n):

result = 0

result = number ^ n

return bin(result)

 

a = 0b101

mask = (0b1 << 9)

 

print flip_bit(a, mask)

 

print 0b1010110

#print 0b1010001

>> 0b1000000101

>> 86

 

 

11. Introduction to Classes

1. Introduction to Classes

1-1. Why Use Classes?

# 이런 걸 만들어 보겠다고 틀을 보여준 것이다.

class Fruit(object):

"""A class that makes various tasty fruits."""

def __init__(self, name, color, flavor, poisonous):

self.name = name

self.color = color

self.flavor = flavor

self.poisonous = poisonous

 

def description(self):

print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)

 

def is_edible(self):

if not self.poisonous:

print "Yep! I'm edible."

else:

print "Don't eat me! I am super poisonous."

 

lemon = Fruit("lemon", "yellow", "sour", False)

 

lemon.description()

lemon.is_edible()

>> I'm a yellow lemon and I taste sour.

>> Yep! I'm edible.

 

 

1-2. Class Syntax

#만들기 시작. 상속을 설명한단다.

class Animal(object):

pass

 

 

1-3. Classier Classes

class Animal(object):

def __init__(self):

pass

 

 

1-4. Let's Not Get Too Selfish

class Animal(object):

def __init__(self, name):

pass

self.name = name

 

 

1-5. Instantiating Your First Object

class Animal(object):

def __init__(self, name):

self.name = name

 

zebra = Animal("Jeffrey")

 

print zebra.name

>> Jeffrey

 

 

1-6. More on __init__() and self

class Animal(object):

"""Makes cute animals."""

def __init__(self, name, age, is_hungry):

self.name = name

self.age = age

self.is_hungry = is_hungry

 

zebra = Animal("Jeffrey", 2, True)

giraffe = Animal("Bruce", 1, False)

panda = Animal("Chad", 7, True)

 

print zebra.name, zebra.age, zebra.is_hungry

print giraffe.name, giraffe.age, giraffe.is_hungry

print panda.name, panda.age, panda.is_hungry

 

>> Jeffrey 2 True

>> Bruce 1 False

>> Chad 7 True

 

 

1-7. Class Scope

class Animal(object):

"""Makes cute animals."""

is_alive = True

def __init__(self, name, age):

self.name = name

self.age = age

 

zebra = Animal("Jeffrey", 2)

giraffe = Animal("Bruce", 1)

panda = Animal("Chad", 7)

 

print zebra.name, zebra.age, zebra.is_alive

print giraffe.name, giraffe.age, giraffe.is_alive

print panda.name, panda.age, panda.is_alive

 

>> Jeffrey 2 True

>> Bruce 1 True

>> Chad 7 True

 

 

1-8. A Methodical Approach

class Animal(object):

"""Makes cute animals."""

is_alive = True

def __init__(self, name, age):

self.name = name

self.age = age

 

# Add your method here!

def description(self):

print self.name

print self.age

 

zebra = Animal("Jeffrey", 2)

giraffe = Animal("Bruce", 1)

panda = Animal("Chad", 7)

hippo = Animal("Hiphop", 12)

 

hippo.description()

>> Hiphop

>> 12

 

 

1-9. They're Multiplying!

class Animal(object):

"""Makes cute animals."""

is_alive = True

health = "good"

def __init__(self, name, age):

self.name = name

self.age = age

 

def description(self):

print self.name

print self.age

 

zebra = Animal("Jeffrey", 2)

giraffe = Animal("Bruce", 1)

panda = Animal("Chad", 7)

hippo = Animal("Hiphop", 12)

sloth = Animal("Stupid", 9)

ocelot = Animal("cucu", 11)

 

print hippo.health

print sloth.health

print ocelot.health

>> good

>> good

>> good

 

 

1-10. It's Not ALL Animals and Fruits

class ShoppingCart(object):

"""Creates shopping cart objects

for users of our fine website."""

items_in_cart = {}

def __init__(self, customer_name):

self.customer_name = customer_name

 

def add_item(self, product, price):

"""Add product to the cart."""

if not product in self.items_in_cart:

self.items_in_cart[product] = price

print product + " added."

else:

print product + " is already in the cart."

 

def remove_item(self, product):

"""Remove product from the cart."""

if product in self.items_in_cart:

del self.items_in_cart[product]

print product + " removed."

else:

print product + " is not in the cart."

 

my_cart = ShoppingCart("Eric")

my_cart.add_item("Ukelele", 10)

>> Ukelele added.

 

 

1-11. Warning: Here Be Dragons

class Customer(object):

"""Produces objects that represent customers."""

#고객들을 나타내는 개체를 생성합니다.

def __init__(self, customer_id):

self.customer_id = customer_id

 

def display_cart(self):

# 당신의 쇼핑 카트의 내용에 대해 써 있다. 난 문자열!

print "I'm a string that stands in for the contents of your shopping cart!"

 

class ReturningCustomer(Customer):

"""For customers of the repeat variety."""

# 반복되는 다양한 고객들에게

def display_order_history(self):

# 당신의 역사에 서 있고 저는 문자열.

print "I'm a string that stands in for your order history!"

 

monty_python = ReturningCustomer("ID: 12345")

monty_python.display_cart()

monty_python.display_order_history()

>> I'm a string that stands in for the contents of your shopping cart!

>> I'm a string that stands in for your order history!

 

 

1-12. inheritance Syntax

class Shape(object):

"""Makes shapes!"""

def __init__(self, number_of_sides):

self.number_of_sides = number_of_sides

 

class Triangle(Shape):

def __init__(self, side1, side2, side3):

self.side1 = side1

self.side2 = side2

self.side3 = side3

 

 

1-13. Override!

class Employee(object):

"""Models real-life employees!"""

def __init__(self, employee_name):

self.employee_name = employee_name

 

def calculate_wage(self, hours):

self.hours = hours

return hours * 20.00

 

class PartTimeEmployee(Employee):

def calculate_wage(self, hours):

self.hours = hours

return hours * 12.00

 

 

1-14. This Looks Like a Job For...(임금 계산)

class Employee(object):

"""Models real-life employees!"""

def __init__(self, employee_name):

self.employee_name = employee_name

 

def calculate_wage(self, hours): #시간당 20달러

self.hours = hours

return hours * 20.00

 

class PartTimeEmployee(Employee): #파트타임 근무자

def calculate_wage(self, hours):

self.hours = hours

return hours * 12.00

 

def full_time_wage(self, hours): #풀타임 근무자

return super(PartTimeEmployee, self).calculate_wage(hours)

 

milton = PartTimeEmployee('Milton')

print milton.full_time_wage(10)

>> 200.0 # 10시간 근무했을 시 200달러

 

 

1-15. Class Basics

class Triangle(object):

def __init__(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

 

 

1-16. Class It UP

class Triangle(object):

number_of_sides = 3

def __init__(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

 

def check_angles(self):

if (self.angle1 + self.angle2 + self.angle3) == 180:

return True

else:

return False

 

 

1-17. Instantiate an Object

# 개체를 인스턴스화 하는 법 instance = Class(args)

class Triangle(object):

number_of_sides = 3

def __init__(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

 

def check_angles(self):

if (self.angle1 + self.angle2 + self.angle3) == 180:

return True

else:

return False

 

# instance = Class(args)

my_triangle = Triangle(30, 60, 90)

 

print my_triangle.number_of_sides

print my_triangle.check_angles()

>> 3

>> True

 

 

1-18. Inheritance

class Triangle(object):

number_of_sides = 3

def __init__(self, angle1, angle2, angle3):

self.angle1 = angle1

self.angle2 = angle2

self.angle3 = angle3

 

def check_angles(self):

if (self.angle1 + self.angle2 + self.angle3) == 180:

return True

else:

return False

 

# instance = Class(args)

my_triangle = Triangle(30, 60, 90)

 

print my_triangle.number_of_sides

print my_triangle.check_angles()

 

class Equilateral(Triangle): #정삼각형

angle = 60

def __init__(self):

self.angle1 = self.angle

self.angle2 = self.angle

self.angle3 = self.angle

 

 

2. Classes

2-1. Class basics

class Car(object):

pass

 

 

2-2. Create an instance of class

class Car(object):

pass

my_car = Car()

 

 

2-3. Class member variables(클래스 멤버 변수 호출하기.)

class Car(object):

condition = "new"

 

my_car = Car()

 

 

2-4. Calling class member variables

class Car(object):

condition = "new"

#my_car는 인스턴스

my_car = Car()

 

print my_car.condition

>> new

 

 

2-5. Initializing a class(초기화 클래스)

class Car(object):

condition = "new"

def __init__(self, model, color, mpg):

self.model = model

self.color = color

self.mpg = mpg

 

my_car = Car("DeLorean", "silver", 88)

 

 

2-6. Referring to member variables

클래스 구성원 변수는 해당 값이 클래스 내에서 생성되었는지(예:차량의 상태), 초기화 시 새 개체에 전달되는지 여부와 동일하게 작동합니다. 클래스의 멤버 변수는 개체에 속하기 때문에 이러한 변수에 액세스 하는 데 도트 표기를 사용합니다.

예를 들어, new_variable이라는 멤버 변수를 생성했다면 new_object라는 클래스의 새 인스턴스가 다음과 같이 이 변수에 액세스 할 수 있다.

class Car(object):

condition = "new"

def __init__(self, model, color, mpg):

self.model = model

self.color = color

self.mpg = mpg

 

my_car = Car("DeLorean", "silver", 88)

 

print my_car.model

print my_car.color

print my_car.mpg

 

>> DeLorean

>> silver

>> 88

 

 

2-7. Creating class methods

멤버 변수 외에도, 클래스는 그들만의 방법을 가질 수 있습니다.

예를 들어:

class Square(object):

def __init__(self, side):

self.side = side

 

def perimeter(self):

return self.side * 4

경계()클래스 방법은 제곱 클래스 정의의 내부에 기록된다는 점을 제외하고는 다른 기능을 정의하는 것과 동일합니다.

우리가 __init__ 을(를)정의했을 때와 마찬가지로, 어떤 클래스 방법으로든 자신을 첫번째 원칙으로 제시할 필요가 있다.

----------------------------------------------------------

#차량 클래스 내에서 display_car라는 메서드를 차량의 멤버 변수에 추가하여"이것은[color][Model]을 생성하는 방법으로 str()를 사용할 수 있는 문자열입니다."

#개별 인쇄 문을 my_car.display_car()호출 결과가 표시된 단일 인쇄 명령으로 교체합니다.

#클래스의 구성원 변수에 액세스 하려면(해당 클래스 내에 있는 동안에도)자체 키워드와 도트 표기법을 사용하여 클래스에 속한 구성원 변수를 나타내도록 지정해야 합니다.

 

class Car(object):

condition = "new"

def __init__(self, model, color, mpg):

self.model = model

self.color = color

self.mpg = mpg

 

def display_car(self):

print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

 

my_car = Car("DeLorean", "silver", 88)

 

my_car.display_car()

>> This is a silver DeLorean with 88 MPG.

 

 

2-8. Modifying member variables (회원 변수 수정)

이러한 구성원 변수를 초기화하는 것과 동일한 방식으로 클래스에 속한 변수를 수정할 수 있습니다. 이것은 클래스 방법 내에서 발생하는 것에 기반하여 변수가 가지는 가치를 변경하려는 경우에 유용할 수 있습니다.

1. 차량 클래스에서 self.condition을 "used"문자열에 설정하는 drive_car를 추가합니다.

my_car.display_car()에 대한 호출을 제거하고 대신 자동차 상태만 인쇄하십시오.

그런 다음 drive_car메서드를 호출하여 차를 운전합니다.

마지막으로, 차의 가치가 어떻게 변하는지 알아보기 위해 차의 상태를 다시 인쇄해 보아라.

class Car(object):

condition = "new"

def __init__(self, model, color, mpg):

self.model = model

self.color = color

self.mpg = mpg

 

def display_car(self):

print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

 

def drive_car(self):

self.condition = "used"

 

my_car = Car("DeLorean", "silver", 88)

 

print my_car.condition

my_car.drive_car()

print my_car.condition

>> new

>> used

 

이해하기 어렵다 ㅠㅠ.

 

 

2-9. Inheritance

수업의 이점 중 중요한 것은 우리가 그들의 부모 수업에서 변수나 방법을 물려받을 더 복잡한 수업을 만들 수 있다는 것이다. 이러한 하위 클래스에는 추가 변수나 방법도 포함될 수 있으므로 이 방법을 사용하면 시간을 절약하고 더 복잡한 개체를 만들 수 있습니다.

우리는 "상위"클래스의 모든 변수와 기능을 상속하는 "하위"클래스를 정의합니다.

class ChildClass(ParentClass):

# new variables and functions go here

일반적으로 가장 기본적인 클래스 유형이기 때문에 개체를 상위 클래스로 사용하지만, 다른 클래스를 지정하여 더 복잡한 기능을 상속할 수 있습니다.

class Car(object):

condition = "new"

def __init__(self, model, color, mpg):

self.model = model

self.color = color

self.mpg = mpg

 

def display_car(self):

print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

 

def drive_car(self):

self.condition = "used"

 

class ElectricCar(Car): # def init을 새로 만들고 molten salt를 추가하라는 거였다.

def __init__(self, model, color, mpg, battery_type):

self.model = model

self.color = color

self.mpg = mpg

self.battery_type = battery_type

 

my_car = ElectricCar("DeLorean", "silver", 88, "molten salt")

 

 

2-10. Overriding methods

당사의 전기 자동차는 좀 더 전문화된 종류의 자동차이므로, 당사는 원래 자동차 클래스와는 다른 기능을 가진 전기 자동차 전용 drive_car()방법을 제공할 수 있습니다.

1.ElectricCar는 새로운 methoddrive_car를 추가하고, 이 car는 차량의 조건을 "likenew"문자열로 변경한다.

그런 다음 전기 자동차 외부에 my_car의 상태를 인쇄합니다.

그런 다음 drive_car기능을 호출하여 my_car드라이브를 설정합니다.

마지막으로 my_car의 상태를 다시 인쇄합니다.

 

class Car(object):

condition = "new"

def __init__(self, model, color, mpg):

self.model = model

self.color = color

self.mpg = mpg

 

def display_car(self):

print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

 

def drive_car(self):

self.condition = "used"

 

class ElectricCar(Car):

def __init__(self, model, color, mpg, battery_type):

self.model = model

self.color = color

self.mpg = mpg

self.battery_type = battery_type

def drive_car(self):

self.condition = "like new"

 

# 처음엔 Car 클래스 안에서 condition을 받아 왔는데 drive_car를 받고 나선 거기서 받아왔다. 당연한데?

my_car = ElectricCar("DeLorean", "silver", 88, "molten salt")

print my_car.condition

my_car.drive_car()

print my_car.condition

>> new

>> like new

 

 

2-11. Building useful classes

유용한 클래스 구축

현실 세계에서 조만간 자동차 수업을 디자인하지 못할 수도 있다. 일반적으로 클래스는 추상 데이터 수집을 유지하고 액세스 하는 데 가장 유용합니다.

재정의할 수 있는 한가지 유용한 클래스 방법은 표현을 줄인 내장형 _____________ 방법이며, 이 방법으로 반환 값을 제공하여 Python에게 인쇄합니다(예:).

개체에서 상속되는 Point3D클래스 정의

Point3D클래스 내에서, 셀프, x, y, z를 받아들이고 이러한 숫자를 멤버 변수 self.x, self.y, self.z에 할당하는 _______ 함수를 정의하십시오.

%"(%d,%d,%d)"%%(self.x, self.y, self.z)를 반환하는 ______ 메서드를 정의하십시오. 이 명령은 Python에게 이 개체를(x, y, z)형식으로 표시하도록 지시합니다.

클래스 정의 밖에 x=1, y=2, z=3의 새 인스턴스가 포함된 my_point라는 변수를 생성합니다.

마지막으로 my_point를 입력합니다.

 

class Point3D(object):

def __init__(self, x, y, z):

self.x = x #self.x = x, 이렇게 하면 오류 난다. ,를 붙이면.

self.y = y #self.y = y,

self.z = z #self.z = z

 

def __repr__(self):

return "(%d, %d, %d)" % (self.x, self.y, self.z)

 

my_point = Point3D(1, 2, 3)

print my_point

>> (1, 2, 3)

 

 

12. File Input and Output

1. File Input and Output

 

1-1. See It to Believe It (믿기 위해 확인하기)

지금까지 입력한 Python코드는 한 소스에서 나오며 키보드에 입력하면 콘솔에 결과가 표시됩니다. 하지만 컴퓨터의 파일에서 정보를 읽거나 해당 정보를 다른 파일에 쓰려는 경우에는 어떻게 합니까?

이 프로세스를 파일 I/O("I/O")라고 하며, Python에는 이러한 작업을 대신하여 여러가지 기본 제공 기능이 있습니다.

오른쪽의 편집기에서 코드를 확인해 보세요.

 

my_list = [i ** 2 for i in range(1, 11)]

# Generates a list of squares of the numbers 1 - 10

 

f = open("output.txt", "w")

 

for item in my_list:

f.write(str(item) + "\n")

 

f.close()

 

 

1-2. The open() Function

한번에 한 단계씩 파일에 쓰는 과정을 살펴보겠습니다. 이전 실습에서 실행된 첫번째 코드는 다음과 같습니다.

이 명령은 Python이"w"모드로 output.txt를 열도록 지시했다("w"는 "쓰기"를 나타낸다). 이 작업의 결과를 파일 개체 f에 저장했습니다.

이렇게 하면 파일이 기록 모드로 열리고 Python이 데이터를 파일에 보내도록 준비합니다.

 

1. 변수 my_file을 생성하고 이를 output.txt에 있는 열림()기능을 호출하도록 설정합니다. 이 경우, 파일을 읽고 쓸 수 있도록 기능에 두번째 인수로 "r+"을 전달하세요! ( 자세한 내용은 힌트를 참조하십시오.)

다음 모드 중 하나로 파일을 열 수 있습니다.

쓰기 전용 모드("w")

읽기 전용 모드("r")

읽기 및 쓰기 모드("r+")

추가 모드("a")로, 파일 끝에 기록한 모든 새 데이터를 추가합니다.

 

my_file = open("output.txt", "r+")

 

 

1-3. Writing

잘 했어요! 이제 데이터를 새로운. txt파일로 작성할 시간입니다.

우리는 첫번째 연습부터 편집자의 코드까지 목록 이해를 추가했다. 이 연습의 목표는 해당 목록의 각 요소를 output.txt라는 파일에 쓰는 것입니다. 현재 폴더에 쓴 output.txt파일이 생성됩니다. 이 파일은 단순하기 때문에 폴더가 숨겨져 있는 것입니다. output.txt에서 각 번호가 고유하게 나열될 것이다.

다음과 같은 Python파일로 쓸 수 있습니다.

.write()방법에는 문자열 인수가 필요하므로 여기서 몇가지 작업을 수행해야 합니다.

파일을 닫아야 합니다. my_file.close()(마지막 연습에서는 이 작업을 수행했습니다)를 불러 오기만 하면 됩니다. 파일을 닫지 않으면 Python이 제대로 쓰지 않습니다. 이제부터는 파일을 닫아야 해요!

1. my_list를 기준으로 하여 각 값을 가져온다.

my_file.write()를 사용하여 각 값을 "output.txt"라는 텍스트 파일에 씁니다.

반복해서 꼭 Str()에게 전화해 주세요. 이렇게 쓰면 돼요.

각 요소 뒤에 새 라인(+"\n")을 추가하여 각 요소가 고유한 라인에 표시되도록 하십시오.

작업이 끝나면 my_file.close()를 사용하여 파일을 닫습니다.

연습을 통과하면 my_list를 output.txt에 성공적으로 작성했다는 것을 의미합니다.

 

# 1부터 10 까지 문자열로 받아서 쓰겠다는 것 같다.

my_list = [i ** 2 for i in range(1, 11)]

 

my_file = open("output.txt", "w")

 

for item in my_list:

my_file.write(str(item) + "\n")

 

my_file.close()

 

 

1-4. Reading

잘 했어요 당신은 프로에요.

마지막으로, 우리는 output.txt파일에서 읽는 법을 알고 싶다. 예상하신 대로, 우리는 이렇게 읽기()기능으로 이것을 합니다.

1. 변수 my_file을 설명하고"output.txt"와 "r"이 모두 포함된 open()을 눌러 반환되는 파일 개체와 동일하게 설정합니다.

그런 다음 위의 예제와 같이 my_file에 .Read()을 사용하여 얻은 결과를 인쇄하십시오.

작업이 끝났으면 파일을 닫으세요! 네가 하지 않으면 모든 종류의 파멸이 일어날 것이다

Hint 파일을 여는 구문은 다음과 같습니다.

 

 

my_file = open("output.txt", "r")

print my_file.read()

my_file.close()

>> 1

>> 4

>> 9

>> 16

>> 25

>> 36

>> 49

>> 64

>> 81

>> 100

 

 

1-5. Reading Between the Lines (한줄 한줄 읽기)

파일 전체를 한번에 끌어 들이지 않고 한줄씩 읽어 가며 읽으려면 어떻게 해야 합니까? 다행히 Python에는 정확하게 다음과 같은 기능을 하는. readline()방법이 포함되어 있다.

파일을 열고. readline()을 파일 개체에 대해 호출하면 파일의 첫번째 행이 표시되고, 이후에. readline()에 대한 호출이 연속적으로 반환됩니다.

새로운 변수 my_file을 선언하고"r"전용 모드의 "texty.txt"파일에 열어()결과를 저장합니다.

별도의 세줄에 my_file.readline()을 호출한 결과를 출력합니다. 매번 어떻게 다음 줄이 나오는지 봐?

작업이 끝나면 파일을 닫는 것을 잊지 마십시오!

 

my_file = open("text.txt", "r")

print my_file.readline()

print my_file.readline()

print my_file.readline()

my_file.close()

>> I'm the first line of the file!

>> I'm the second line.

>> Third line here, boss.

 

 

1-6. PSA: Buffering Data

편지를 다 쓴 후에는 항상 파일을 닫아야 한다고 말씀 드려요. 그 이유는 이렇습니다!

I/O프로세스 중 데이터는 버퍼링 됩니다. 즉, 파일에 쓰기 전에 임시 위치에 저장됩니다.

Python은 파일에 데이터를 쓰는 등의 방법으로 버퍼를 정리하지 않습니다. 닫지 않고 파일에 쓰면 데이터가 대상 파일로 이동하지 않습니다.

1. 편집자에게 우리의 아주 나쁜 코드를 확인해 보세요. run(실행)을 클릭하면 우리의 read_file.read()데이터를 다시 읽지 않았다는 점에 주목할 것입니다!

파일에 쓴 후 읽기 전에 write_file.close()호출을 추가합니다.

print read_file.read()라인 뒤에 read_file.close()호출 추가

코드를 다시 실행합니다.

이번에는 데이터가 나오는 것을 볼 수 있을 거예요!

 

write_file = open("text.txt", "w")

 

read_file = open("text.txt", "r")

 

write_file.write("Not closing files is VERY BAD.")

 

write_file.close()

print read_file.read()

read_file.close()

>> Not closing files is VERY BAD. (파일을 닫지 않는 것은 매우 나쁜 일이다.)

# 파일 사용했으면 제때제때 닫아야 한다. write 했으면 그 다음엔 닫아주고 read 했으면 그 다음엔 닫아주고.!

 

 

1-7. The 'with' and 'as' Keywords

프로그래밍은 컴퓨터가 그 일을 하도록 하는 것입니다. Python이 파일을 자동으로 닫도록 할 수 있는 방법이 있나요?

물론 있죠. 저는 Python입니다.

당신은 이것을 알지 못하지만, 파일 객체는 특수한 쌍의 기본 제공 방법인 __enter__(), __exit__() 을(를)포함한다. 상세 내역은 중요하지 않지만 중요한 것은 파일 개체의__exit__()방법이 호출될 때 파일이 자동으로 닫힌다는 점입니다. 이 방법을 어떻게 호출합니까? with 그리고 as.

구문은 다음과 같습니다.

#script.py 페이지

with open("text.txt", "w") as textfile:

textfile.write("Success!")

#text.txt 페이지

>> Success!

 

 

1-8. Try It Yourself

효과가 있었어요! 우리의 Python프로그램이 텍스트. txt에 성공적으로 기록되었다.

이제 시도해 보겠습니다. 원하는 모든 데이터를with...as파일에 쓰십시오. 파일 개체에 my_file이라는 일반적인 이름을 지정하십시오.

with open("text.txt", "w") as my_file:

my_file.write("Sleepy")

 

 

1-9. Case Closed?

마지막으로, 우리가 열어 놓은 파일이 닫혀 있는지 테스트할 방법을 원합니다. 파일 개체를 여러개 열어 두는 경우도 있는데, 주의하지 않으면 개체가 모두 닫히지 않습니다. 이것을 어떻게 테스트할 수 있을까요?

Python파일 개체는 파일이 닫힌 경우 True이고 그렇지 않으면 False입니다.

file_object.closed을(를)선택하여 파일이 닫혀 있는지 확인하고 파일이 여전히 열려 있는 경우 파일에 대해 닫기 close()를 호출할 수 있습니다.

1. 다음 코드를 사용하여 두가지를 수행합니다.

파일이 닫히지 않았는지 확인하십시오.

그런 경우에는, 전화를 걸어. 닫아.

(종결된 문장이 True이면 아무것도 하지 말아야 하기 때문에 여기서는 다른 설명이 필요하지 않습니다.)

설명이 끝나면 my_file.closed의 값을 인쇄하여 파일이 실제로 닫혀 있는지 확인합니다.

 

with open("text.txt", "w") as my_file:

my_file.write("My Data!")

 

#if 문에서 my_를 넣지 않고 file만 해도 정상작동 된다. 왜지?

# 만약 my_file이 닫혀있지 않는다면 my_file을 닫아라. 후에 출력으로 확인.

if not my_file.closed:

my_file.close()

 

print my_file.closed

>> True

 

https://www.crocus.co.kr/341

 

Crocus

꽃말 후회없는 청춘 ( We are Crocus! ) 미치게 살아봐요. 뭔가에 홀린 것처럼. 새벽이 넘어가도록 도서관에서 공부하다 저 벤치를 달굴 해가 뜨는 모습도 지켜봐보고, 씻지 않은 채로, 아무도 상관하지 않고 집..

www.crocus.co.kr

파이썬 큰 따옴표 작은 따옴표 차이
http://blog.naver.com/hyem0322/221034352793

 

파이썬 모듈 이란(import, from 설명)
http://blog.naver.com/gt6600/220910561853

파이썬 모듈 이란(randint, uniform)
http://blissa.tistory.com/802

파이썬 sort, sorted 차이
http://www.crocus.co.kr/937

파이썬 .split()
https://shlee_0607.blog.me/220676419002

 

파이썬 입력 함수
http://blog.naver.com/ksg97031/221124518775

파이썬 리스트 조작 함수
http://beaqon.blog.me/221004505651
Python3(파이썬3) 내장함수 3(lambda, len, list, map...
https://blog.naver.com/baekmg1988/220950402977
[파이썬/range] 반복문 - for 문을 이용한 range 함수
https://blog.naver.com/heartflow89/221062991798

람다(Lambda)함수란? 부속 사용 함수: map() reduce() reduce() 출처: 왕초보를 위한 Python 2.7
https://wikidocs.net/64
파이썬 04 - bin, oct, hex
https://blog.naver.com/dooits/221120598155
파이썬 int() 진수 변환
https://thrillfighter.tistory.com/295

[파이썬] 클래스, 인스턴스, 상속, 오버라이드, 슈퍼[출처] [파이썬] 클래스, 인스턴스, 상속, 오버라이드, 슈퍼 |작성자 호로요이이
https://blog.naver.com/demonic3540/221188267854

 

[파이썬] 클래스, 인스턴스, 상속, 오버라이드, 슈퍼

[들어가는 말] 파이썬 입문과정 때 대충 넘어갔던 개념들이 헷갈려 다시 정리해봄 ㅠ 클래스 개념을 메이플...

blog.naver.com

 

줄임말
def: defines the function

'스스로 코딩 > Codecademy' 카테고리의 다른 글

Choose your path - Codecademy  (0) 2020.04.26
CSS - Codecademy  (0) 2020.04.26
Ruby - Codecademy  (0) 2020.04.26
Codecademy란?  (0) 2020.04.26
블로그 이미지

Cyberworld

Everything is connected, connection is power.

,

<!DOCTYPE html> : 최초의 선언문
<h1..h2..h3></h1../h2../h3> : 제목으로 사용함. 큰 글씨가 나옴. h뒤 숫자가 커질수록 글씨 크기 줄어듬.(텍스트 확대)
<p></p> : 글 내용을 적는 곳.
<a></a>: 콘텐츠와 연결하기 위해 사용.
<div></div> : 텍스트나 다른 HTML 요소를 포함할 수 있음.
<ul></ul> : Unordered list 정렬되지 않은 리스트
<ol></ol> : Ordered list 정렬된 리스트(순서 있는, 숫자 있는)
<li></li> : list. ul이나 ol 리스트 안에서 사용된다. 내용을 씀.

<img src = "" /> : 이미지를 표현하게 할 수 있음.
<img src = "#" alt= "" / > : alt 기능. 영상이나 이미지를 웹 페이지에 로드 하지 못할 경우, 그 주소를 불러옴.
<video src ='' width="" height="" controls> Video not supported : 비디오 업로드 가능.(controls 있으면 영상 재생 가능하게 버튼 뜸.)
<a href="">Linking Out</a> : 웹 주소를 href에 넣고  Linking Out 부분이 빈 공간인데 이 공간에 쓰고 싶은 타이틀을 쓰면 그 글에 하이퍼 링크가 걸린다.

target=_blank : 현재 창에서 접속하는 것이 아니라 새로운 창에서 뜨게 한다.
사용 예) <a href="xxx.xx" target="_blank">BAKA</a> BAKA를 누르면 새로운 창이 뜸. 

상대 경로:  ./index.html : ./ 폴더 안에 있는 index.html 파일을 불러온다.
절대 경로: full url, http://codecademy.com/learn/index.html


div id를 주소에 #과 같이 넣어주면 introduction이라는 단어를 누를 때 그 페이지 쪽으로 가게 해준다.
                        div id 적는 곳            단어
<li>< a href="#introduction">introduction</a></li>
<div id="introduction">

<table></table>: 얘 안에서 테이블 관련된 명령어 수행 가능
<thead></thead>: table의 머리
<tbody></tbody>: table의 몸
<tfoot></tfoot>: table의 발
<tr></tr>: 행(rows)을 추가한다. 1행 2행 3행 등등
<th></th>: 제목 셀(열). 표 머리글
<td></td>: 내용 셀(열)
<td rowspan="합칠 행의 개수">내용</td>: 행이 서로 다른 n개의 셀을 병합
<td colspan="합칠 열의 개수">내용</td>: 열이 서로 다른 n개의 셀을 병합

<!-- 주석 처리할 내용 -->: 주석 

<style></style> 태그 사용법 예)  
  <style>
      table, th, td {
   border: 1px solid black;
   font-family: Arial, sans-serif;
    font-size: 18px;
   text-align: center;
  } </style>

부모 자식 개념 잘 확인하고 있기.

CSS 사용법 3가지 정리: http://ingorae.tistory.com/1692
CSS FONTS 글꼴 설정: http://nimolove.tistory.com/101

블로그 이미지

Cyberworld

Everything is connected, connection is power.

,

위키백과에 따르면 코드카데미(Codecademy)는 프로그래밍을 학습할 수 있는 온라인 플랫폼이다. 자바스크립트, PHP, 파이썬2, 루비 등 프로그래밍 언어와 HTML, CSS 등의 마크업 언어 과정이 있다. 2011년 9월 기준 55만명이 강의를 수강했다.


코드카데미는 제가 군대에 있었을 때 공부 연등을 이용하여서 조금이라도 감을 잡기 위해서 했었습니다.

제가 살면서 처음으로 여기 사이트에서 결제를 하고 싶다라는 생각이 들었을 정도로  되게 좋은 교육 프로그램들을 운영하고 있습니다. 일단 무료로 들을 수 있는 교육들이 되게 많아요. 대신에 무료는 어떤 프로젝트 기능들은 이용하지 못하지만 대신에 문법적인 공부를 하는데 있어서 길을 잡아줘서 되게 좋아요.

영어는 제가 잘 못해서 ㅎㅎ.. 네이버 번역기 파파고를 사용 했습니다.

크롬이랑 익스플로러는 사지방에서 업데이트를 안 해주어서 whale 브라우저를 항시 이용 했습니다.

프로그래밍 하는데 있어서 구글 번역기 보다 파파고가 더 정확 했었어요. 비교 해봤거든요.


HTML, CSS, Javascript, Ruby, SQL, C++, Swift, Python, PHP, Alexa, Watson, API, JAVA 등등 무료가 엄청 많아요.

프로그래밍을 배우고 싶고 처음에 어떻게 시작해야 할지 모르겠다면 Codecademy에서 무료로 프로그래밍 문법적 교육 받을 수 있으니까 해보시고 그 다음에 실제로 코딩 공부하셔도 무방할 것 같아요 ㅎㅎ. 결제 하시면 더 많은 기능 이용할 수 있는데 뭔가 광고 같네요 ㅋㅋ.


저도 무료 기능들만 사용해서 뻘쭘 하네요 ㅎㅎ... Codecademy 감사합니다.


Codecademy 카테고리 안에 있는 내용들은 제가 군 복무 시절 했던 내용들이라 지금은 조금 달라질 수도 있어요.

'스스로 코딩 > Codecademy' 카테고리의 다른 글

Choose your path - Codecademy  (0) 2020.04.26
CSS - Codecademy  (0) 2020.04.26
Ruby - Codecademy  (0) 2020.04.26
Python 개념 - Codecademy  (0) 2020.04.26
블로그 이미지

Cyberworld

Everything is connected, connection is power.

,