조건문과 반복문

if

weather = input('오늘 날씨는 어때요? ') # input을 이용해 다음과 같이 작성 후 실행 시 커서가 ? 뒤에서 기다리고 있다. 사용자가 입력한 값은 문자열로 저장된다. 
if weather == '비' or weather == '눈':
    print('우산을 챙기세요.')
elif weather == '미세먼지':
    print('마스크를 챙기세요.')
else:
    print('준비물이 필요 없어요.')

temp = int(input('기온은 어때요? ')) # 정수형으로 입력값을 받고 싶을 때
if 30 <= temp:
    print('너무 더워요, 나가지 마세요.')
elif 10 <= temp and temp < 30:
    print('괜찮은 날씨에요.')
elif 0 <= temp < 10:
    print('외투를 챙기세요.')
else:
    print('너무 추워요, 나가지 마세요.')

 if 문을 통해 원하는 조건에 맞는 코드를 실행시킬 수 있다. 그리고 만약 처음 if의 조건에 성립하지 못했다면 elif를 만나고, 이러한 if 와 elif 모두의 조건에 성립할 수 없다면 else로 넘어가게 된다.

 

 위 코드에서 쓰인 input을 통해서 사용자가 입력한 입력값을 받을 수 있다.

 

for

for waiting_no in [0, 1, 2, 3, 4]:
    print("대기번호: {0}".format(waiting_no))

for waiting_no in range(5): # 0 부터 5 직전까지
    print('대기번호: {0}'.format(waiting_no))

for waiting_no in range(1, 5): # 1부터 5 직전까지
    print('대기번호: {0}'.format(waiting_no))

starbucks = ['아이언맨', '토르', '아이엠 그루트']

for customer in starbucks:
    print('{0}, 커피가 준비되었습니다.'.format(customer))

 for문을 통해서 원하는 만큼 코드를 반복적으로 실행할 수 있다.

 

students = [1, 2, 3, 4, 5]
print(students)
students = [i + 100 for i in students] # students의 각 요소를 i로 불러오면서 그 i에 100 더한 값을 students 리스트에 넣어라.
print(students)

students = ['Iron man', 'Thor', 'I am groot']
print(students)
students = [len(i) for i in students]
print(students)

students = ['Iron man', 'Thor', 'I am groot']
print(students)
students = [i.upper() for i in students]
print(students)

 이렇게 리스트 안에서 반복을 진행하여 각 요소의 값을 바꿀 수 있다. 첫 번째 students는 [101, 102, 103, 104, 105]가 되었을 것이다. 두 번째 students 리스트는 각 요소가 길이로 반환되어 [8, 4 ,10]이 된다. 세 번째 students는 모두 대문자로 바뀌게 된다.

 

while

customer = '토르'
index = 5
while index >= 1:
    print("{0}님, 커피가 준비 되었습니다. {1}번 남았습니다.".format(customer, index))
    index -= 1
    if index == 0:
        print('커피는 폐기처분되었습니다.')

 while 문은 조건을 만족하는 한, 계속해서 while 밑의 코드가 실행된다. 위 코드는 index가 점차 5, 4, 3, 2, 1로 줄어들면서 5번 반복하게 되고 0이 되면서 index >= 1을 만족하지 못하게 되기 때문에 while문이 종료된다.

 

customer = '아이언맨'
index = 1
while True:
    print('{0}님, 커피가 준비되었습니다. 호출 {1}번 했습니다.'.format(customer, index))
    index += 1

 이처럼 코드를 작성 시, 계속해서 True이기 때문에 무한 루프에 빠지게 된다. 터미널에서 index가 계속해서 증가하는 것을 목격할 수 있다.

무한루프, 터미널 창 클릭 후 ctrl + c(윈도우)로 빠져나올 수 있다.

 

customer = '토르'
person = 'Unknown'

while person != customer:
    print('{0}님, 커피가 준비되었습니다.'.format(customer))
    person = input('이름이 어떻게 되시나요? ')
    if person == '토르':
        print('네, 감사합니다.')

 위 코드에서는, input에서 사용자가 토르라고 입력하지 않으면 while문이 계속해서 실행된다. 사용자가 토르라고 입력하면 person = '토르'가 되고 if문을 실행하여 '네, 감사합니다.'를 실행시킨다. 그리고 person != customer는 False가 되어 while이 종료된다.

 

continue, break

absent = [2, 5]
noBook = [7]

for student in range(1, 11):
    if student in absent:
        continue # continue를 만나면 밑에 있는 문장을 실행하지 않고 다음으로 넘어간다. 즉 2나 5에서는 책 좀 읽어줘를 실행하지 않고 3과 6으로 넘어가게 된다.
    elif student in noBook:
        print('오늘 수업은 여기까지. {0}은 교무실로 따라와'.format(student))
        break # break를 만나면 곧바로 반복문이 종료된다. 즉 7에서는 8로 넘어가는 것이 아니라 반복문을 종료시킨다.
    print('{0}, 책 좀 읽어줘.'.format(student))

 continue를 만나면 밑의 코드를 무시하고 다음 차례로 넘어간다. 즉 if문에서 현재 student가 absent와 동일한 2라면 continue가 실행된다. 따라서 '책 좀 읽어줘'라는 print문이 실행되지 않고 student는 3으로 넘어가게 된다.

 

 break를 만나면 반복문을 종료시키게 된다. 만약 현재 student가 noBook과 동일한 7이라면 elif문의 코드가 실행되고 print문이 실행되면서 while이 멈추게 된다. break는 다음 차례로 넘어가는 continue와는 다르게 8로 넘어가지 않고 7에서 for문을 종료한다는 것이다.

 

퀴즈

'''
Quiz) 당신은 Cocoa 서비스를 이용하는 택시 기사님입니다.
50명의 승객과 매칭 기회가 있을 때, 총 탑승 승객 수를 구하는 프로그램을 작성하시오.

조건1 : 승객별 운행 소요 시간은 5분 ~ 50분 사이의 난수로 정해집니다.
조건2 : 당신은 소요 시간 5분 ~ 15분 사이의 승객만 매칭해야 합니다.

(출력문 예제)
[O] 1번째 손님 (소요시간 : 15분)
[ ] 2번째 손님 (소요시간 : 50분)
[O] 3번째 손님 (소요시간 : 5분)
...
[ ] 50번째 손님 (소요시간 : 16분)

총 탑승 승객 : 2 분
'''

 

# while 사용
currPassenger = 1
passCount = 0

while currPassenger < 51:
    leadTime = randint(5, 50)
    if 5 <= leadTime <= 15:
        print('[O] {0}번째 손님 (소요시간 : {1})'.format(currPassenger, leadTime))
        passCount += 1
    else:
        print('[ ] {0}번째 손님 (소요시간 : {1})'.format(currPassenger, leadTime))
    currPassenger += 1

print('총 탑승 승객 : {0} 분'.format(passCount))

 

count = 0

for i in range(1, 51):
    leadTime = randrange(5, 51)
    if 5 <= leadTime <= 15:
        print('[O] {0}번째 손님 (소요시간 : {1})'.format(i, leadTime))
        count += 1
    else:
        print('[ ] {0}번째 손님 (소요시간 : {1})'.format(i, leadTime))

print('총 탑승 승객 : {0} 분'.format(count))

'프로그래밍 > Python' 카테고리의 다른 글

리스트, 딕셔너리, 튜플, 세트  (0) 2022.03.09
문자열  (0) 2022.03.04
연산자  (0) 2022.03.03
자료형  (0) 2022.03.03

자바스크립트에서(파이썬이나 다른 프로그래밍 언어에서도 마찬가지일 것이다) 조건이 충족되면 어떤 코드가 실행될 수 있도록 제어할 수 있다.

if (false) {
	console.log("Hello, world");
}

위의 console.log는 실행되지 않는다. ()안에 들어오는 코드가 조건인데, 이미 조건이 false로 전제되어 있기 때문이다. true로 되어 있다면 console.log는 실행된다. 하지만 false와 true로 조건문을 실행하는 것은 무의미하다. false라면 그냥 코드를 안적으면 되는 것이고 true라면 if 없이 쓰면 되기 때문이다.

 

이렇게 if문을 통해서 ()안의 조건이 충족되면 {}의 코드가 실행되도록 할 수 있다. 더 나아가 else if, else를 써서 'A라면 B를 해주세요, 하지만 C라면 D를 해주세요. 이도저도 아니면 E를 해주세요'라는 조금 더 복잡한 조건문을 만들 수 있다.

if (A) {
	B
} else if (C) {
	D
} else {
	E
}

물론 위의 A, B, C, D, E는 아무것도 정의되지 않은 코드이기 때문에 정상적으로 실행되지 않는다. console로 실행해보니 에러가 뜬다.

 

var something = true;
var moreSomething = true;

if (something) {
	console.log("I am inside something");

	if (moreSomething) {
    	console.log("I am inside moreSomething)";
    } else {
    	console.log("I never gets called");
    }
} else {
	console.log("I never gets called either");
}

// 위와 같이 실행할 경우
// I am inside something
// I am inside moreSomething
// 만 출력된다.

이렇게 서로 if문에 if문이 들어가도록 중첩되게 사용할 수도 있다.

 

if (A) {
  // one..
} else if (B) {
  // two..
} else if (C) {
  // three..
} else if (D) {
  // four..
} else if (E) {
  // five..
} else {
  // six..
}

유의할 점으로, 위와 같이 코드를 짰을 때 A랑 C가 true더라도 A 조건의 one만 실행된다. else는 '~~가 아니면 ~~을 해라'라는 뜻이기 때문에, 앞의 것이 true이면 뒤의 것은 실행되지 않는다.

 

  • Quiz
if (true) {
  console.log(1);
} else if (true) {
  console.log(2);
} else {
  console.log(3);
}

if ("") {
  console.log(1);
} else if ("a") {
  console.log(2);
} else {
  console.log(3);
}

if (null) {
  console.log(1);
} else if (5) {
  console.log(2);
} else {
  console.log(3);
}

맨 위의 if문은 맨 처음부터 true이므로 1이 출력된다. 두 번째 if문에서는 처음에는 Falsy값인 ""이 조건으로, false로 인지하기 때문에 두 번째에서 Truthy 값인 "a"가 true로 인식되어 2가 출력된다. 3번째도 마찬가지로 처음에 Falsy값인 null로 인해 false로 인지하여 1이 출력되지 않고 두 번째에서 Truthy값인 5를 true로 인지하여 2가 출력된다.

 

  • Switch

if문과 비슷한 것이 switch문인데 switch문은 case를 사용한다.

var expr = 'Bananas'

switch (expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Apples':
    console.log('Apples are $0.32 a pound.');
    break;
  case 'Bananas':
    console.log('Bananas are $0.48 a pound.');
    break;
  case 'Cherries':
    console.log('Cherries are $3.00 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    break;
  default:
    console.log('Sorry, we are out of ' + expr + '.');
}

console.log("Is there anything else you'd like?");

// 위의 코드를 실행할 경우
// 'Bananas are $0.48 a pound.'
// "Is there anything else you'd like?")
// 가 출력된다.

말그대로 해당되는 case를 찾아간다. 

var expr = 'Bananas';
switch (expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Apples':
    console.log('Apples are $0.32 a pound.');
    break;
  case 'Bananas':
    console.log('Bananas are $0.48 a pound.');

  case 'Cherries':
    console.log('Cherries are $3.00 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    break;
  default:
    console.log('Sorry, we are out of ' + expr + '.');
}

console.log("Is there anything else you'd like?");

// 'Bananas' case에 break가 빠져있다.
// Bananas are $0.48 a pound.
// Cherries are $3.00 a pound.
// Is there anything else you'd like?
// 가 출력된다.

이 때 주의할 것이 break인데, break를 각 case마다 설정해두지 않는다면 다음 case문이 실행된다.

var expr = 'Pineapple';
switch (expr) {
  default:
    console.log('Sorry, we are out of ' + expr + '.');
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Apples':
    console.log('Apples are $0.32 a pound.');
    break;
  case 'Bananas':
    console.log('Bananas are $0.48 a pound.');
    break;
  case 'Cherries':
    console.log('Cherries are $3.00 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    break;
}

console.log("Is there anything else you'd like?");

// 위 코드를 실행할 경우
// 'Sorry, we are out of Pineapple.'
// 'Oranges are $0.59 a pound.'
// "Is there anything else you'd like?"
// 가 출력된다.

또 다른 주의점은 default문이다. 아무것도 해당하지 않을 경우 기본적인 문구가 나오도록 설정하는 것인데, 위와 같이 맨 마지막에 위치한 경우가 아닐 경우 defauly문에는 break가 없기 때문에 break를 만나기 전까지의 코드가 실행된다. 따라서 default는 마지막에 넣어주는 것이 좋다.

 

switch 참고 출처 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/switch

+ Recent posts