본문 바로가기
Python

[Python] 제어문 (if, while, for)

by curious week 2024. 12. 26.

if문

name = True
if name:
  print(f'{name}입니다.');
else:
  print(f'{name}입니다.')
  
# x or y	x와 y 둘 중 하나만 참이어도 참이다.
# x and y	x와 y 모두 참이어야 참이다.
# not x	x가 거짓이면 참이다.

empty = ''
if not empty == '':
  print('no')
else:
  print('yes')

if empty == 'man':
  print('man')
else: 
  if 'woman': # 파이썬에서 문자열은 비어 있지 않기 때문에 **참(True)**으로 평가
    print('woman')
  else:
    print('empty')


# in, not in (문자열, 리스트, 튜플)
a = 1 in [1, 2, 3]
a = 1 not in [1, 2, 3]
a = 'a' not in ('a', 'b', 'c')
a = 'o' in 'python'
print(a)

# pass: 참, 거짓 중 하나 일 때만 출력하도록 할 때
if 'on' in 'come':
  pass
else:
  print('no!!')

# elif
empty = ['gogo', 'gigi', 'gaga']
if 'gugu' in empty:
  print('gugu')
elif 'glgl' in empty:
  print('glgl')
else:
  print('gogo')

# 한 줄로 적기
if 'gogo' in empty: pass
elif 'gigi' in empty: print('gigi')
else: print('no!!!')

# 변수 = 조건문이_참인_경우의_값 if 조건문 else 조건문이_거짓인_경우의_값
massage = 'yes' if 'gogo' in empty else 'no'
print(massage)

while문

# while 조건문:
treeHit = 0
while treeHit < 5: # 조건이 맞으면 반복되기에 treeHit <= 5면 6까지 출력된다. 
  treeHit += 1
  print('나무를 %d 번 찍었습니다.' % treeHit)
  if treeHit == 5:
    print('나무가 쓰러집니다.')
    
# while 문 만들기
prompt = """
1. 나무
2. 나무
3. 나무
4. 돌 
Enter rockHit : """
while treeHit != 4:
  print(prompt)
  treeHit = int(input())

# while문 빠져나오기 break
coffee = 1500
tea = 500
money = 3500
while money >= 0:
  if money >= coffee:
    print('돈 있다')
    money -= coffee
    print('coffee 꿀꺽!')
  elif money >= tea:
    print('돈 있다')
    money -= tea
    print('tea 꿀꺽!')
  else:
    print('돈 없다')
    break

# 건너띄기 continue
a = 0
while a < 10:
  a = a + 1
  if a % 2 == 0: continue # 나머지 값이 있는 홀수만 출력
  print(a)

for문

# 다양한 타입의 for문
list = [1, 2, 3, 4, 5]
for i in list:
  print(i)

a = [{1, 2}, {2, 3}, {3, 4}]
for (i, i2) in a:
  print(i + i2)

test = [('yeah!', 90),('bigGirl', 67),('beautiful', 45),('your', 80), ('!', 25)]
result = []
for (p, i) in test:
  if i >= 60:
    result.append(p)
    
for (p, i) in test:
  if i < 60:
    result.append(p)

print(result)

# continue
for (p, i) in test: 
  if i <= 80:
    continue
  print(p)

# range(시작 숫자(이상), 끝 숫자(미만)): range(10)은 1에서 10미만의 숫자를 포함하는 객체를 만들어준다.
add = 0
for i in range(1, 11):
  add += i
print(add)

# len = length
for i in range(len(test)):
  print(test[i])

# 구구단 // end 매개변수에는 줄바꿈 문자(\n)가 기본값으로 설정
for i in range(2,10):
  for j in range(1, 10):
    print(i*j, end=' ')
  print('')
  
# 리스트 컴프리헨션 [표현식 for 항목 in 반복 가능한 객체 if 조건문]
a = [1, 2, 3, 4]
result = [num * 3 for num in a if num % 2 != 0]
print(result) # 3을 곱하고 홀수만 출력

result = [x * y for x in range(2, 10)
                for y in range(1, 10)]
print(result)

'Python' 카테고리의 다른 글

[Python] 표준 라이브러리  (0) 2025.01.12
[Python] 내장 함수  (0) 2025.01.12
[Python] 클래스, 모듈, 패키지, 예외처리  (1) 2025.01.12
[Python] 입출력  (0) 2025.01.08
[Python] 자료형, 변수  (0) 2024.12.12