-
파이썬을 배워 봅시다. 파이썬 기초: 리스트와 함수 쉽게 배우기(3)사회 2024. 9. 22. 07:00728x90반응형
함수와 조건문을 결합하기
함수 안에 조건문을 넣으면, 더 유용한 동작을 수행할 수 있어요.
예를 들어, 주어진 나이에 따라 성인인지 미성년자인지 확인하는 함수를 만들어볼게요.
pythondef check_age(age):if age >= 18:return "성인입니다."else: return "미성년자입니다."result = check_age(20)print(result) # 성인입니다.이렇게 함수에 조건을 넣으면 여러 상황에 맞게 활용할 수 있죠!
3. 리스트와 함수, 조건문의 활용 예시
이제 리스트, 함수, 조건문을 한꺼번에 사용해서 간단한 프로그램을 만들어볼게요.
예를 들어, 여러 사람의 나이를 리스트로 받아서,
그 사람들이 성인인지 미성년자인지 판별하는 프로그램을 만들어보겠습니다.
pythonages = [16, 21, 18, 14, 30]def check_age(age):if age >= 18:return "성인"else:return "미성년자"for age in ages:result = check_age(age)print(f"{age}세는 {result}입니다.")- 결과:
16세는 미성년자입니다.21세는 성인입니다.18세는 성인입니다.14세는 미성년자입니다.30세는 성인입니다.
4. 요약
- 조건문은 "만약 이런 조건이면 이렇게 하고, 아니면 저렇게 해라"와 같은 논리를 표현해요.
- 리스트와 함수를 조건문과 결합하면 더 복잡하고 유용한 프로그램을 만들 수 있어요.
이제 조건문을 사용해 리스트와 함수에서 다양하게 응용하는 방법도 알았어요!
다음에는 반복문과 조건문의 더 복잡한 활용이나 파일 처리에 대해 다뤄볼까요?
계속해서 쉽게 풀어가겠습니다!
728x90반응형'사회' 카테고리의 다른 글
파이썬을 배워 봅시다. 파이썬 기초: 반복문과 조건문 결합, 파일 처리 (2) (0) 2024.09.23 파이썬을 배워 봅시다. 파이썬 기초: 반복문과 조건문 결합, 파일 처리 (1) (0) 2024.09.22 파이썬을 배워 봅시다. 파이썬 기초: 리스트와 함수 쉽게 배우기(2) (0) 2024.09.22 파이썬을 배워 봅시다. 파이썬 기초: 리스트와 함수 쉽게 배우기(1) (0) 2024.09.21 파이썬을 배워 봅시다. 파이썬의 기본 데이터 타입(2) (0) 2024.09.21 - 결과: