Condition & Loop

  • 조건문의 이해 활용(if)
  • 반복문의 이해 및 활용(while, for)

In [6]:
a = 99

if a % 9 == 0:
    if a % 11 == 0:
        print '!!!'
elif a % 10 ==0:
    print '???'
else:
    print 'hahaha'


!!!

In [3]:
x = 7

if (5 > x) and (x < 10):
    print 'oh!'

In [4]:
a = []

if a:
    print 'right'
    
else:
    print "empty"


empty

In [7]:
5 == 6
5 != 6

a = 0
if not a == 0:
    print 'haha'

In [8]:
count = 1
while count <=3:
    print count
    count += 1
    
print count
print 'a'


1
2
3
4
a

In [9]:
count = 1
while True:
    print count
    count += 1 
    if count > 3:
        break


1
2
3

In [10]:
var = 7

while var > 0:
    var -= 1
    if var == 5:
        continue
        
    print 'Current variable value :', var
    
print 'Good bye!'


Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!

In [11]:
nums = [1, 3, 5]

position = 0

while position < len(nums):
    number = nums[position]
    
    if number % 2 == 0:
        print 'even number'
        break
        
    position += 1
else:
    print 'no even number'


no even number

In [12]:
nums = [1, 3, 2, 5, 4, 6, 7, 9, 8]
pos = 0

while pos < len(nums):
    print nums[pos],
    pos += 1


1 3 2 5 4 6 7 9 8

In [13]:
a = [1, 2, 3, 4]
b = a

print a == b


True
  • for
    • 이터레이터가 내부적으로 생김
    • for [loop_var] in [sequence]: 로 쓰임
    • sequence는 리스트, 문자열, 튜플, 딕셔너리, 셋 등 순회 가능한 객체

In [14]:
a = [1, 2, 3, 4, 5]

for i in a:
    print i


1
2
3
4
5

In [17]:
nums = [1, 3, 2, 5, 4, 6, 7, 8, 9]
for val in nums:
    print val,
print 
for i in nums:
    print i,
print    
for num in nums:
    print num,


1 3 2 5 4 6 7 8 9
1 3 2 5 4 6 7 8 9
1 3 2 5 4 6 7 8 9

In [20]:
str = 'hello world'
for char in str:
    print char


h
e
l
l
o
 
w
o
r
l
d

In [25]:
capitals = {'korea' : 'seoul', 'japan' : 'tokyo', 'usa' : 'Washington D.C'}

for country in capitals:
    print country, capitals[country]
print '-' * 20
for key in capitals.keys():
    print key
print '-' * 20    
for val in capitals.values():
    print val
print '-' * 20    
for k, v in capitals.items():
    print k, v


japan tokyo
korea seoul
usa Washington D.C
--------------------
japan
korea
usa
--------------------
tokyo
seoul
Washington D.C
--------------------
japan tokyo
korea seoul
usa Washington D.C

In [26]:
nums = [1, 3, 2, 5, 4, 6, 7, 9, 8]

for val in nums:
    print val,
    
for i, _ in enumerate(nums):
    print 'value at index', i


1 3 2 5 4 6 7 9 8 value at index 0
value at index 1
value at index 2
value at index 3
value at index 4
value at index 5
value at index 6
value at index 7
value at index 8

In [27]:
a = [1, 2, 3, 4]
b = [2, 3, 4]

for i in a:
    for j in b:
        print i, j


1 2
1 3
1 4
2 2
2 3
2 4
3 2
3 3
3 4
4 2
4 3
4 4
  • if & for 연습문제

    1. 1 - 100 까지 정수 중 2의 배수 또는 11의 배수를 모두 출력
    2. a = [22, 1, 3, 4, 7, 98, 21, 55, 87, 99, 19, 20, 45]의 최대값과 최소값을 구하라
    3. a = [22, 1, 3, 4, 7, 98, 21, 55, 87, 99, 19, 20, 45]의 평균을 구하라

In [39]:
nums = range(1, 101)

for i in nums:
    if i % 2 == 0 or i % 11 ==0:
        print i,


2 4 6 8 10 11 12 14 16 18 20 22 24 26 28 30 32 33 34 36 38 40 42 44 46 48 50 52 54 55 56 58 60 62 64 66 68 70 72 74 76 77 78 80 82 84 86 88 90 92 94 96 98 99 100

In [ ]:
a = [22, 1, 3, 4, 7, 98, 21, 55, 87, 99, 19, 20, 45]

minimum = a[0]

for i in a[1:]:
    if minimum > i:
        minimum = i
        
print minimum

In [40]:
a = [22, 1, 3, 4, 7, 98, 21, 55, 87, 99, 19, 20, 45]

sum1 = 0

for i in a:
    sum1 = sum1 + i
    
print float(sum1)/len(a)


37.0
  • comprehension
    • 하나 이상의 이터레이터로부터 파이썬의 자료 구조를 만드는 엘레강스하고 간결한 방법

In [41]:
nums = [1, 2, 3, 4, 5, 6]

even_nums = []
for i in nums:
    if i % 2 == 0:
        even_nums.append(i)
        
print even_nums


[2, 4, 6]

In [44]:
nums = [1, 2, 3, 4, 5, 6]

even_nums2 = [i for i in nums if i % 2 == 0]
even_nums3 = [i + 3 for i in nums if i % 2 == 0]
print even_nums2, even_nums3


[2, 4, 6] [5, 7, 9]

In [45]:
nums2 = [i for i in nums]
nums3 = [i**2 for i in nums]

print nums2
print nums3


[1, 2, 3, 4, 5, 6]
[1, 4, 9, 16, 25, 36]

In [46]:
nums4 = [i for i in nums if i < 4]

nums5 = [i**2 if i < 4 else i * 2 for i in nums]

print nums4
print nums5


[1, 2, 3]
[1, 4, 9, 8, 10, 12]

In [48]:
rows = range(1, 4)
cols = range(1, 3)

for row in rows:
    for col in cols:
        print row, col
        
print '-' * 20


cells = [(row, col) for row in rows for col in cols]
for row, col in cells:
    print row, col


1 1
1 2
2 1
2 2
3 1
3 2
--------------------
1 1
1 2
2 1
2 2
3 1
3 2

In [49]:
words = ['apple', 'banana', 'chicago', 'do', 'elephant']

dict1 = {}
for w in words:
    dict1[w] = len(w)

print dict1

words = ['apple', 'banana', 'chicago', 'do', 'elephant']
words_dict = {w: len(w) for w in words}

print words_dict


{'do': 2, 'chicago': 7, 'elephant': 8, 'apple': 5, 'banana': 6}
{'do': 2, 'chicago': 7, 'elephant': 8, 'apple': 5, 'banana': 6}
  • practice

    • Celsius = [39.2, 36.5, 37.3, 37.8] F = (9/5) * C + 32 일 때, 리스트의 각 값을 화씨로 바꾼 리스트를 만드시오.
    • 주어진 문자열에서 띄어쓰기의 개수는? 'Today is very nice and I want to go out for dinner'
    • 주어진 문자열에서 모음을 모두 제거하시오. 'Today is very nice and I want to go out for dinner'

In [50]:
Celsius = [39.2, 36.5, 37.3, 37.8]

F = [1.8 * c + 32 for c in Celsius]

print F


[102.56, 97.7, 99.14, 100.03999999999999]

In [51]:
str1 = 'Today is very nice and I want to go out for dinner'

temp = [ch for ch in str1 if ch == ' ']
print len(temp)


11

In [52]:
str1 = 'Today is very nice and I want to go out for dinner'

vowels = 'aeiou'

temp = [ch for ch in str1 if not ch in vowels]
print ''.join(temp)


Tdy s vry nc nd I wnt t g t fr dnnr

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: