python游戏练手--猜数字

匿名 (未验证) 提交于 2019-12-02 22:51:30
#!/usr/bin/env python#coding=utf-8import random#将玩家猜测过的数字保存到这个变量中,因为玩家还没有做过任何猜测,所以保存的是整数0guessesTaken = 0print('Hello! What is your name?')MyName = input()#判断输入到MyName中的值是否存在#不存在的话,就告诉用户需要输入字符串,不能直接回车或者空格代替if MyName == "":    print('Hello! What is your name? please input string')    MyName = input()else:    #如果没有问题,直接输出客户的输入到控制台,让客户确认    print('Your name is ' + MyName)#生成一个随机数并存入number变量中number = random.randint(1, 20)print('Well, ' + MyName + ', I am thinking of a numbert betwen 1 and 20.')for i in range(1,7):    print('Take a guess.')    # guess = input() #用户输入字符串    # guess = int(guess) #将用户输入的字符串转变为整数格式    #要灵活使用int(),float(),str()和bool()函数    #将上面2个命令组合起来使用,如下guess = int(input())    #捕捉异常,猜数字的时候如果没有接收到数字,需要重新输入    try:        guess = int(input())        if guess < number:            print('Your guess is too low.')        if guess > number:            print('Your guess is too high.')        if guess == number:            break    except ValueError:        print('please input number use int')        guess = int(input())    #记录猜的次数,配合下面的guessesTaken输出    guessesTaken += 1if guess == number:    guessesTaken = str(guessesTaken + 1 )    print('Good Job, ' + MyName + '! You guessed my number in ' + guessesTaken + ' guesses!')if guess != number:    number = str(number)    print('Nope. The number I was thinking of was ' + number + '.')

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!