代码来自《父与子的编程之旅:与小卡特一起学Python 》第一章,我在原本的基础上做了一些修改。
原来代码中的文字看着不怎么像英文,我对其中一些单词做了修改。(这个纯属无聊)
思路:
- 引入库用来生成1~99之间的随机数
- 通过input()方法给用户输入提示并获得用户输入的数字
- 比较获得的数字与生成的随机数的大小来提示用户下一步的输入
- 输入超过6个数字或者猜中结束程序
- 新增:猜数字结束后询问是否接着猜,如果输入为"Y",重新开始猜数字
同时,我将原来猜数字的代码放在函数里面用来重复调用:
import randomdef guess(): secret = random.randint(1, 99) guess = 0 tries = 0 print("Hey! I'm the Dread Pirate Roberts, and I have a secret!") print("It is a number from 1 to 99. I'll give you 6 tries.") while guess !=secret and tries < 6: guess = int(input("What's your guess?")) if guess < secret: print("Too low!") if guess > secret: print("Too high!") tries = tries + 1 if guess == secret: print("Great! You got it! Found my secret, you did!") else: print("No more guesses! Better luck next time!") print("The secret number was", secret) guess_flag=input("Do you want to countinue(Y/N):") if guess_flag=="Y": guess() guess()
执行结果(采用二分法能比较快速的猜中数字):
很明显,在猜数字结束后,当询问是否继续,回答为"Y"时报错。
我试着把guess()方法放在def guess():前面,然后(貌似JavaScript是可以这么干的呀):
错误原因:
变量名和函数名一样导致guess变量在调用函数前被赋值为整型的一个数字,因此调用不成功
修改如下:
import randomdef myguess(): secret = random.randint(1, 99) guess = 0 tries = 0 print("Hey! I'm the Dread Pirate Roberts, and I have a secret!") print("It is a number from 1 to 99. I'll give you 6 tries.") while guess !=secret and tries < 6: guess = int(input("What's your guess?")) if guess < secret: print("Too low!") if guess > secret: print("Too high!") tries = tries + 1 if guess == secret: print("Great! You got it! Found my secret, you did!") else: print("No more guesses! Better luck next time!") print("The secret number was", secret) guess_flag=input("Do you want to countinue(Y/N):") if guess_flag=="Y": myguess()myguess()
关于变量名和函数名重复的测试:
另外,raw_input()方法在python3.5中已经弃用,python2.7中可用,其他版本我不清楚,可能是python2和python3的一点小区别吧!
参考:
- http://www.ituring.com.cn/tupubarticle/3680【《父与子的编程之旅:与小卡特一起学Python 》第一章】
- https://docs.python.org/3.5/library/random.html【Python3.5 random库】