#!/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 + '.')