본문 바로가기

study_IT/기타

생활코딩 파이썬 제어문

728x90
반응형

파이썬 제어문: 조건문과 반복문

1. Boolean 데이터 타입

print(True)  # True
print(False)  # False

 

2. 비교연산자

print('1 == 1', 1 == 1)  # 1 == 1 True
print('1 == 2', 2 == 1)  # 1 == 2 False
print('1 < 2', 1 < 2)    # 1 < 2 True
print('1 > 2', 1 > 2)    # 1 > 2 False
print('1 >= 1', 1 >= 1)  # 1 >= 1 True
print('2 >= 1', 2 >= 1)  # 2 >= 1 True
print('1 != 1', 1 != 1)  # 1 != 1 False
print('2 != 1', 2 != 1)  # 2 != 1 True

 

3. 조건문

3-1) 조건문의 기본형식

print(0)
if True:
    print(1)
print(2)
 
print('---')
 
print(0)
if False:
    print(1)
print(2)

input_id = input('id : ')
id = 'egoing'
if input_id == id:
    print('Welcome')

 

3-2) 조건문-else

print(0)
if True:
    print(1)
else:
    print(2)
print(3)
print('---')

print(0)
if False:
    print(1)
else:
    print(2)
print(3)

input_id = input('id : ')
id = 'egoing'
if input_id == id:
    print('Welcome')
else:
    print('Who?')

 

3-3) 조건문 elif

print(0)
if True:
    print(1)
elif True:
    print(2)
else:
    print(3)
print(4)
print('---')

print(0)
if False:
    print(1)
elif True:
    print(2)
else:
    print(3)
print(4)
print('---')

print(0)
if False:
    print(1)
elif False:
    print(2)
else:
    print(3)
print(4)

input_id = input('id : ')
id1 = 'egoing'
id2 = 'basta'
if input_id == id1:
    print('Welcome')
elif input_id == id2:
    print('Welcome')
else:
    print('Who?')

 

3-4) 조건문 중첩

input_id = input('id:')
id = 'egoing'
input_password = input('password:')
password = '111111'
if input_id == id:
    if input_password == password:
        print('Welcome')
    else:
        print('Wrong password')
else:
    print('Wrong id')

 

4. 반복문

4-1) 반복문-for 기본형식

names = ['egoing', 'basta', 'blackdew', 'leezche']
for name in names:
    print('Hello, '+name+' . Bye, '+name+'.')

 

4-2) 반복문-다차원 배열의 처리

persons = [
    ['egoing', 'Seoul', 'Web'],
    ['basta', 'Seoul', 'IOT'],
    ['blackdew', 'Tongyeong', 'ML'],
]
print(persons[0][0])
 
for person in persons:
    print(person[0]+','+person[1]+','+person[2])
 
person = ['egoing', 'Seoul', 'Web']
name = person[0]
address = person[1]
interest = person[2]
print(name, address, interest)
 
name, address, interest = ['egoing', 'Seoul', 'Web']
print(name, address, interest)
 
for name, address, interest in persons:
    print(name+','+address+','+interest)

4-3) 반복문-Dictionary

person = {'name':'egoing', 'address':'Seoul', 'interest':'Web'}
print(person['name'])
 
for key in person:
    print(key, person[key])
 
persons = [
    {'name':'egoing', 'address':'Seoul', 'interest':'Web'},
    {'name':'basta', 'address':'Seoul', 'interest':'IOT'},
    {'name':'blackdew', 'address':'Tongyeong', 'interest':'ML'}
]
 
print('==== persons ====')
for person in persons:
    for key in person:
        print(key, ':', person[key])
    print('-----------------')

 

728x90
반응형