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?
You cannot alter a local variable in another function;
number
inmain()
is distinct fromnumber
in therandomNumber()
function.Your
randomNumber()
function does return a new value; assign it back tonumber
inmain()
:Since you are otherwise ignoring the original value of
number
as you pass it in torandomNumber()
, you can remove the arguments altogether: