Python getting user input errors

孤者浪人 提交于 2019-11-29 18:11:36

You need to use

return getNum(numList)

instead of

getNum(numList)

in the getNum function. The reason is that you call the getNum function recursively, thus you have to return the accepted value back through all recursions you made. Additionally, you must pass the arguments to each call.

the way you are calling getNum() in "if conditions" is wrong it should be:-

if num <= 0 or num >9:
    print 'Invalid number. Please try again.'
    getNum(numList)

if num in numList:
    print 'Number taken. Please try again.'
    getNum(numList)

A complete solution without the dangers of input, error handling and no problem with a recursion limit.

def get_num(num_list):
    while True:
        try:
            num = int(raw_input('Pick your number: '))
        except ValueError:
            print('Not a number')
        else:
            if 0 < num <= 9:
                if not num in num_list:
                    return num
                else:
                    print('Number taken.')
            else:
                print('Invalid number.')

number_list = []
for _ in range(5):
    number = get_num(number_list)
    print('Number entered: {}'.format(number))
    number_list.append(number)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!