Programming/Python 웹 스크래퍼 만들기

Python 랜덤 숫자 맞추기

Security Engineer 2022. 11. 3. 19:57

3.4 Python Standard Libarary

컴퓨터가 숫자 하나를 선택하고, user 도 숫자 하나를 선택한다.

user가 숫자를 정확하게 맞췄다면 이기고, 아니면 진다.

user_choice = int(input("choose number ")) 
pc_choice = 50 

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

이전에 했듯이 int는 input 에서 나온 string 형태의 "20" 을 int 형태의 20으로 변환 시켜준다

int : "20" → 20

모든 조건이 들어가므로 굳이 else 를 쓰지 않아도 잘 작동한다.

 

출력값:

choose number 50

You won!

choose number 70

Lower!

choose number 30

Higher!

숫자를 랜덤하게 만들어보자

Python Standard Library 를 이용해서 ( 이미 언어에 포함된 function 들의 그룹 )

이미 python을 다운 받은 순간, 언어에 이미 포함되어 있으니 다운받지 않아도 된다.

Bulit-in → input, int, print 과 같은 내장 함수

어떤 함수나 모듈은 import 를 해서 가져와야한다.

우리는 그중에 random 으로 정수를 가져오는 randint(a,b) 함수를 사용한다.

a <= 숫자 <= b

a보다 크거나 같고 b 보다 작거나 같은 정수를 랜덤하게 가져온다.

from random import randint → random 모듈에서 randint 가져오기

from random import randint 

user_choice = int(input("choose number: ")) 
pc_choice = randint(1,50) 

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

from 과 import 를 사용해서 random 모듈의 randint 를 가져왔다

1~50 사이의(1보다 크거나 같고 50보다 작거나 같은) 랜덤한 정수를 가져오기 때문에

elif 의 print 문에 컴퓨터가 매번 랜덤하게 고른 정수를 알기 위해

computer chose 와, 실제 랜덤하게 픽한 pc_choice를 넣었다.