Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the global variable not showing the correct value

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}")

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading