logoRawon_Log
홈블로그소개

Built with Next.js, Bun, Tailwind CSS and Shadcn/UI

Python

Python beginner - Control Flow

Rawon
2025년 9월 1일
목차
Python 기초 문법 - Control Flow
If
Else & Elif
And & OR
Python Standard Library
While
Python Casino Game

목차

Python 기초 문법 - Control Flow
If
Else & Elif
And & OR
Python Standard Library
While
Python Casino Game

Python 기초 문법 - Control Flow

If

  • if 조건:
  • 실행할 코드
python
if 10 == 5:
  print("write the code to run")

Else & Elif

python
password_correct = True

if password_correct:
  print("Here is ypur money")
else:
  print("Wrong Password")
  • if와 else 내부(탭이나 space 2번) 에 실행할 코드를 입력해야 함!
  • else는 반드시 사용할 필요없이 선택사항임.
python
winner = 10

if winner > 10:
  print("Winner is greater than 10")
elif winner < 10:
  print("Winner is less than 10")
else:
  print("Winner is 10")
  • elif 는 else와 if 가 합쳐진 것으로 JS의 else if 와 동일한 역할을 함.
  • elif 도 반드시 사용해야 하는 것이 아닌 선택사항임.

And & OR

  • 그전에 python 내장 함수 3가지를 소개하려 함. (print 와 같은 내장함수)
  • input 함수는 1개의 argument만을 받으며, 이는 질문임. 이건 단순한 print 가 아니라 value를 print 하기도 하지만 실행 상태로 나의 응답을 기다림
  • 사용자가 나에게 무엇을 답하던지 그 값이 input 함수의 return 값임
  • 정리하면 input 함수는 사용자에게 input 을 요청하고 사용자가 키보드로 입력한 문자열을 반환하는 함수!
python
age = input("How old are you?") # How old are you? > 36 입력

print("user answer", age) # user answer 36
  • type 함수는 변수의 타입을 알려주는 함수임.
python
age = input("How old are you?") # How old are you? > 36 입력

print(type(age))  # <class 'str'>. -> age 변수 타입이 string 이란 의미

if age < 18 # error 발생, str과 숫자를 비교할 수 없기 때문
  • int 함수는 문자열 등 다른 타입을 int 타입으로 변환
python
age = int("36") # string 36을 int(정수) 타입으로 변환
  • and : 양쪽 모두가 true 여야 함. 만약 앞부분이 false 라면 전체가 false가 됨
  • or : 앞부분 또는 뒷부분 둘 중에 하나라도 true이면 true
python
age = int(input("How old are you?"))

if age < 18:
  print("You can`t drink")
elif age >= 18 and age < 35: # 18세 이상이면서 동시에 35세 미만인지
  print("You drink beer!")
elif age == 60 or age == 70:
  print("Birthday party")
else:
  print("Go ahead!")

Python Standard Library

  • 언어에 default로 포함된 function을 의미. 이미 언어에 포함된 function 그룹
  • Built-in Function 은 항상 사용할 수 있는 function을 의미 (print, int, input 등)
  • random.randint(a, b) -> a <= N <= b
  • 이러한 내장 함수를 그냥 복사/붙여넣기 해서 사용하면 제대로 동작하지 않음.
  • 아래 예시의 경우 random 이라는 모듈의 이름이 정의되지 않으면 제대로 동작하지 않음.
  • 그러므로 from random import randint 추가
python
from random import randint

user_choice int(input("Choose number"))
pc_choice = random.randint(1, 50)

if user_choice == pc_choice:
  print("You won!")
elif user_choice > pc_choice:
  print("Lower!")
elif user_choice < pc_choice:
  print("Higher")

코드블럭을 주석처리 하기 위해서는 맨위 그리고 맨 아래 “”” 을 추가!

While

  • while 은 if 와 비슷한 조건문임.
  • 멈추지 않는다는 점만 빼면 if와 같음.
  • 한번 조건을 만족하면 영원히 지속됨. 그래서 멈출 수 있는 로직이 필요함.
python
while 조건:
  print("Hi")
  
# ---

distance = 0

while distance < 20:
  print("I`m running", distand, "kim")
  distance = distance + 1

Python Casino Game

  • 지금까지 배운 내용을 바탕으로 간단한 카지노 게임 만들기
  • while 을 사용해서 유저가 게임에서 이길 때까지 if 조건문을 계속해서 실행시키고자 함
python
from random import randint

print("Welcome to Python Casino")
pc_choice = randint(1, 50)

playing = True

while playing:
  user_choice = int(input("Choose number"))
  if user_choice == pc_choice:
    print("You won!")
    playing = False
  elif user_choice > pc_choice:
    print("Lower!")  
  elif user_choice < pc_choice:
    print("Higher!")

이 링크를 통해 구매하시면 제가 수익을 받을 수 있어요. 🤗

https://inf.run/Trxxf