-
[Python] 14. 조건문 (if문)Programming/Python 2021. 7. 11. 19:04
weather = input("Today's weather") if weather == "Sunny": print("You dont need an umbrella") elif weather == "Rain" or weather == "Snow": print("You probably need an umbrella ") else: print("Wrong answer")
- 위 코드는 날씨를 의미하는 문자열 변수 weather에 따라, 조건문을 구성한다.
- if 문의 기본적인 구조는 if - elif - else 이며, elif와 else는 생략 가능하다.
- and 또는 or을 사용하여 원하는 조건을 구성하는 것이 가능하다.
- {}를 사용하는 C, C++과 달리, Python에서는 : 를 통해 조건과 statement를 구분한다. statement와 if문의 탈출은 줄 맞춤을 통해 구분한다.
temp = float(input("Today's temperature")) if 40 <= temp: print("Very hot") elif 30 <= temp < 40: print("Hot") elif 10 <= temp < 30: print("Warm") else: print("Cold")
- 위 코드는 온도를 의미하는 실수형 temp에 따라 조건문을 구성한다.
- input을 float으로 묶어준 이유는, input으로 입력받은 것은 문자열 형태로 저장되기 때문이다.
- if - elif를 통해 여러 조건에 따른 출력문을 구성하였으며, else를 통해 조건을 만족하지 않는 상황에서의 출력문을 구성했다.
*본 글은 코딩 유튜버 '나도코딩'님의 무료강의를 바탕으로 내용을 정리 및 추가한 글입니다.
https://www.youtube.com/watch?v=kWiCuklohdY&t=5934s
'Programming > Python' 카테고리의 다른 글
[Python] 16. while문과 continue, break (0) 2021.07.11 [Python] 15. for문 (0) 2021.07.11 [Python] 13. 집합(set) (0) 2021.07.08 [Python] 12. 튜플(tuple) (0) 2021.07.08 [Python] 11. 사전(Dictionary) (0) 2021.07.08