Programming/Python

[PY4E] 파이썬 조건문; if else try except quit

aram 2022. 7. 6. 00:05

1. 비교연산자

< 작다
<= 작거나 같다
== 같다
is
>= 크거나 같다
> 크다
!= 같지 않다
is not

▼ 파이썬 is, is not 연산자 자세히 알아보기

기본(7번) https://dailystudy.tistory.com/26

추가 내용 https://dailystudy.tistory.com/43

 

2. 조건문

  • 들여쓰기
    • if(조건문)과 for(반복문) 다음 " : (콜론) " 필수
    • 들여쓰기를 통해 블록 범위 표시
    • 탭1 = 스페이스4
    • 탭과 들여쓰기 혼동 시 "들여쓰기 에러" 발생
  • 숫자형 : 수학에서의 참/거짓과 동일 
    • 0 = False
    • 1 = True
  • 문자형 
    • if "abc" = True
    • if "" = False
  • 단일 if문
x = 10

if x > 2:
    print('More than two')

print('All done')

 

  • 중첩된 if문 - if = True, 중첩된 if문까지 실행여부 판단 
x = 10

if x > 2:
    print('More than two')
    if x < 50:
    	print('less than fifty')

print('All done')

 

  • 두 갈래 if else문 - if = True, if만 실행 / if = False, else만 실행
hours  = input('Enter Hours: ')
rate = input('Enter Rate: ')

fhours = float(hours)
frate = float(rate)

if fhours > 40:
    pay = 40*frate + (fhours-40) * frate*1.5
else:
    pay = fhours * frate
    
print('Pay:', str(pay))

 

  • 여러 조건 elif문 - if, elif, else 중 순차진행 → True 나오면 stop
hours  = input('Enter Hours: ')
rate = input('Enter Rate: ')

fhours = float(hours)
frate = float(rate)

if fhours > 40:
    pay = 40*frate + (fhours-40) * frate*1.5
elif float(hours) > 60:
    pay = 40*frate + (fhours-40) * frate*1.5
    print('Exceeded working hours')
else:
    pay = fhours * frate
    
print('Pay:', str(pay))

 

3. try / except 구조

  • 코드 실행 중 오류 발생 시, 파이썬 STOP 그 뒤의 코드는 아예 신경 안 씀
  • try 블록 True → except 블록 건너뜀
  • try 블록 False → except 블록 실행
  • try 블록에 여러 코드 입력 시, 중간에 False이면 그 즉시 STOP → except 블록 실행
    : 뒤의 코드는 불필요해짐
    : try 블록에 넣을 때는 실행여부에 따른 코드도 check
# type 1
hours  = input('Enter Hours: ')
rate = input('Enter Rate: ')

try:
    fhours = float(hours)
    frate = float(rate)
    if fhours > 40:
        pay = 40*frate + (fhours-40) * frate*1.5
    else:
        pay = fhours * frate
    
    print('Pay:', str(pay))

except:
    print('Error, please enter numeric input') #정상 여부 판단
# type 2
hours  = input('Enter Hours: ')
rate = input('Enter Rate: ')

try:
    fhours = float(hours)
    frate = float(rate)

except:
    print('Error, please enter numeric input')
    quit() #여기서 종료. 이후에 나오는 코드는 모두 무시
    
if fhours > 40:
    pay = 40*frate + (fhours-40) * frate*1.5
else:
     pay = fhours * frate
    
print('Pay:', str(pay))

 

* 내용참고&출처 : 태그의 수업을 복습 목적으로 정리한 내용입니다.

728x90