Python 3 changing variable inside function without using global variables - python

So i am currently working on a university project, therefore i can't really paste my code to be more specific, but we have this stupid rule that global variables are not allowed and using them would lead to points removal. So my question is:
I am making a roll the dice game, where a couple of players take turns and i need a variable that identifies which player is on turn. I have a function, which represents each turn and a second, which calls the first function multiple times, which is equal to the number of players. Lets say i have 3 players:
def func1():
player_on_turn = 1
result = 0
print('Player',player_on_turn,'is on turn.')
#something
return result
def func2():
players = 3
for player in range(1,players+1):
player = func1()
func2()
So this variable player_on_turn has to change 3 times, meaning for each call of the function. The first call it is equal to 1, the second to 2, etc.
I've done this already with global variable, but apparently i can't use them, because "it makes the code hard to read". In the first function i am already using return for a one value which changes inside the function and is being reset each call. Is there a way i could probably do this? Thanks in advance!

You can use Function Parameters to pass data between functions.
You can also use a Class to create objects that store data without global variables.

Related

How to access multiple values from a function while only calling the function one time?

I'm looping through documents looking for occurrences of words contained in a corpus list. I noticed that every time I use a value returned from the function, it calls the whole function again.
def function1():
print ("function1")
x = 1
y = 2
return (x,y)
print (function1()[0])
print (function1()[1])
I'm getting as a result...
function1
1
function1
2
which indicates that the function ran 2 times. Is there a way to just have the function run one time?
So hopefully the output would look like...
function1
1
2
The code is taking hours to run, and I think this is part of the reason why. Edit: I realize I could assign the output tuple to a variable, but am trying to avoid global variables.
Assign function1 result to a variable.
This is the example:
Example = function1()
print(Example[0])
print(Example[1])
It will only run the function once and you can access the data that returned by that function as many times as you like without running the function again.
Yes.
Assign the return value of the function to a variable.
Then access the variable as many times as you need to -- the function need not be called again (unless it is a function which will give you a different return value when called again -- such as getting the current time. But you wouldn't be asking the question if you were doing something like that.)

How do I make a variable created inside a function become global?

I have a function in a program that I`m working at and I named a variable inside this function and I wanted to make it global. For example:
def test():
a = 1
return a
test()
print (a)
And I just can`t access "a" because it keeps saying that a is not defined.
Any help would be great, thanks.
I have made some changes in your function.
def test():
# Here I'm making a variable as Global
global a
a = 1
return a
Now if you do
print (a)
it outputs
1
As Vaibhav Mule answered, you can create a global variable inside a function but the question is why would you?
First of all, you should be careful with using any kind of global variable, as it might be considered as a bad practice for this. Creating a global from a function is even worse. It will make the code extremely unreadable and hard to understand. Imagine, you are reading the code where some random a is used. You first have to find where that thing was created, and then try to find out what happens to it during the program execution. If the code is not small, you will be doomed.
So the answer is to your question is simply use global a before assignment but you shouldn't.
BTW, If you want c++'s static variable like feature, check this question out.
First, it is important to ask 'why' would one want that? Essentially what a function returns is a 'local computation' (normally). Having said so - if I have to use return 'value' of a function in a 'global scope', it's simply easier to 'assign it to a global variable. For example in your case
def test():
a = 1 # valid this 'a' is local
return a
a = test() # valid this 'a' is global
print(a)
Still, it's important to ask 'why' would I want to do that, normally?

Can the same parameters be used in 2 different definitions? Python

Say I had a function in Python:
def createCube(no_of_cubes):
This function creates cubes and the number of cubes it creates is set by the parameter: no_of_cubes
If i then wanted to create another function:
def moveCubes():
and I wanted the parameter no_of_cubes to be used in this function, and for the parameter to use the same integer that has been inputted for the first function. How would I do so? Or is it not possible?
A parameter is merely an argument to a function, much like you'd have in a maths function, e.g. f(x) = 2*x. Also like in maths, you can define infinite questions with the same arguments, e.g. g(x) = x^2.
The name of the parameter doesn't change anything, it's just how your function is gonna call that value. You could call it whatever you wanted, e.g. f(potato) = 2 * potato. However, there are a few broad naming conventions—in maths, you'd give preference to a lowercase roman letter for a real variable, for example. In programming, like you did, you want to give names that make sense—if it refers to the number of cubes, calling it no_of_cubes makes it easier to read your program than calling it oquhiaisnca, so kudos on that.
I'm not sure how that bit fits into your program. A few of the other answers suggested ways to do it. If it's just two loose functions (not part of a class), you can define a variable outside the functions to do what you want, like this:
1: n = 4 # number of cubes, bad variable name
2: def createCube(no_of_cubes):
3: # things
4: def moveCubes(no_of_cubes):
5: # different things
6: createCube(n)
7: moveCubes(n)
What happens here is that line 6 calls the function createCube and gives it n (which is 4) as a parameter. Then line 7 calls moveCubes giving it the same n as a parameter.
This is a very basic question, so I'm assuming you're new to programming. It might help a lot if you take some python tutorial. I recommend Codecademy, but there are several others you can choose from. Good luck!
It is possible. But that two definitions get that parameter as their own one. I mean that parameter works only the definition scope. It may not be harmful for another same name parameter on different definitions.
If you cannot, probably you shouldn't do it.
If they're two separate functions (not nested or so), they should not share parameters.
If they do have connection in some way, a better way is to define a class:
class Cube:
def __init__(self, no_of_cubes):
self.no_of_cubes = no_of_cubes
def create_cube(self):
# use self.no_of_cubes
pass
def move_cubes(self):
# use self.no_of_cubes
pass
c = Cube(no_of_cubes)
c.create_cube()
c.move_cubes
Unless you know what you're doing, don't define global variable.
You can load the function moveCubes() inside createCube(). For example:
def createCube(no_of_cubes):
# Do stuff
moveCubes(no_of_cubes)
def moveCubes(no_of_cubes):
# Do more stuff
Or you could define no_of_cubes out of the functions so it is accessible to all.
no_of_cubes = 5
def createCube():
global no_of_cubes
# Do stuff
def moveCubes():
global no_of_cubes
# Do stuff

Functions access to global variables

I am working on a text-based game to get more practice in Python. I turned my 'setup' part of the game into a function so I could minimize that function and to get rid of clutter, and so I could call it if I ever wanted to change some of the setup variables.
But when I put it all into a function, I realized that the function can't change global variables unless you do all of this extra stuff to let python know you are dealing with the global variable, and not some individual function variable.
The thing is, a function is the only way I know of to re-use your code, and that is all I really need, I do not need to use any parameters or anything special. So is there anything similar to functions that will allow me to re-use code, and will not make me almost double the length of my code to let it know it's a global variable?
You can list several variables using the same global statement.
An example:
x = 34
y = 32
def f():
global x,y
x = 1
y = 2
This way your list of global variables used within your function will can be contained in few lines.
Nevertheless, as #BrenBarn has stated in the comments above, if your function does little more than initializating variables, there is no need to use a function.
Take a look at this.
Using a global variable inside a function is just as easy as adding global to the variable you want to use.

Python - Updating Variable in For Loop [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed last month.
So I decided to write Monopoly in Python, but I'm having some trouble updating the players location. I wrote a for loop that iterates through the players, rolls the dice for each one, and then updates their location. The problem is that the location variable isn't keeping the latest location, it keeps resetting back to 0 at the start of the for loop. Here's my code:
player1location = 0
def turn(numberPlayers, player, player1location, Board):
for player in range(numberPlayers):
player = 'Player'+str(player+1)
print 'It\'s', player, 'turn!'
print player1location
rollDice = raw_input('Press Enter to roll the dice!')
diceRoll = random.randint(1,6)
print player, 'rolled a', diceRoll
player1location = player1location + diceRoll
print 'You landed on', player1location
print '\n'
while True:
turn(numberPlayers, player, player1location, Board)
I can provide more of the code if necessary, but I think this is everything that controls the players location. Thanks!
EDIT: So apparently I'm changing the local variable instead of the global variable. How would I change the global variable instead?
You have function parameter with the same name as your target variable which you want to update.
Due to which, any changes you make is made to the function parameter, and not to the global variable. That's because the function creates a local scope for the paremeter you are passing to the function. So, it overshadows the variable defined with the same name globally.
So, either change the name of the function parameter player1location or the name of the global variable.
Note that you have two variables called player1location - one is defined globally in your first line (outside of any function): player1location = 0, and the second one is created locally each time you call your function: def turn(numberPlayers, player, player1location, Board). Even though they have the same name, these are two distinct variables in python, because they are defined in different scopes.
There are a couple of ways you could fix this.
You could remove player1location from your function definition, and then you'd always be changing the globally-scoped variable. However, from your naming convention, I'm guessing that you'd like to reuse the function for other players as well (although it still couldn't hurt to try it, to help you understand how it works).
The better way would likely be to return the new player location at the end of your function (return player1location), and then assign it to the globally-scoped location upon return (player1location = turn(numberPlayers, player, player1location, Board)).

Categories