Python MIT OCW Lec2 : Branching, Iteration

김재만·2023년 9월 18일
0

Python MIT OCW

목록 보기
2/9

배울 내용

    1. String object type
    1. Branching and conditionals
    1. Indentation
    1. Iteration and loops

1. String Object Type

  • Enclose in quotation marks or single quotes

    	hi = "hello there"
  • concatenate strings
    : put the strings together

hi = "hello there"
name = "ana"

greet = hi + name
print(greet) # hello thereana

greeting = hi + " " + name
print(greeting) # hello there ana
  • do some operations on a string as defined in Python docs
silly = hi + " " + name * 3
print(silly) # hello there anaanaana

Input/Output : print

  • used to output to console
x = 1
print(x)

x_str = str(x)
print("my fav num is", x, ".", "x =", x) # my fav num is 1 . x = 1
# 두 object 사이에는 자동으로 공백이 생성. 즉, 콤마 자리는 하나의 공백으로 처리. 
# object가 반드시 string일 필요가 없다.

print("my fav num is " + x_str + ". " + "x = " + x_str)
# concatenate : 모든 object가 반드시 string이어야 한다.

Input/Output : input("")

  • prints whatever is in the quotes
  • user types in something and hits enver
  • binds that value to a variable
text = input("Type anything... ")
print(5*text)

# Type anything... string
# stringstringstringstringstring
  • input gives you a string so must cast if working with numbers
num = int(input("Type a number... "))
print(5*num)

# Type a number... 5
# 25

2. Indentation

  • matters in Python
  • how you denote blocks of code
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")
  • Python은 포함 범주를 들여쓰기로 사용, colone은 이 들여쓰기를 암시한다.
    : 들여쓰기를 위해서는 반드시 콜론 필요
    : tab 과 space 3~5회는 같은 공백을 보일지라도 다른 들여쓰기이다. python에서는 통일시켜야함 (다만 자동완성 기능으로 자연스럽게 통일이 되긴 함)

3. Branching and Coditionals

Comparison Operators on int, float, string

  • i and j are var. names

  • comparisons below evaluate to a Boolean
    : i > j
    : i >= j
    : i < j
    : i <= j
    : i == j (equality)
    : i != j (inequality)

  • string vs num(int, float)
    : not allowed

  • string vs string
    : 오름차순

Logic Operators on bools

  • a and b are boolean var.

  • not a
    : True if a is False
    : False if a is True

  • a and b
    : True if both are True

  • a or b
    : True if either or both are True

Comparison Example

pset_time = 15
sleep_time = 8
print(sleep_time > pset_time) # False
derive = True
drink = False
both = drink and derive
print(both) #  False

Control Flow - Branching

  1. if
if <condition>:
	<expression>
    <expression>
    ...
  1. if - else
if <condition> : 
	<expression>
    <expression>
    ...
else : 
	<expression>
    <expression>
    ...
  1. if - elif - else
if <condition> :
	<expression>
    <expression>
    ...
elif <condition> :
	<expression>
    <expression>
    ...
else : 
	<expression>
    <expression>
    ...
  • < condition > has a value True of False
  • evaluate expressions in that block if < condition > is True

4. Iteration and Loops

While

while <condition> : 
	<expression>
    <expression>
    ...
  • repeat until < condition > is False
  • example
n = 0
while n < 5 : 
	print(n)
    n = n+1
    
# 0
# 1
# 2
# 3
# 4

break Statement

  • immediately exits whatever loop it is in
  • skips remaning expressions in code block
    - exits only innermost loop!
while <condition_1> : 
	while <condition_2> :
    	<expression_a>
        break
        <expression_b>
    <expression_c>
  • example
mysum = 0
for i in range(5, 11, 2) : 
  mysum += i
  if mysum == 5 : 
    break
    mysum += 1
print(mysum) # 5

For

range(start, stop, step)

  • start, stop, step have to be integer
  • default values are start = 0 and step = 1 and optional
  • loop until value is stop - 1
for <variable> in range(<some_num>) : 
	<expression>
    <expression>
    ...
  • each time through the loop, < variable > takes a vale
  • first time, < variable > starts at the smallest value
  • next time, < variable > gets the prev value +1
  • ex)
for n in range(5) : 
	print(n)
    
# 0
# 1
# 2
# 3
# 4
mysum = 0
for i in range(7, 10) : 
  mysum += i
print(mysum) # 24 = 7 + 8 + 9
mysum = 0
for i in range(5, 11, 2) : 
  mysum += i
print(mysum) # 21 = 5 + 7 + 9

for vs while

  • for
    : know number of iteration
    : can end early via break
    : uses a counter
    : can rewrite a for loop using a while loop
  • while
    : unbounded number of iterations
    : can end early via break
    : can use a counter bum must initialize
    : may not be able to rewrite a while loop using a for loop
profile
Hardware Engineer가 되자

0개의 댓글