Raspberry Pi_Kor_23.5.6 간단한 사례를 이용한 Python 학습


Published Book on Amazon


All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 1
All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 2


출판된 한글판 도서


최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (상)
최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (하)


Original Book Contents


23.5.6  간단한 사례를 이용한 Python 학습

 

   숫자 맞추기 Game Example

 

이 프로그램은 대화식의 숫자 맞추기 게임으로, 사용자가 1부터 99까지의 숫자를 맞추도록 한다.

 

여기서는 무작위 숫자를 얻기 위해서 "randint" 함수를 사용하고 있다. 이 프로그램은 "while" loop을 사용하여 사용자가 숫자를 맞출 때까지 계속 실행된다.  

 

import random

n = random.randint(1, 99)

guess = int(raw_input("Enter an integer from 1 to 99: "))

while n != "guess":

    print

    if guess < n:

        print "guess is low"

        guess = int(raw_input("Enter an integer from 1 to 99: "))

    elif guess > n:

        print "guess is high"

        guess = int(raw_input("Enter an integer from 1 to 99: "))

    else:

        print "you guessed it!"

        break

    print

 


 

   평균값 계산 Example

 

다음 사례는 3개의 값을 입력 받아서 평균값을 계산하는 프로그램으로 반드시 정수를 입력해야 한다.

 

# Get three test score

round1 = int(raw_input("Enter score for round 1: "))

round2 = int(raw_input("Enter score for round 2: "))

round3 = int(raw_input("Enter score for round 3: "))

  

# Calculate the average

average = (round1 + round2 + round3) / 3

 

# Print out the test score

print "the average score is: ", average


 

Leave a Reply