-2

I want to generate an ID number. If this random are same regenerate the random number.

import random
while True:
   def generateNumber(ID):
      value = random.randint(1, 2)
      if value != ID:
         return (value)
      generateNumber(value)
  a = int(input('Enter a data: '))
  print("->", generateNumber(a))

Why this function return None value when the data are the same in recursion function?

I debug when the two data are equal, function recursion and call again itself and after generate value changed a different value. But this recursion still worked and return None type data.

XharonX
  • 1
  • 2
  • In its current form, your problem is not reproducible; but apparently, with the necessary fixes, your question is a duplicate of a common beginner FAQ. Going forward, please review the [help] and in particular [How to ask](/help/how-to-ask) as well as the guidance for providing a [mre]. – tripleee May 15 '23 at 12:15

1 Answers1

-1

The function is returning None because there is a recursive call to a function called generate() instead of generateNumber(). Due to this typo, when the condition if value != ID is met, the function calls itself recursively with generate(value) instead of generateNumber(value). Since the function generate() does not exist, it returns None, and ultimately the generateNumber() function also returns None.

To fix the issue, you should change the recursive call to generateNumber(value) so that the correct function is called. Here's the corrected code:

import random

def generateNumber(ID):
    value = random.randint(1, 2)
    if value != ID:
        return value
    return generateNumber(value)

a = int(input('Enter a data: '))
print("->", generateNumber(a))
Zahreddine Laidi
  • 560
  • 1
  • 7
  • 20
  • sorry for my wrong question. If I use wrong function name, **NameError** will be raised. Thanks for your sharing – XharonX May 16 '23 at 07:39