0

The code is creating a random number from a low value and a high value supplied by the user. Why, when printing the value of the comp_num inside the function it returns the correct value but when printing it at the end of the sequence it is 0.

import random 

comp_num = 0

def generateNumber():
  comp_num = random.randint(low_number,high_number)
  print(comp_num)

low_number = int(input("Please select the minimum number"))
high_number = int(input("Please select the high number"))


generateNumber()
print(f"The comp_num is {comp_num}")
jon
  • 407
  • 4
  • 13
  • Does this answer your question? [Python global variable/scope confusion](https://stackoverflow.com/questions/30439772/python-global-variable-scope-confusion) – matszwecja Nov 09 '22 at 09:23

2 Answers2

1

You need to say inside the function that comp_num is a global variable:

import random 

comp_num = 0

def generateNumber():
    global comp_num
    comp_num = random.randint(low_number,high_number)
    print(comp_num)

low_number = int(input("Please select the minimum number"))
high_number = int(input("Please select the high number"))


generateNumber()
print(f"The comp_num is {comp_num}")

Output:

Please select the minimum number 2
Please select the high number 3
3
The comp_num is 3
Will
  • 1,619
  • 5
  • 23
0

You can also design your function to return a result. Even better tell to the function which input arguments it takes.

Which is a clean approach when you code gets bigger. Furthermore when you look at the function declaration you know what it does.

import random 

def generateNumber(low: int, high: int) -> int:
  return random.randint(low,high)

low_number = int(input("Please select the minimum number"))
high_number = int(input("Please select the high number"))


comp_num = generateNumber(low_number, high_number)
print(f"The comp_num is {comp_num}")
0x0fba
  • 1,520
  • 1
  • 1
  • 11