TIL(1) - for 문 실습

9483 단어 Python3Python3

Today's 코드: Number Guessing Game

오늘은 for, while문의 loop을 이용하여 랜덤으로 추출되는 숫자를 추측하는 간단한 프로그램을 만들어 보았다.

import random

highest = 10
answer = random.randint(1, highest)
print(answer) - 정답 미리보기용
guess = 0
print("Please guess the number btw 1 and {}:  ".format(highest))
  • 개요: random 모듈을 이용하여서 파이썬에서 자동 추출해준 숫자를 내가 맞추는 프로그램.
  • Import: 빌트인 모듈인 random을 호출하여서 컴퓨터로 하여금 랜덤으로 숫자를 추측하게 만듬
  • guess = 0: 시작 숫자를 0으로 initializing 하는 개념
  • {}.format(highest): {}란에 (highest) 변수를 호출하는 메소드, 출력결과로 중괄호안에 highest 변수가 대입된다.

 #if 로 만들어보기

 if guess < answer:
     print("Please guess higher")
     guess = int(input())
     if guess == answer:
         print("yes, you got it correctly")
     else:
         print("You are wrong again and failed")

 elif guess > answer:
     print("Please guess lower")
     guess = int(input())
     if guess == answer:
         print("yes, you got it correctly")
     else:
         print("You are wrong again and failed")
  • if 절 끝은 꼭 콜론(:)으로 끝나야 하고 다음줄로 건너뛰고 인덴테이션이 필수로 들어가야한다! 파이썬의 주요 특징: indentation에 따라 코드의 정상작동 여부가 판가름됨!
  • if, elif, else 사용시, 꼭 적힌 순서대로 작성이 되어야 되고 만약 이들 사이의 순서가 바뀌면 코드에러가 난다.
  • if 이후에 elif는 몇 개든 복수로 올 수 있음!
 while로 만들어보기

 if guess == answer:
     print("Wow, you got it first time")

 while guess < answer:
     print("Please guess higher")
     guess = int(input())
     if guess == answer:
         print("yes, you got it correctly")
         break
     else:
         print("You are wrong, guess another one")
         continue

 while guess > answer:
     print("Please guess lower")
     guess = int(input())
     if guess == answer:
         print("yes, you got it correctly")
         break
     else:
         print("You are wrong, guess another one")
         continue
  • While은 Ture/False에 따라 무한 루프의 기능을 가지고 있다. 루핑을 시키려면 While문이 참이 되게 설정하면됨.
  • 위 if로 만든 코드와의 차이점은; while이 루핑의 성격을 띄므로 break 와 continue를 적절히 사용해서 무한 루핑에 빠지는 것을 미연에 방지하고, 또는 오답이 나거나 원하는 int 값 대신 str 값과 같은 오답을 적을 경우에 대비해 원질문으로 계속 돌아가는 기능을 추가할 수 있다.
  • break란?: break라는 키워드를 넣으면 break를 만나는 순간 해당 위치에서 반복문을 빠져나옴.
  • continue란?: 반복문을 빠져나오는게 아니고 해당 조건만 뛰어넘는 기능.

# 모범답안
while guess != answer:
    guess = int(input())

    if guess == answer:
        print("Well done, you guessed it")
        break
    else:
        if guess < answer:
            print("Please guess higher")
        else:
            print("please guess lower")
  • 위에서 작성한 두 코드보다 더 모범이 되는 답안이다. 코드의 간결성, Readability면에서 더 쉽게 읽히고 더 쉽게 이해되는 효율적인 코드이다.
  • 한번에 답을 맞출 수 있는 확률이 매우 적다는 사실에서 기인하여, 애초부터 While guess != answer: 문으로 시작한 코드는 불필요하게 많아지는 if절과 while절을 최소화 하는데 도움이 되었음.

좋은 웹페이지 즐겨찾기