*본 내용은 KAIST 김문주 교수님의 [처음 배우는 프로그래밍(w.파이썬] 강의를 보고 공부하면서 요점 정리한 내용입니다.
# 샵을 이용해 주석처리를 할 수 있습니다.
name = input("What is your name? ")
print("Welcome to CS101, " + name)
raw_n = input("Enter a positive integer> ")
n = int(raw_n)
for i in range(n):
print("*" * i)
from cs1robots import *
Robot()
>>>type(3)
<class 'int'>
>>>type(Robot())
<class 'cs1robots.Robot'>
객체이름(변수) = 실제객체(값)
a = 3
>>>hubo = Robot()
>>>hubo.move()
n = None
>>> type(n)
<class 'None Type'>
a = (2012, "Kim")
>>> a, b = ("aa", "bb")
>>> a, b = b, a
>>> print(b)
aa
subtuple = mytuple[i;j]
list2 = list1[:] # 튜플 복사하기
subtuple은 mytuple의 인덱스 i, i+1, ... , j-1에 해당하는 원소를 포함한 튜플입니다.
i 를 생략하면, subtuple은 mytuple의 첫 번째 원소부터 가지게 됩니다.
j 를 생략하면, subtuple은 mytuple의 마지막 원소까지 가지게 됩니다.
>>> countries = [ "Australia", "South Korea" , "United States" ]
>>> gold = []
>>> countries[0]
'Australia'
>>> countries[-1]
'United States'
>>> countries[-2]
'South Korea'
>>> korea = [ "Korea", 'KR', (3, 3, 2) ]
>>> nobles = [ 'helium', 'none', 'argon', 'krypton',
'xenon' ]
>>> nobles[1] = "neon" # 원소 변경
>>> nobles
['helium', 'neon', 'argon', 'krypton', 'xenon']
>>> nobles.append('radon') # 원소 추가
>>> nobles
['helium', 'neon', 'argon', 'krypton', 'xenon',
'radon']
# 하나의 객체가 여러 이름 갖는 경우
>>> list1 = ["A","B","C"]
>>> list2 = list1
>>> len(list1)
3
>>> list2.append("D")
>>> len(list1)
4
>>> list1[1] = "X"
>>> list2
['A', 'X', 'C', 'D']
>>> list1 is list2
True
# 두 객체를 따로 갖는 경우
>>> list1 = ["A","B","C"]
>>> list2 = ["A","B","C"]
>>> len(list1)
3
>>> list2.append("D")
>>> len(list1)
3
>>> list1[1] = "X"
>>> list2
['A', 'B', 'C', 'D']
>>> list1 is list2
False
>>> len(countries)
함수 range는 range 타입의 객체를 만들어주는 함수입니다.for country in countries:
print(country)
for medals, country in top_ten:
print(medals, country)
>>> range(10)
range(0, 10)
>>> type(range(10))
<class 'range'>
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(10, 15))
[10, 11, 12, 13, 14]
>>> l = list(range(1, 11))
>>> for i in range(len(l)):
... l[i] = l[i] ** 2
>>> l
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
sublist = mylist[i;j]
list2 = list1[:] # 리스트 복사하기
sublist는 mylist의 인덱스 i, i+1, ... , j-1에 해당하는 원소를 포함한 리스트입니다.
i 를 생략하면, sublist는 mylist의 첫 번째 원소부터 가지게 됩니다.
j 를 생략하면, sublist는 mylist의 마지막 원소까지 가지게 됩니다.
>>> "abc" in "01234abcdefg"
True
>>> "abce" in "01234abcdefg"
False
문자열 포맷 연산자 %를 사용하면 더 쉽고 간단하게 문자열을 출력할 수 있습니다.print("Max between " + str(x0) + " and " +
str(x1) + " is " + str(val))
print("Max between %d and %d is %g" % (x0, x1, val))
print("Maximum is %g" % val)
# 포맷 연산자 사용 방법
format_string % (arg0, arg1, .... )
자료형에 따라 다른 문자열 포맷코드를 사용합니다.
%d: 10진법 정수
%g: 실수
%.2f: 소수점 자리수가 설정된 실수(이 경우는 소숫점 둘째 자리까지)
%s: 모든 자료형(문자열 등)
각 문자열 포맷 코드가 나타낼 문자열이 차지하는 영역의 크기를 설정할 수 있습니다.
>>> print("%3d~%3d:%10g" % (x0, x1, x2))
>>> t = ("CS101", "A+", 13)
>>> t[0] = "CS206"
TypeError: 'tuple' object does not support item assignment
>>> list(t)
['CS101', 'A+', 13]
>>> tuple(gold)
(0, 4, 5, 10, 3, 0, 2, 1, 4, ..., 2, 6, 1, 9)
>>> list("CS101")
['C', 'S', '1', '0', '1']
>>> odds = {1, 3, 5, 7, 9}
>>> emptyset = set() # {} creates an empty dictionary
>>> odds
{9, 3, 5, 1, 7}
>>> emptyset
set()
>>> odds[1]
TypeError: 'set' object does not support indexing
>>> 2 in odds
False
>>> for num in odds:
... print(num)
9
3
5
1
7
>>> gold = [10, 3, 6]
>>> gold
[10, 3, 6]
>>> goldset = set(gold)
>>> goldset
{3, 6, 10}
>>> type(goldset)
<class 'set'>
>>> set("Good morning!")
{'G', 'm', 'i', 'd', 'o', '!', 'g', 'n', 'r', ' '}
majors = {"CS": "Computer Science",
"EE": "Electrical Engineering",
"MAS": "Mathematical Sciences",
"ME": "Mechanical Engineering"}
d1 = dict() # an empty dictionary
d2 = {} # an empty dictionary
>>>majors[0]
KeyError: 0
>>> majors["PH"] = "Physic"
>>> majors["PH"]
'Physic'
>>> majors["PH"] = "Physics"
>>> majors["PH"]
'Physics'
>>> for key in majors:
... print("%s is %s." % (key, majors[key]))
CS is Computer Science.
PH is Physics.
ME is Mechanical Engineering.
EE is Electrical Engineering.
MAS is Mathematical Sciences.
>>> for key, value in majors.items():
... print("%s is %s." % (key, value))
CS is Computer Science.
PH is Physics.
ME is Mechanical Engineering.
EE is Electrical Engineering.
MAS is Mathematical Sciences.
리스트 자료 구조집합 자료 구조사전 자료 구조리스트보다 집합에서 원소의 포함 여부를 더 빠르게 계산할 수 있습니다.class Card(object):
""" A Blackjack card.""" # class comment: class 전체에 대한 설명을 적어줌
pass # 안에 내용들을 작성하지 않고 가장 간단하게 정의해줌
# Card 객체 생성하기
c = Card()
# card의 속성 설정하기
c.face = "Ace"
c.suit = "Spades"
c.value = 11
# c 객체의 형태는 사용자가 정의한 Card입니다.
>>> type(c)
<class '__main__.Card'>
>>> def f(x): # 함수 정의하기
... return math.sin(x / 3.0 + math.pi/4.0)
>>> print(f) #함수 자체 출력
<function f at 0xb7539a3c>
>>> print(type(f)) # 함수 타입 출력
<class 'function'>
#함수의 인자로 함수 사용
def print_table(func, x0, x1, step):
x = x0
while x <= x1:
print(x, func(x))
x += step
print_table(f, -math.pi, 3 * math.pi, math.pi/8)
class Card(object):
"""A Blackjack card."""
def value(self): # method of Card
if type(self.face) == int:
return self.face
elif self.face == "Ace":
return 11
else:
return 10
>>> card1 = Card()
>>> card1.face = "Ace"
>>> card1.suit = "Spades"
>>> card1.value()
11
# face가 가능한 모든 값들
FACES = list(range(2, 11)) + ['Jack', 'Queen', 'King', 'Ace']
# suit가 가능한 모든 값들
SUITS = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
Class Card(object):
"""A Blackjack card."""
def __init__(self, face, suit):
# 사용자가 넣은 입력이 잘못된 것인지 검사
assert face in FACES and suit in SUITS
self.face = face
self.suit = suit
#이제 Card 객체를 훨씬 간단하게 만들 수 있습니다.
card1 = Card("Ace", "Spades")
class Card(object):
"""A Blackjack card."""
"""Already defined init and value methods"""
def __str__(self):
article = "a "
if self.face in [8, "Ace"]:
article = "an "
return (article + str(self.face) + " of" + self.suit)
# 이제 다음처럼 카드 내용을 출력할 수 있습니다.
# print 함수는 인자 card 를 __str__를 사용해서 자동으로 문자열 형태로 바꿉니다.
>>> for card in hand:
... print(card, "has value", card.value())
# 객체에서 비교 연산자 (==, !=, < 등)를 사용하면 예상과 다른 결과가 나올 수 있습니다.
>>> Card(8, "Diamonds") == Card(9, "Diamonds")
False
>>> Card(8, "Diamonds") == Card(8, "Diamonds")
False
# 사용자의 생각대로 비교 연산자를 통해 객체를 비교하기 위해서는 다음과 같이 정의를
해야 합니다.
class Card(object):
"""A Blackjack card."""
"""Already defined other methods"""
def __eq__(self, rhs): # rhs는 right hand side 의미
return (self.face == rhs.face and self.suit == rhs.suit)
def __ne__(self, rhs):
return not self == rhs
# __ne__함수를 정의해주지 않으면
>>> Card(8, "Diamonds") == Card(8, "Diamonds")
True
>>> Card(8, "Diamonds") != Card(8, "Diamonds")
Ture # 의도와 다른 결과
>>>9/7
1.2857142857142858
>>>9//7
1
>>> "Hello" + "World"
'HelloWorld'
>>> "Hello" * 3
'HelloHelloHello'
>>>"Apple" < "Banana"
True
(not True) == False
(not False) == True
(False and False) == False
(False and True) == False
(True and False) == False
(True and True) == True
(False of False) == False
(False of True) == True
(True of False) == True
(True of True) == True
for i in range(4):
print("Hello World")
while 조건문:
print("Hello World")
if True:
print("It is true") // 출력됨
if False:
print("It is false") // 출력되지 않음
if a>b:
print("a가 b보다 큽니다.")
elif a==b:
print("a와 b가 같습니다.")
else:
print("b가 a보다 큽니다.")
def 함수이름(인자) :
함수 내용
return 결과
def to_radians(deg):
return (deg / 180.0) * math.pi
def student():
name = "Hong, Gildong"
id = 20101234
return name, id
>>> name, id = student()
>>> print(name)
"Hong, Gildong"
>>> print(id)
20101234
def swap(a, b):
a, b = b, a
x, y = 123, 456
swap(x, y)
print (x, y) // 바뀌지 않고 123, 456 출력됨
def create_sun(radius = 30, color = "yellow"):
sun = Circle(radius)
sun.setFillColor(color)
sun.setBorderColor(color)
sun.moveTo(100, 100)
return sun
moon = create_sun(28, "silver")
star = create_sun(2) # create_sun(2, "yellow")과 동일
sun = create_sun() # create_sun(30,"yellow")과 동일
def f1(x, y=0): # 옳은 함수 정의
return x+y
Def f2(x=0, y): # 틀린 함수 정의
return x+y
moon = create_sun(color = "silver")
moon = create_sun(color = "silver", radius = 28)
>>> avg(d, end=3)
5.0
>>> avg(data=d, end=3)
5.0
>>> avg(end=3, data=d)
5.0
>>> avg(end=3, d)
SyntaxError: non-keyword arg after keyword arg
>>> int("32")
32
>>> int(17.3)
17
>>> float(17)
17.0
>>> float("3.1415")
3.1415
>>> str(17) + " " + str(3.1415)
'17 3.1415'
>>> complex(17)
(17 + 0j)
import math
sin = math.sin
pi = math.pi
radians = degrees / 360.0 * 2 * pi
print(sin(radians))
전역 변수로 파이썬이 추론합니다.def f1():
return 3 * a + 5
지역 변수로 파이썬이 추론합니다.def f2(x):
a = 3 * x + 17
return a * 3 + 5 * a
a = 17
def test():
print(a) # a는 전역 변수로 판단
a = 13
print(a) # a는 지역 변수로 판단
test()
def turn_left():
hubo.turn_left()
global hubo_direction
hubo_direction += 90
a = "Letter a" # 전역 변수
def f(a): # 지역 변수(매개 변수)
print("A = ", a)
def g():
a = 7 # 지역 변수
f(a+1)
print("A = ", a)
print("A = ", a) # Letter a 출력
f(3.14) # 3.14 출력
print("A = ", a) # Letter a 출력
g() # 8 7 출력
print("A = ", a) # Letter a 출력
>>> help("cs1media")
import math
print(math.sin(math.pi))
# 모듈 이름 붙이지 않고 사용하기
from math import *
print(sin(pi)) # OK
print(math.pi) # NameError: name 'math'
# 필요한 함수만 들여오기
from math import sin
print(sin(3.14)) # OK
print(pi) # NameError: name ‘pi'
print(cos(3.14)) # NameError: name 'cos‘
print(math.cos(3.14)) # NameError: name 'math'
def bubbleSort(a):
sorted = False
while(not sorted):
sorted = True
for i in range(1,len(a)):
if(a[i-1] > a[i]):
a[i-1],a[i]=a[i],a[i-1]
sorted = False
planets.txt 파일
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
>>> f = open("planets.txt", "r")
>>> s = f.readline()
>>> s, len(s)
('Mercury\n', 8)
파일 객체에 for 반복문을 사용하면 반복할 때마다 readline() 함수를 실행합니다. 반복문은 파일의 마지막 줄을 읽은 후에 종료됩니다.
파일 객체의 사용이 끝나면 f.close()함수를 실행해야 합니다.
파일에서 읽어온 문자열 앞뒤의 공백 문자(줄 바꿈 문자, 띄어쓰기 등)를 제거하기 위해서 strip(), rstrip()함수를 사용합니다.
print()문에 end=" " 인자를 추가하면 문자열을 출력한 후 줄을 바꾸는 대신 한 칸을 띄어 쓸 수 있습니다.
>>> for l in f: # 파일 내용을 한 줄씩 읽는다.
... s = l.strip()
... print(s, end=" ")
Venus Earth Mars Jupiter Saturn Uranus Neptune
planets = []
f = open("planets.txt", "r")
for line in f:
planets.append(line.strip()) # strip() 통해 개행문자 제거
f.close()
print(planets)
파일 객체는 위와 비슷한 일을 하는 멤버 함수를 가지고 있습니다. (하지만 이 함수는 공백 문자를 따로 제거하지는 않습니다.)
planets = f.readlines()
f = open("./test.txt", "w")
f.write("CS101 is fantastic\n")
f.close()