[Python] 04. IF

Min's Study Note·2023년 11월 3일
0

Python

목록 보기
4/21

04. IF

✔️ 기본형(1) : if

  • 조건문이 True(혹은 1) 라면 실행문을 실행하고, False(혹은 0) 라면 실행하지 않음
if True:	
	print('if문 실행') 
# 출력값: if문 실행 

if False:	
	print('if문 실행') 
    
# 출력값:

✔️ 기본형(2) : if else

  • 조건문이 True(혹은 1) 라면 if의 실행문을 실행하고, False(혹은 0) 라면 else의 실행문을 실행함
if 1:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if 0:	
	print('if문 실행')
else:	
	print('else문 실행') 
    
# 출력값: else문 실행

✔️ if elif else

  • 조건문이 True(혹은 1) 가 되는 if 혹은 elif의 실행문을 실행하고, 모든 조건문이 False(혹은 0) 라면 else의 실행문을 실행함
  • 위에서부터 시작하여 가장 먼저 True(혹은 1) 가 되는 if 혹은 elif의 실행문만 실행됨
a = 0
if a == 0:	
	print('if문 실행')
elif a == 1:
	print('elif문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

a = 1
if a == 0:	
	print('if문 실행')
elif a == 1:	
	print('elif문 실행')
else:	
	print('else문 실행') 

# 출력값: elif문 실행 

a = 2
if a == 0:	
	print('if문 실행')
elif a == 1:	
	print('elif문 실행')
else:	
	print('else문 실행') 

# 출력값: else문 실행 

a = 3
if a == 0:	
	print('if문 실행')
elif a == 1:	
	print('첫 번째 elif문 실행')
elif a == 2:	
	print('두 번째 elif문 실행')
elif a == 3:	
	print('세 번째 elif문 실행')
else:	
	print('else문 실행') 

# 출력값: 세 번째 elif문 실행

✔️ 조건문 유형 : 객체 내 요소의 존재 여부

  • 여기서 객체는 일반적으로 문자열, 리스트, 튜플, 딕셔너리를 의미함
  • 객체 내에 요소가 하나 이상 있으면 True, 하나도 없으면 False
if 'abc':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if '':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: else문 실행 

if [1, 2, 3]:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if []:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: else문 실행

✔️ 조건문 유형 : in, not in

  • 여기서 객체는 일반적으로 문자열, 리스트, 튜플, 딕셔너리를 의미함
  • 요소 in 객체 : 객체 내에 특정 요소가 존재하면 True, 존재하지 않으면 False
  • 요소 not in 객체 : 객체 내에 특정 요소가 존재하지 않으면 True, 존재하면 False
if 'a' in 'abc':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if 'k' in 'abc':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: else문 실행 

if 6 not in [1, 2, 3]:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if 1 not in [1, 2, 3]:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: else문 실행

✔️ 조건문 유형 : 비교연산자(==, !=, >, >=, <, <=)

  • 여기서 값은 일반적으로 숫자형, 문자열을 의미함
  • 값1 == 값2 : 두 값이 같으면 True, 다르면 False
  • 값1 != 값2 : 두 값이 다르면 True, 같으면 False
  • 값1 > 값2 : 값1이 값2보다 크면 True, 작거나 같으면 False
  • 값1 >= 값2 : 값1이 값2보다 크거나 같으면 True, 작으면 False
  • 값1 < 값2 : 값1이 값2보다 작으면 True, 크거나 같으면 False
  • 값1 <= 값2 : 값1이 값2보다 작거나 같으면 True, 크면 False
  • 객체1 is 객체2 : 객체1과 객체2가 같으면 True, 다르면 False
  • 객체1 is not 객체2 : 객체1가 객체2가 다르면 True, 같으면 False
  • 값 비교: ==, != 는 두 값이 같은지 여부(글자가 같은지? 숫자의 크기가 같은지?)를 확인함, 단순 크기 비교 시 권장되는 연산자
  • 객체 비교: is, is not 은 값 뿐만 아니라 데이터 타입, 메모리 주소 등 객체 자체가 같은지 여부를 확인함, 일반적으로 클래스를 통해 생성된 객체의 동등 비교 시 사용함
  • ex) 3 == 3.0 은 True 가 되며 3 is 3.0 은 데이터 타입과 메모리 주소가 달라지므로 False 가 됨
if 'abc' == 'abc':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if 'abc' != 'abc':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: else문 실행 

if 3 >= 2:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if 3 < 2:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: else문 실행 

if 3 is 3.0:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: else문 실행

✔️ 조건문 유형 : 논리연산자(and, or, not)

  • 조건문1 and 조건문2 : 두 조건문 모두 True이면 True, 그 외 False
  • 조건문1 or 조건문2 : 두 조건문 중 하나라도 True이면 True, 그 외 False
  • not 조건문 : 조건문이 False이면 True, True이면 False
  • and 와 or 는 여러 조건문을 연결할 수 있음
  • ex) 조건문1 and 조건문2 or 조건문3 and 조건문4 or 조건문5 and 조건문6 ...
if 1 == 1 and 'kkk' not in 'abc':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if 5 == 1 and 'kkk' not in 'abc':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: else문 실행 
if 5 == 1 or 'kkk' not in 'abc':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if not 5 == 1:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

if 1 == 1 and 2 == 2 and 3 == 3:	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행

✔️ if문 조건부 표현식

  • (True 일 때 실행문) if (조건문) else (False 일 때 실행문)
if 'a' in 'abc':	
	print('if문 실행')
else:	
	print('else문 실행') 

# 출력값: if문 실행 

print('if문 실행') if 'a' in 'abc' else print('else문 실행') 

# 출력값: if문 실행

✔️ 실행문을 비우고 싶을 때 : pass

  • 실행문 자리에 pass 입력 시, 조건문 만족 시 아무일도 일어나지 않음
if 1 == 1:	
	pass
else:	
	print('else문 실행') 
# 출력값:

연습문제

👉 학점 출력

print("Input", end=" : ")
score = int(input())
result = ''
if score >= 90:
  result = 'A'
elif score >= 80:
  result = 'B'
elif score >= 70:
  result = 'C'
elif score >= 60:
  result = 'D'
else:
  result = 'F'

print("당신의 학점은 {}입니다".format(result))
# Input : 85
# 당신의 학점은 B입니다

👉 for문 사용해서 3333부터 9999까지 숫자 중 1234배수 아닌 수의 합계 구하되,
합계가 100000이 넘기 직전까지만 구하는 파이썬 코드 작성.
코드에는 continue문과 break 모두 사용

total = 0

for i in range(3333, 10000, 1):
    if i % 1234 == 0:
        continue

    total += i;

    if total + i> 100000:
        break

print(f"합계: {total}")
#97063

👉 3부터 100까지 소수(Prime Number)만 출력

for i in range(3,101,1):
    is_prime=True
    for j in range(2,i,1):
        if i%j==0:
            is_prime=False
            break
    if is_prime:
        print(i, end=" ")
#3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

출처 및 참고

0개의 댓글