猜数字小游戏

2020-05-02  本文已影响0人  希文X

学习收获

程序运行效果

猜数字小游戏.png

程序源码

# 导入用于生成随机数的模块
import random

# 1 随机产生一个1到20之间的数字,作为目标数字
secretNumber = random.randint(1, 20) 
print('I am thinking of a number between 1 and 20.') 

# 2 猜数字(6次机会)
for guessesTaken in range(1, 7):
    # 2.1 提示玩家输入所猜数字
    print('Take a guess.')     
    guess = int(input()) 

    # 2.2 判断输输入数字是否为目标数值,并给出大小关系提示
    if guess < secretNumber:         
        print('Your guess is too low.')     
    elif guess > secretNumber:         
        print('Your guess is too high.')     
    else:         
        break # This condition is the correct guess!

# 3 判断游戏结果,在6次机会中是否成功猜出数字
if guess == secretNumber:     
    print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!') 
else:     
    print('Nope. The number I was thinking of was ' + str(secretNumber)) 
上一篇下一篇

猜你喜欢

热点阅读