鱼C论坛

 找回密码
 立即注册
查看: 879|回复: 3

[已解决]学完第五讲的问题

[复制链接]
发表于 2021-8-28 17:04:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在论坛上看完第五讲之后,小甲鱼讲到游戏改进的地方:用户输入错误类型时,题型用户重新输入,并提供了以下代码:
temp = input("不妨猜一下小甲鱼现在心里想的是哪个数字:")
# 这种想法是因为 type(1) 会返回 <class 'int'>,如果 type(temp) 返回结果一致说明输入是整数。
while type(temp) != type(1):
    print("抱歉,输入不合法,", end='')
    temp = input("请输入一个整数:")

我想把这段程序插入到以前写的程序中,结果出现了问题。以前的代码如下:
import random

secret = random.randint(1,10)

temp = input('guess which number I am thinking of : ')
guess = int(temp)
times = 1

while(guess != secret) and (times < 3):
        if guess > secret:
                print('oh,it\'s too big')
        else:
                print('oh, it\'s too small')

        temp = input('try again: ')
        guess = int(temp)
        times = times +1

if (times <= 3) and (guess == secret):
        print('Are you a genius ? ')
        print('hng, there is no award even so')
else:
        print('Well, game ove given you three times')


插入之后,我把上面的代码修改如下:
import random

secret = random.randint(1,10)

temp = input('guess which number I am thinking of : ')
guess = int(temp)
times = 1


if isinstance(temp,int):
        while(guess != secret) and (times < 3):
                if guess > secret:
                        print('oh,it\'s too big')
                else:
                        print('oh, it\'s too small')

                temp = input('try again: ')
                guess = int(temp)
                times = times +1

        if (times <= 3) and (guess == secret):
                print('Are you a genius ? ')
                print('hng, there is no award even so')
        else:
                print('Well, game ove given you three times')
else:
        print('抱歉,输入不合法,', end = ' ')
        temp = input('注意,请输入一个整数:')


但是这样修改是不对的,正如小甲鱼所说, input() 的返回值始终是字符串,所以 type(temp) 永远是 <class 'str'>

我的问题是,怎样修改才能实现原来的功能?
最佳答案
2021-8-28 17:07:32
>>> n = "123"
>>> n.isdigit()
True
>>> m = "abc"
>>> m.isdigit()
False
>>> 
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-8-28 17:07:32 | 显示全部楼层    本楼为最佳答案   
>>> n = "123"
>>> n.isdigit()
True
>>> m = "abc"
>>> m.isdigit()
False
>>> 
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-8-28 17:46:46 | 显示全部楼层
突然想到一个不算太聪明的思路,就是挨个遍历,然后看看它的 ASCII 值是不是在 0 ~ 9 的范围内
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-8-29 09:42:21 | 显示全部楼层

嗯,我往下看了看,小甲鱼给出了说明,用 isdigit()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-17 10:50

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表