Python源码在guess错误后没按照预设效果执行,pythonguess,import rando
Python源码在guess错误后没按照预设效果执行,pythonguess,import rando
import randomsecret = random.randint(1, 100)guess = 0tries = 0print "AHOY! 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 = input("What's yer guess?") if guess < secret: print "Too low, ye scurvy dog!" elif guess > secret: print "Too high, landlubber!" tries = tries + 1 if guess == secret: print "Avast! Ye got it! Found my secret, ye did!" else: print "No more guesses! Better luck next time, matey!" print "The secret number was", secret
我是纯新手 也是看到《和孩子一起学编程》里的这个例子
其实那里面说了 要注意缩进
python是依靠缩进判断语句块
把上面 if guess < secret: 减少一个缩进就行了
if后接的是结果判断,在while循环完成游戏后再进行
import randomsecret = random.randint(1, 100)guess = 0tries = 0print "AHOY! 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 = input("What's yer guess?") if guess < secret: print "Too low, ye scurvy dog!" elif guess > secret: print "Too high, landlubber!" tries = tries + 1if guess == secret: print "Avast! Ye got it! Found my secret, ye did!"else: print "No more guesses! Better luck next time, matey!" print "The secret number was", secret
短短一段代码实在有太多地方值得吐槽了。
首先,input()输入得到的变量一定是String类型的,是无法和Number进行比较的,必须先int一下。
其次,你的逻辑写的实在是有问题。在guess<secret和guess>secret判断玩之后不就剩下guess==secret的情况么,然后你再后头又判断了一次是否相等。也就是说只要是不等的情况下你的代码会返回三行字符串,最开始判断大小于会返回一行,后面的不等于又会返回两行。这应该不是你要的结果。
把判断是否相等的代码归并到一块,把判断tries的代码归并到一块就没有问题了。
以下是示例代码(Python3版请自行转换到Python2):
#! /usr/bin/python3import randomsecret = random.randint(1, 100)guess = 0tries = 0print(""" AHOY! I'm the Dread Pirate Roberts, and I have a secret! It is a number from 1 to 99. I'll give you 6 tries.""")while True: if tries < 6: tries = tries + 1 else: print(""" No more guesses! Better luck next time, matey! The secret number was %s """ % secret,) break guess = int( input("What's yer guess?") ) if guess < secret: print("Too low, ye scurvy dog!") elif guess > secret: print("Too high, landlubber!") else: print("Avast! Ye got it! Found my secret, ye did!")
编橙之家文章,
相关内容
- 有哪些渗透工具是用python语言开发的?,渗透python,目前
- Python生成固定大小文件最高效方法,python生成大小,问,
- flask CSS文件'ascii' codec问题,flaskcodec,flask 版本使用0.
- JS是学习python爬虫必要了解的知识点吗,python爬虫,额
- 求指导django中one-to-many和foreign key的应用及用途,djang
- Python什么方法可以将XML转换为JSON格式,pythonjson,由于老
- Python mysql数据牗executemany指定写入表报错,pythonexecute
- python3一当前函数调用另一个函数中的数据怎么实现,
- python import模块导入ImportError: No module named A路径应该没问
- 请问python 中cx_oracle使用where col in (:1)的方式的时候,是
评论关闭