PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 29, 2022

[FIXED] how to add scores every time the if statement is true?

 August 29, 2022     csv, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing