Startup Data scientist Blog

データ分析系のテック情報を発信します

pythonを使った数字当てゲームの実装

 

 

import random

value = random.randint(1, 10)
count = 0
guess = 0
print('Guess a number between 1 and 10')

while guess != value:
    count += 1
    guess = input(f'Enter guess #{count}:')
   
    if guess.isnumeric():
        guess = int(guess)
       
    else:
        print('Number only, please!')
        continue
       
    if guess > value:
        print('Your guess is too high, try again')
    elif guess < value:
        print('Your guess is too low, try again')
       
else:
    print(f'You guessed it in {count} tries')

基本的にはwhile内のブロックで処理が行われる。python のwhileでループ構造を構築し、条件が満たされている限りコード ブロックを反復処理することが可能となる。

 

Output

Guess a number between 1 and 10
Enter guess #1: Bob
Numbers only, please!
Enter guess #2: Beth
Numbers only, please!
Enter guess #3: 5
You guessed it in 3 tries!