본문 바로가기

백엔드개발자 준비하기 - 파이썬

[파이썬] 조건문, 반복문

조건문

a = 5
if a > 10:
    print('greater than 10')
elif a > 3:
    print('greater than 3')
elif a == 5:
    print('is five')
else :
    print('not greater than 10')

결과

greater than 3

반복문1

for i in range(4):
    print(i)

결과

0
1
2
3

반복문2

for _ in range(4):
    print('message')

결과

message
message
message
message

반복문3

a = range(4) #start, stop
print(a)
print(type(a))

for i in a:
    print(i)

결과

range(0, 4)
<class 'range'>
0
1
2
3

반복문4

a = range(0, 50, 3) #start, stop, step
print(a)
print(type(a))

for i in a:
    print(i)
    
#for(int i = 0; i < 50; i += 3)

결과

range(0, 50, 3)
<class 'range'>
0
3
6
9
12
15
18
21
24
27
30
33
36
39
42
45
48

반복문5

# 100에서 500미만 5의 배수 출력

list1 = []
for i in range(100, 500, 5):
    list1.append(i)

print(list1)

결과

[100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 
185, 190, 195, 200, 205, 210, 215, 220, 225, 230, 235, 240, 245, 250, 255, 260, 265, 
270, 275, 280, 285, 290, 295, 300, 305, 310, 315, 320, 325, 330, 335, 340, 345, 350,
355, 360, 365, 370, 375, 380, 385, 390, 395, 400, 405, 410, 415, 420, 425, 430, 435, 
440, 445, 450, 455, 460, 465, 470, 475, 480, 485, 490, 495]

 

반복문6

list2 = [x for x in range(100, 500, 5)]
print(list2)

결과

[100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 
185, 190, 195, 200, 205, 210, 215, 220, 225, 230, 235, 240, 245, 250, 255, 260, 265, 
270, 275, 280, 285, 290, 295, 300, 305, 310, 315, 320, 325, 330, 335, 340, 345, 350,
355, 360, 365, 370, 375, 380, 385, 390, 395, 400, 405, 410, 415, 420, 425, 430, 435, 
440, 445, 450, 455, 460, 465, 470, 475, 480, 485, 490, 495]

반목문7

list_3 = []
list_5 = []

for i in range(0, 100, 3):
    list_3.append(i)
    
for i in range(0, 100, 5):
    list_5.append(i)

print(list_3)
print(list_5)

list_3_a = []
for i in list_3:
    if i % 5 > 0:
        list_3_a.append(i)
print(list_3_a)

s = 0
for i in list_3_a:
    s = s +i
for i in list_5:
    s = s +i
    
print(s)

결과

[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
[3, 6, 9, 12, 18, 21, 24, 27, 33, 36, 39, 42, 48, 51, 54, 57, 63, 66, 69, 72, 78, 81, 84, 87, 93, 96, 99]
2318

반복문8

list_a = []

for i in range(0, 100):
    if i % 3 == 0 or i % 5 == 0:
        list_a.append(i)
        
print(list_a)

list_a = [i for i in range(0, 100) if i % 3 == 0 or i % 5 == 0]
print(sum(list_a))

결과

[0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99]

2318

 

'백엔드개발자 준비하기 - 파이썬' 카테고리의 다른 글

[파이썬] 문자열  (0) 2023.02.02
[파이썬] 함수  (0) 2023.02.02
[파이썬] list, tuple, set, dictionary  (0) 2023.01.31
[파이썬] 기본 문법  (0) 2023.01.31
[파이썬] 환경설정  (0) 2023.01.31