Issue
I want to add a scoring system on my code. Every time that the player gets a correct answer, a 5 point score will be added to the player's overall score. This is my code below:
def easyLevel():
n = 2
while n <= 7:
pattern = random.choice(string.ascii_lowercase)
for i in range(n-1):
pattern = pattern + " " + random.choice(string.ascii_lowercase)
print("The pattern is: ")
print(pattern)
easyAns = str(input("What was the pattern?: "))
if easyAns == pattern:
n = n + 1
print("That's correct!")
else:
print("Sorry, that's incorrect.")
break
How can I save the scores in a file? Along with the last pattern that the player answered correctly.
Also, is there a way I could print the pattern and score outside of this function? if so, how can I do that?
Would appreciate your help. Thank you!
Solution
What if you use a global variable to store the score?
import random
import string
score = 0 # set the global variable score to 0
def easyLevel():
global score #this tells python that when we assign to score in this function, we want to change the global one, not the local one
n = 2
while n <= 7:
pattern = random.choice(string.ascii_lowercase)
for i in range(n-1):
pattern = pattern + " " + random.choice(string.ascii_lowercase)
print("The pattern is: ")
print(pattern)
easyAns = str(input("What was the pattern?: "))
if easyAns == pattern:
n = n + 1
print("That's correct!")
score = score + 5 # so when we change score in here, it changes the global variable score
else:
print("Sorry, that's incorrect.")
break
An alternative would be to use the score as a local variable, and return it when done. This would however not negate the need for a global score variable in some capacity.
Here's some more info from Stack: Using global variables in a function
Happy coding!
Answered By - iteratedwalls Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.