This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 6 months ago.
I have function which checks the score and will(I haven't finished) increases level if the score hits the given score, my function:
def levels(Score):
if score >= 100:
enemies = 6
velocity = 2
and I'm calling it in the game loop:
levels(score)
The function never gets executed, my source code http://pastebin.com/JPZSTA6a
Line: 35-38 and 150
Thank you
The function is being called, but you are assigning to enemies and velocity in the function, so they are local to the function, and are then discarded when the function returns. So your function is called, but has no lasting effect.
You need to read about locals and globals in Python. As others point out you also have both Score and score here. Python is case-sensitive, those are different names.
You have if score >= 100 when you probably meant if Score >= 100. The function gets executed, it's just that the if statement always evaluates to false.
It's a scoping issue, the variables you're referring (enemies and velocity) to are created further down inside a while loop so they're not in scope in the function where you're trying to modify them. You need to read up on Execution model it should be able to clarify scoping rules.
Your code, paraphrased:
def game():
def levels(Score):
print 'levels!'
while start == True:
print 'start is indeed True!'
while not finish or falling:
'I am not Finnish'
for i in range(enemies):
'alas for I am beset by enemies!'
levels(score)
So, why isn't levels() being called? I suppose one of those many control flow items doesn't go the way you want. I can't say for example whether or not your enemies variable is empty but I can tell you that print is your friend.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm testing stuff with pythong (I'm really mediocre and still learning); I made a game thing and i want to count how many times wins/guesses. I've tried some ways that define a function but the variable must be called before the function so it resets; again I'm really bad so I'd appreciate if someone can write me an example/explanation. PS: I'm new to stack overflow if you can't tell so apologies if didnt use a specific format or something :D
If you want to count wins, a good way to do this is with a for loop. These are sections of code with repeat a certain number of times. You can put your main game structure in a function, which is completed at each iteration of the loop. So let's say your actual game is a function called main_game():
def main_game():
# all your game code can go here
if won: # you can change this to reflect your own code
return True # the return statement passes a value back to the place that called it
else:
return False
A side note: if you don't understand basic python constructs like return or def, take a look at the python docs.
We can then loop this function round. The range() here takes an argument which represents the number of times this should be carried out, so in this case 10 times.
wins = 0
for i in range(10): # this a for loop. "i" represents the iteration of the loop.
result = main_game() # this calls the function
if result == True: # in other words, if they've scored
wins = wins+1 # add one to the wins total
The expression result = main_game() basically assigns whatever main_game() returns to a variable called result. That's why we use return True rather than print(True) in our main_game function, because it sends that value back to result.
Then it checks to see if the user won, and if so, increments their win total before iterating. Notice there are no elif or else statements, because if result is anything other than True, we don't have to do anything with the win total.
This is a basic skeleton for how you can use a counter which goes up based on a condition to do with your game, and requires some expansion, but should give you a few pointers.
I'm new to programming and have just hit my first speed bump since starting this semester. We have been working in python and our latest assignment has us altering a previous program to use functions. I am understanding how to use them and what not, but some small things with local variables I think I lack in some conceptual understanding.
I use pycharm to write my assignments, and I can see it states one of my variables is unused and I don't understand why or how to fix it. I've been tinkering for a couple hours and am lost.
# Function "checkName" takes in 2 parameters
# The first is name, which will be given by user input
# The second is nameList, which comes from the function getNamesList
def checkName(name, nameList):
for i in range(0, len(nameList)):
if name == nameList[i]:
rank = i + 1
break
else:
rank = 0 ## This rank is undefined ##
return rank
Any pointers on what I'm doing wrong? An explanation of the differences between defining local and global variables would be appreciated as well!
You get the error "Local variable 'rank' value not used" on the line rank = i + 1 because the the break statement on the next line causes the the function to end without ever reading the value from rank. This is only the case because your return statement is indented too far. Move it back one level of indentation so it doesn't return until the loop is done and the warning will go away.
def checkName(name, nameList):
for i in range(0, len(nameList)):
if name == nameList[i]:
rank = i + 1
break
else:
rank = 0 ## This rank is undefined ##
return rank
I can tell you that if you hit your 'break' statement, you're not going to be returning anything, because you've got your indentation wrong. You need to take one indentation out of your return.
I can also tell you a little bit about global and local variables, in lay-terms: Any variable you define inside your function, such as 'rank', will not persist outside the function. If you run the above and then try to call 'rank' outside of your function, you'll be calling a blank variable (unless you specifically named another variable 'rank'). This enables you to use rank inside the function without fearing conflict with variables outside the function. In general, you want to avoid making any truly 'global' variables, but a variable named outside of a function is more 'global' than one named inside one.
As for what pyCharm is flagging, I'm not sure, because I don't use the program. Are you calling your function anywhere? It could be letting you know that you're defining your function, and then not calling it.
By reading your code, I understand that this functions returns the rank or the index of a name in a given list of names.
You have a wrong indentation on the return statement.
So to improve your code, check this:
def checkName(name, nameList):
for i in range(nameList):
if name == nameList[i]:
return i + 1
# you don't need an else here, just return -1 or 0 or None ( by default )
# whenever `name` doesn't exists on the nameList
# not very pythonic
return 0
Your code was not always using the local variable rank because of the wrong indentation.
From the point of view of the code as written, rank is defined but not used - you set it and break, so it looks like nothing is done with it. Once again, it's that indent others have mentioned.
Thank you all very much for the quick and helpful replies! My indentation was off, silly error. Honestly don't know how I overlooked it so many times.
I also appreciate the distinction on local variables. I think my previous understanding was alright, but the pycharm note i was getting threw me for a loop.
Probably the shortest it can be:
nameList = ["a", "b", "c"]
def checkName(name, nameList):
return(nameList.index(name) + 1 if name in nameList else 0)
for i in ["a", "b", "c", "d"]:
print(checkName(i, nameList))
Result:
1
2
3
0
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.
I have a variable distance whose value is being constantly updated by a function a.
Inside the function, there is an infinite loop which keeps on changing the value of distance.
I want to work with this variable and be able to write statements like
if distance ==0:.
I feel this won't be possible as we want to execute two tasks simultaneously, one which is updating the value of distance and the other one being the conditional statement. The code would never reach the conditional statement since it will remain inside the infinite loop forever.
How do I do this?
Added some code for reference:
def a():
global distance
while True:
distance+=1
def b():
#want to call a so that distance keeps on getting updated
if distance < 100:
print ("I am the best")
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)).