鱼C论坛

 找回密码
 立即注册
查看: 2537|回复: 6

[已解决]《零基础入门学习Python》005课-课后练习

[复制链接]
发表于 2020-11-30 14:33:12 | 显示全部楼层    本楼为最佳答案   
输入合法性判断,正如前面鱼油回答,input返回的是一个字符串,所以会进入死循环,
程序还有一个问题,我觉得if 语句还可以改,
if times >= 2:
    print('还有%d次机会'%(times),end='')
    temp = input('请输入一个整数')
这样当我们改变次数times 的时候,程序运行才合理。

import random
times =10
secret = random.randint(1,10)

guess = 0
print('我们来玩个游戏吧')
temp =int(input('请输入我心里想的一个数字:'))

while type(temp) != type(1):
    print('抱歉,输入不合法,', end='')
    temp = input('请输入一个整数:')
while (guess != secret) and (times > 0):      
    guess = int(temp)        
    times= times - 1
    if guess == secret:
        print('哇,被你猜中了!')
        print('但是猜中了也没有奖励~')
        break
    else:
        if guess > secret:
            print('大了大了')
            if times >= 2:
                print('还有%d次机会'%(times),end='')
                temp = input('请输入一个整数')
            else:
                if times == 1:
                    print('还有1次机会',end='')
                    temp = input('请输入一个整数:')
                else:
                    print('没机会啦')
        else:
            print('小了小了')
            if times >= 2:
                print('还有%d次机会'%(times),end='')
                temp = input('请输入一个整数')
            else:
                if times == 1:
                    print('还有1次机会',end='')
                    temp = input('请输入一个整数')
                else:
                    print('没机会啦')
               
print('游戏结束')
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2020-12-1 21:13:03 | 显示全部楼层
Python萌新小杨 发表于 2020-11-30 19:53
请问('还有%d次机会'%(times)里的%d是什么意思呀

是print函数的格式化输出,运行你就会有体会。还可以百度了解得详细些。比如:https://www.cnblogs.com/hokky/p/8434236.html
https://my.oschina.net/liurihui/blog/3073746
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-10-7 05:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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