鱼C论坛

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

[已解决]循环语句的用法

[复制链接]
发表于 2018-9-27 17:59:31 | 显示全部楼层 |阅读模式

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

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

x
这里自己想的一个检验保证正确性的简单代码,如下:

temp = input("不妨猜一下我心里面的数字1~10:")
while temp.isdigit()==False:
    temp = input("不是数字,请重新输入!")
else:
    guess = int(temp)
    while guess>10 or guess<1:
        temp = input("数字范围1~10! 请重新输入!")

这里如果第一次输入的是 15, 第二次在输入ABC 则没法返回第二行去判断。
请教大家,有什么好办法吗?
最佳答案
2018-9-27 21:37:13
import random

goal = random.randint(0, 10)

while True:
    tmp = input('please input guess num: ')

    if (tmp.isdigit() == True):
        guess = int(tmp)

        if (guess > 10) or (guess < 0):
            print("guess out of range\n")
        elif guess == goal:
            print('congratulations, guess right, goal=' + str(goal))
            break;
    else:
        print("it's not a num, please input again\n")
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-9-27 19:51:56 | 显示全部楼层
我一般是
while True:
    temp = inupt('请输入数字')
    try:
       temp   =   int(temp)
       if   0<temp<10:
            print('超出范围')
            continue
    except:
       print('输入的不是数字')
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-9-27 21:37:13 | 显示全部楼层    本楼为最佳答案   
import random

goal = random.randint(0, 10)

while True:
    tmp = input('please input guess num: ')

    if (tmp.isdigit() == True):
        guess = int(tmp)

        if (guess > 10) or (guess < 0):
            print("guess out of range\n")
        elif guess == goal:
            print('congratulations, guess right, goal=' + str(goal))
            break;
    else:
        print("it's not a num, please input again\n")
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-9-28 12:13:05 | 显示全部楼层
本帖最后由 斯林 于 2018-9-28 12:26 编辑

我一般是这样的:
while not x.isdigit():
       print('\a')                                            #发出提示音
       x = input('格式不对,请重新输入:')
x=int(x)
也有时候是这样的:
while isinstance(x,int) == False:
        try:
            x = int (x)
        except:
            print('\a')                         #系统提示音
            x = input('格式不对,请重新输入:')

这两种都是不输入合适的数字不能继续进行下去的
前者不能输入负数,后者可以是负数
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-9-14 02:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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