0

I have a simple program that prompts user to enter number between 1-9 and if the number has been entered previously it will ask the user to enter another number. The user has 10 tries or attempts.

This is only part of what I wanted to do but I am having problems passing the parameter from the getNum method to the method that calls it. If I enter the number between 1-9, it has no problem. The problem starts when I entered the number previously entered and the prompts ask for another number.

def getNum(numList):
    num = input("Pick your number: ")

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

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

    else: 
        return num  

inputList = []
endGame = True
choice = 0  
attempts = 0 
while endGame == False or attempts < 10:

    userNum = getNum(inputList)
    print 'Number entered:', userNum
    inputList.append(userNum)
    print inputList

    attempts += 1 

Can anyone let me know what I did wrong here?

Cryssie
  • 3,047
  • 10
  • 54
  • 81

3 Answers3

1

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.

Abrixas2
  • 3,207
  • 1
  • 20
  • 22
0

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)
Axesh Ajmera
  • 383
  • 2
  • 8
0

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)
Matthias
  • 12,873
  • 6
  • 42
  • 48