python 3用户输入验证

时间:2016-07-03 09:47:28

标签: python function validation

我刚开始学习python3的小游戏。代码如下:

import random

def get_luck():
    lucky_num = random.randrange(0, 101)
    return lucky_num

def filter(num):
    if str.isdigit(num):
        if int(num)>=0 and int(num)<= 101:
            print('number' + num + 'is right, wish you luck')
            return num
        else:
            print('number not in range, type again')
            input_check()
    else:
        print('not a number, type again')
        input_check()
    return num

def input_num():
    input_num = input('type a number between 0 to 100 ===> ')
    print("you just type in : " + input_num)
    return input_num

def input_check():
    r = 0  # <==  just for tracking bug
    first_num = input_num()
    print('first_num is: ' + first_num)
    correct_num = filter(first_num)
    r = r + 1 #<== just for tracking bug
    print(r)
    print('correct_num is:' + correct_num)
    return correct_num

def run_game():
    lucky_num = get_luck()
    any_num = input_check()
    print(any_num, lucky_num)

run_game()

运行此代码后,我尝试第一个数字234然后尝试字符串“eee”,最后输入正确的数字66.我希望看到输出打印66和幸运数字。但是由于以下结果:

type a mumber between 0 to 100 ===> 234
you just type in is : 234
first_num is: 234
number not in range check again
type a mumber between 0 to 100 ===> eee
you just type in is : eee
first_num is: eee
not a number check again
type a mumber between 0 to 100 ===> 66
you just type in is : 66
first_num is: 66
got the right num = 66
1
correct_num is:66
1
correct_num is:eee
1
correct_num is:234
234 98

看来这段代码:     print(r)     print('correct_num is:' + correct_num)

在“你知道 - 什么”原因中循环三次::))!

感谢任何身体都可以提供帮助!

===========================================

感谢您的回答: Asking the user for input until they give a valid response 我解决了我的错误:

import random

def get_luck():
    lucky_num = random.randrange(0, 101)
    return lucky_num


def get_input():
    while True:
        try:
            input_num = input('Number between 0 to 100 ===> ')
            if str.isalpha(input_num) or int(input_num)<0 or int(input_num)>100:
                raise ValueError
        except ValueError:
            print("Not a Number Or Number Not in Range")
            continue
        else:
            break
    return input_num

def run_game():
    lucky_num = get_luck()
    input_num = get_input()
    print(input_num, lucky_num)

run_game()
希望可以帮助别人。

0 个答案:

没有答案