python doesn't update int in main method

79 views Asked by At

I'm very new to python and I'm trying to get the hang of things. It's a very easy and obvious question, but I don't know the answer. Anyways, I will first post the code:

import pygame,sys
import random

number = 0

def randomNumber(number):
    number = random.randint(1,10)
    print(number)
    return(number)

def main(number):

    randomNumber(number)
    print(number)

if __name__=='__main__':
    main(number)

If I run this program the first number that's printed out is always a number from 1 to 10, but the second number is always zero. I don't want that, I want the second number to be the same number as the first one. How can I do that? So how can I successfully update this int?

1

There are 1 answers

1
Martijn Pieters On BEST ANSWER

You cannot alter a local variable in another function; number in main() is distinct from number in the randomNumber() function.

Your randomNumber() function does return a new value; assign it back to number in main():

def main(number):
    number = randomNumber(number)
    print(number)

Since you are otherwise ignoring the original value of number as you pass it in to randomNumber(), you can remove the arguments altogether:

def randomNumber():
    number = random.randint(1,10)
    print(number)
    return number

def main():
    number = randomNumber()
    print(number)

if __name__=='__main__':
    main()