Lecture 2. BRANCHING, ITERATION
이 글은 Mit Open Courseware(OCW)에서 공개한 교육자료이며 OCW의 라이센스정책을 따릅니다.
License : Common Creative License : BY-NC-SA (저작자표시-비영리-동일조건변경허락)
출처 : https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/lecture-slides-code/MIT6_0001F16_Lec2.pdf
1. Strings
- String : 문자, 특수문자, 스페이스, 숫자로 구성
- 큰따옴표(" ")나 작은따옴표( ' ' )로 묶어서 표기
ex) hi = "hello there"
- 문자열 연결 : + 사용
>>> hi = "hello there"
>>> name = "ana"
>>> greet = hi + name
>>> greeting = hi + " " + name
>>> print(greet)
hello thereana
>>> print(greeting)
hello there ana
- 문자열에서 * 연산 : 횟수만큼 반복
>>> silly = hi + " " + name * 3
>>> print(silly)
hello there anaanaana
2. INPUT/OUTPUT: print
- print : 결과를 콘솔로 출력
- print 함수의 인자로 사용할때는 인자간 자동 space
- + 를 사용한 문자열 연결일때는 space 별도 지정 필요
>>> x = 1
>>> print(x)
>>> x_str = str(x)
>>> print("my fav num is",x, ".", "x =", x)
my fav num is 1 . x = 1
>>> print("my fav num is " + x_str + ". " + "x = " + x_str)
my fav num is 1. x = 1
3. INPUT/OUTPUT : input ("")
- 따옴표 안의 내용을 촐력하고 사용자의 입력 대기
- 입력후 enter 를 누르면 변수에 입력된 값을 할당
>>> text = input("아무 글자나 입력하세요...")
아무 글자나 입력하세요...abc
>>> print(5*text)
abcabcabcabcabc
>>>
- 입력된 문자를 cast(형변환)해서 사용할 수 있다.
- 아래처럼 int 형으로 형변환 할 경우 입력을 문자로 하면 오류발생
>>> num = int(input("숫자를 입력하세요... "))
숫자를 입력하세요... 2
>>> print(5*num)
10
4. Comparison Operator : int, float, string
- 비교 연산자
i > j
i >= j
i < j
i <= j
i == j : 일치확인. 같으면 TRUE, 다르면 FALSE
i != j : 불일치확인. 다르면 TRUE, 같으면 FALSE
5. Logic Operator : bools
- not a : a 가 TRUE 면 FALSE, FALSE면 TRUE
- a and b : a와 b가 모두 TRUE 일 경우에만 TRUE. 그 외는 FALSE
- a or b : a와 b가 모두 FALSE 일 경우에만 FALSE. 그 외는 TRUE
A |
B |
A and B |
A or B |
True |
True |
True |
True |
True |
False |
False |
True |
False |
True |
False |
True |
False | False |
False |
False |
>>> pset_time = 15
>>> sleep_time = 8
>>> print(sleep_time > pset_time)
False
>>> derive = True
>>> drink = False
>>> both = drink and derive
>>> print(both)
False
6. Control Flow
- condition은 True, False
- expression block은 condition이 True 일 경우 수행
1) if
if <condition> :
<expression>
<expression>
...
2) if - else
if <condition> :
<expression>
<expression>
...
else :
<expression>
<expression>
..
3) if - elif - else
if <condition> :
<expression>
<expression>
...
elif :
<expression>
<expression>
..
else :
<expression>
<expression>
..
7. INDENTATION
다른 언어가 코드의 블럭을 { 과 같은 기호로 구분하는것과 달리 파이썬은 indentation(들여쓰기)로 블럭을 구분한다.
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
if y != 0:
print("therefore, x / y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")
print("thanks!")
8. CONTROL FLOW : while LOOPS
- <condition>이 True , False를 평가하고 True면 블럭내부 수행, False면 종료
while <condition> :
<expression>
<expression>
...
n = input("You're in the Lost Forest. Go left or right? ")
while n == "right":
n = input("You're in the Lost Forest. Go left or right? ")
print("You got out of the Lost Forest!")
9. CONTROL FLOW : while and for LOOPS
n = 0
while n < 5:
print(n)
n = n+1
위 코드와 아래코드는 동일하다
for n in range(5):
print(n)
10. CONTROL FLOW : for LOOPS
for <variable> in range(<some_num>):
<expression>
<expression>
...
range (start, stop, step)
- 지정하지 않으면 star 0, step은 1
- loop 는 stop -1 까지 수행
mysum = 0
for i in range(7, 10):
mysum += i
print(mysum)
mysum = 0
for i in range(5, 11, 2):
mysum += i
print(mysum)
=> 5+7+9 = 21
11. break STATEMENT
break 문을 만나면 해당 블럭의 control-flow 를 벗어난다.
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
mysum += 1
print(mysum)
=> 5
12. continue STATEMENT
continue 문을 만나면 해당 블럭의 continue 이하는 수행하지 않고 다음 loop를 수행한다
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
continue
mysum += 1
print(mysum)
=> 23
댓글