파이썬 학습 입문 노트(18) 숫자 맞추기 미니게임

2905 단어
프로그램 소개: 숫자를 맞히는 작은 게임, 컴퓨터가 랜덤으로 1-100의 숫자를 생성한 다음에 사용자가 숫자의 값을 맞히면 시스템은 사용자에게'숫자가 너무 높다/숫자가 너무 낮다'고 알린다.
코드 섹션:
#  1
import random

n = random.randint(1,100) #    1-100     
step = 0 #     

print('Game start')
guess = int(input('Please enter an integer from 1 to 100:'))

while True:
    step+=1
    print('step',step)
    if guessn:
        print(guess,'is high')
    else:
        print('You win!')
        break
    guess = int(input('Please enter an integer from 1 to 100:'))
    
print('Game over')

결과: 게임에 버그가 존재합니다. 1. 비숫자 문자를 입력하면 오류가 발생합니다. 2. 게임은 종료 기능이 없습니다.
#  2    BUG   0    
import random

n = random.randint(1,100) #    1-100     
step = 0 #     
print('Game start')

def get_number():
    guess = input('Please enter an integer from 1 to 100:')
    while True:
        if guess.isdigit():#           
            guess = int(guess)
            return guess
        else:
            guess = input('Please enter an integer from 1 to 100:')

guess = get_number()#      

while True:
    step+=1
    print('step',step)
    
    if guess == 0:#    
        print('quit')
        break
    
    if guessn:
        print(guess,'is high')
    else:
        print('You win!')
        break
    guess = get_number()
    
print('Game over')

결과 2 Game start Please enter an integer from 1 to 100:50 step 1 50 is high Please enter an integer from 1 to 100:0 # 0 누르면 게임 step 2 quit Game over 종료
#  3     ,      ,      

import random

n = random.randint(1,100) #    1-100     
step = 0 #     
high = 100
low = 1
print('Game start')

def get_number():
    guess = input('Please enter an integer from 1 to 100:')
    while True:
        if guess.isdigit():#           
            guess = int(guess)
            return guess
        else:
            guess = input('Please enter an integer from 1 to 100:')

guess = get_number()

while True:
    step+=1
    print('step',step)
    
    if guess == 0:#    
        print('quit')
        break
    
    if guessn:
        print(guess,'is high')
        high = guess - 1
    else:
        print('You win!')
        break
    print('You can try',low,'to',high)
    guess = get_number()
    
print('Game over')

결과 Game start Please enter an integer from 1 to 100: 50 step 1 50 is low You can try 51 to 100 Please enter an integer from 1 to 100: 80 step 2 80 is high You can try 51 to 79 Please enter an integer an integer from 1 to 100: 60 step 3 60 is high You can try 51 to 59 Please enter an integer from 1Game over

좋은 웹페이지 즐겨찾기