Why isn't the score showing correctly? [closed] - python
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm still a beginner in python, so I decided to make a rock, paper game.
For some reason, when the user or computer wins, it doesn't give them a point until the next round.
import random
games = int(input("")) #how many games
usersc = 0
compsc = 0
for x in range(games):
score = (str(usersc) + "-" + str(compsc))
user = input("") #ROCK, PAPER, SCISSORS
comp = random.randint(0,2)
if user == 'ROCK':
if comp == 0:
print("tie " + score)
elif comp == 1:
compsc += 1
print("loss " + score)
else:
usersc += 1
print("win " + score)
elif user == 'PAPER':
if comp == 0:
usersc += 1
print("win " + score)
elif comp == 1:
print("tie " + score)
else:
compsc += 1
print("loss " + score)
elif user == 'SCISSORS':
if comp == 0:
compsc += 1
print("loss " + score)
elif comp == 1:
usersc += 1
print("win " + score)
else:
print("tie " + score)
else:
print("try again")
if compsc > usersc:
print("loss")
elif usersc > compsc:
print("win")
else:
print("tie")
For example, when the computer wins, it says loss 0-0 when it should say loss 0-1, but then the next round it'll say 0-1.
Any help would be appreciated.
Problem is that you store score in a variable before incrementing it so you will always be 1 game behind. The simplest way to ensure the score is always correct would be to create a function to get the score like this...
def get_score():
return str(usersc) + "-" + str(compsc)
This would ensure the latest user and comp score values are always used.
Using this the code becomes...
import random
games = int(input("")) #how many games
usersc = 0
compsc = 0
def get_score():
return str(usersc) + "-" + str(compsc)
for x in range(games):
user = input("") #ROCK, PAPER, SCISSORS
comp = random.randint(0,2)
if user == 'ROCK':
if comp == 0:
print("tie " + get_score())
elif comp == 1:
compsc += 1
print("loss " + get_score())
else:
usersc += 1
print("win " + get_score())
elif user == 'PAPER':
if comp == 0:
usersc += 1
print("win " + get_score())
elif comp == 1:
print("tie " + get_score())
else:
compsc += 1
print("loss " + get_score())
elif user == 'SCISSORS':
if comp == 0:
compsc += 1
print("loss " + get_score())
elif comp == 1:
usersc += 1
print("win " + get_score())
else:
print("tie " + get_score())
else:
print("try again")
if compsc > usersc:
print("loss")
elif usersc > compsc:
print("win")
else:
print("tie")
When you are printing loss+score or win+score,
first update score as score = (str(usersc) + "-" + str(compsc)) and then print it.
Related
Trying again using multiple loops in a code
I have a problem using the while loop. When I am inputting right answer for example, and the second one is wrong, the tryAgain input is showing. If I want to play again, it just looping in from the start and choosing a topic won't work. If I made it wrong, from the start, it will just loop on its own from inputting answers. tryAgain = True repeat = True while tryAgain: print("TOPICS: \n") print("1. topic 1") print("2. topic 2") print("3. topic 3") print("======================================") num = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: ")) if num > 3: print("There is no given topic") print("==========================") tryAgain = True else: if num == 1: reader = WordListCorpusReader('filename', ['textfile']) with open('filename') as f: text = [line.strip().upper() for line in f] answer = [] while lives > 0: while repeat: index = 0 while index < 10: answerlst = input(str(index + 1) + '. ').upper() if answerlst in text: #condition if the inputted answer is on the file if answerlst in answer: #check if the inputted answer is on the array print("\nYou repeated your answer!") repeat = True continue else: answer.append(answerlst) print("Correct!") repeat = False if answerlst == "ans1": print("Points: 10") points += 10 elif answerlst == "ans2": print("Points: 20") points += 20 elif answerlst == "ans3": print("Points: 30") points += 30 elif answerlst == "ans4": print("Points: 40") points += 40 elif answerlst == "ans5": print("Points: 50") points += 50 elif answerlst == "ans6": print("Points: 60") points += 60 elif answerlst == "ans7": print("Points: 70") points += 70 elif answerlst == "ans8": print("Points: 80") points += 80 elif answerlst == "ans9": print("Points: 90") points += 90 elif answerlst == "ans10": print("Points: 100") points += 100 if points == 550: print("\nCONGRATULATIONS!!!! YOU GOT A PERFECT POINTS OF:", points) break else: if answerlst == "ans1": points += 10 elif answerlst == "ans2": points += 20 elif answerlst == "ans": points += 30 elif answerlst == "ans4": points += 40 elif answerlst == "ans5": points += 50 elif answerlst == "ans6": points += 60 elif answerlst == "ans7": points += 70 elif answerlst == "ans8": points += 80 elif answerlst == "ans9": points += 90 elif answerlst == "ans10": points += 100 lives -= 1 if lives == 0: print("\nGAME OVER!!!!!\n") print("You just got a: ", points) break index +=1 playAgain = input("Do you want to play again? [Y] / [N]: ").upper() if playAgain == 'Y': answer.clear() #to clear the list tryAgain = True I just show the structure of my code in order to understand.
Congratulations, because now you've learned what spaghetti code is - it's just a mess, where you can't properly find errors. When such situation occurs, try to divide your problem into smaller parts (stages). Implement the stages as functions, and your code will become much easier. For example I tried to rework your program like this. ATTENTION: I don't have your files, so this code probably won't work out of the box, I cannot test it. But just try to read it and understand the approaches. After reworking this code I noticed that you never set lives to any number, but you should. def input_topic(): while True: print("TOPICS: \n") print("1. topic 1") print("2. topic 2") print("3. topic 3") print("======================================") topic = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: ")) if topic > 3: print("There is no given topic") print("==========================") else: return topic def read_text(filename): reader = WordListCorpusReader(filename, ['textfile']) with open(filename) as f: text = [line.strip().upper() for line in f] return text def input_answer_and_check(index, text, already_answered): while True: answerlst = input(str(index+1) + '. ').upper() if answerlst in text: if answerlst not in answer: return True, answerlst else: print("\nYou repeated your answer!") else: return False, answerlst def get_answer_points(answerlst) if answerlst == "ans1": return 10 elif answerlst == "ans2": return 20 elif answerlst == "ans3": return 30 elif answerlst == "ans4": return 40 elif answerlst == "ans5": return 50 elif answerlst == "ans6": return 60 elif answerlst == "ans7": return 70 elif answerlst == "ans8": return 80 elif answerlst == "ans9": return 90 elif answerlst == "ans10": return 100 def ask_try_again(): playAgain = input("Do you want to play again? [Y] / [N]: ").upper() return playAgain == 'Y' while True: topic = input_topic() text = read_text('filename') answer = [] lives_left = 5 index = 0 max_index = 10 total_points = 0 while lives_left > 0 and index < max_index and total_points < 550: is_correct_answer, answerlst = input_answer_and_check(index, text, answer) answer_points = get_answer_points(answerlst) total_points += answer_points if is_correct_answer: answer.append(answerlst) print("Correct!") print(f"Points: {answer_points}") else: lives_left -= 1 index += 1 if lives_left == 0: print("\nGAME OVER!!!!!\n") print("You just got a: ", total_points) elif total_points >= 550: print("\nCONGRATULATIONS!!!! YOU GOT A PERFECT POINTS OF:", total_points) if not ask_try_again(): break
I need to make a Number Spelling Game program in python
The program will display random numbers on the screen and requests for the spelling of that number. It checks if the input is correct, then it displays another number. If the input is wrong, then it will send an error message and request another answer. It need to track the number of correct and wrong answers and display it at the end. Here's the what I've done so far: import random numberList = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] word = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"] number = random.sample(numberList, 10) trials = 3 correct = 0 wrong = 0 attempts = 10 print("HELLO, WELCOME TO THE WORD SPELLING GAME!\n") print("SPELL AS MUCH NUMBER AS YOU CAN TO GET POINTS!") print("----------------------------------------------\n") for element in number: spell = str(input('Spell ' + str(element) + ':')) while attempts > 0: if element == numberList[0]: if spell.lower() == word[0]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[0]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 0: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[0]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break elif element == numberList[1]: if spell.lower() == word[1]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[1]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 1: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[1]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break elif element == numberList[2]: if spell.lower() == word[2]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[2]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 1: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[2]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break elif element == numberList[3]: if spell.lower() == word[3]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[3]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 1: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[3]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break elif element == numberList[4]: if spell.lower() == word[4]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[4]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 1: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[4]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break elif element == numberList[5]: if spell.lower() == word[5]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[5]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 1: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[5]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break elif element == numberList[6]: if spell.lower() == word[6]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[6]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 1: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[6]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break elif element == numberList[7]: if spell.lower() == word[7]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[7]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 1: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[7]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break elif element == numberList[8]: if spell.lower() == word[8]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[8]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 1: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[8]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break elif element == numberList[9]: if spell.lower() == word[9]: correct = correct + 1 attempts = attempts - 1 elif spell.lower() != word[9]: trials = trials - 1 print("Incorrect spelling. ", trials, " trials left.") if trials > 1: spell = input('Spell ' + str(element) + ':') if spell.lower() == word[9]: correct = correct + 1 attempts = attempts - 1 else: print("Sorry! Number of trials exceeded.") wrong = wrong + 1 trials = 3 break else: print("\n-----------------------------------------------") print("END OF GAME!\n") print("CORRECT SPELLING SCORE: ", str(correct), "\n") print("WRONG SPELLING SCORE: ", str(wrong))
If I understand your question correctly, this is what you want. I have changed your import at the top. I have also added some more variables at the top. I have replaced all your condition blocks with a regular function. You can see that if have used ".lower()" as this will stop it from being case sensitive. from random import randint numberList = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] word = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"] trials = 3 correct = 0 wrong = 0 attempts = 10 attemp_number = 0 print("HELLO, WELCOME TO THE WORD SPELLING GAME!\n") print("SPELL AS MUCH NUMBER AS YOU CAN TO GET POINTS!") print("----------------------------------------------\n") def validate_user_input(random_number_to_spell): global wrong, correct, attemp_number result = False while result == False and attemp_number < attempts and wrong < trials: print("Please spell the number: ", random_number_to_spell) user_input = input() correct_spelling = word[random_number_to_spell-1] if user_input.lower() == correct_spelling.lower(): print("You spelled ", random_number_to_spell, " correctly") correct = correct + 1 result = True attemp_number = attemp_number + 1 else: print("You did not spell", random_number_to_spell, "correctly") wrong = wrong + 1 attemp_number = attemp_number + 1 while wrong < 3: if attemp_number < attempts: random_number_to_spell = randint(1, 10) validate_user_input(random_number_to_spell) else: break print("You have ", correct, " correctly spelled numbers") print("You have ", wrong, " wrong spelled numbers")
Python: local variable referenced before assigment
I'm very new to python (~1 wk). I got this error when trying to run this code, intended to be a simple game where you guess heads or tails and it keeps track of your score. Is there any way I can avoid this error? I get the error for the "attempts" variable when I run attempts += 1, but I assume I'd get it for "score" too when I do the same. import random coin = ['heads', 'tails'] score = 0 attempts = 0 def coin_flip(): print("Heads or tails?") guess = input() result = random.choice(coin) print("Your guess: " + guess) print("Result: " + result) attempts += 1 if result == guess: print('You guessed correctly!') score += 1 else: print('Your guess was incorrect.') percentCorrect = str((score / attempts) * 100) + '%' print("You have " + str(score) + " correct guesses in " + str(attempts) + ' attempts.') print("Accuracy: " + percentCorrect) print('Do you want to play again?') if input() == 'y' or 'yes': return coin_flip() else: quit() coin_flip()
import random coin = ['heads', 'tails'] score = 0 attempts = 0 def coin_flip(): global attempts global score print("Heads or tails?") guess = input() result = random.choice(coin) print("Your guess: " + guess) print("Result: " + result) attempts += 1 if result == guess: print('You guessed correctly!') score += 1 else: print('Your guess was incorrect.') percentCorrect = str((score / attempts) * 100) + '%' print("You have " + str(score) + " correct guesses in " + str(attempts) + ' attempts.') print("Accuracy: " + percentCorrect) print('Do you want to play again?') if input() == 'y' or 'yes': return coin_flip() else: quit() coin_flip() What was missing: global attempts global score
This is an issue with scoping. Either put the word global in front of attemps and score, or create a class (which would not be ideal for what I assume you're doing).
Python Code Condensation
I am new and a beginner. I need help condensing play_game() below. I need to get it to 18 lines. I would like to call the if and else function from within this code to shorten it by that many lines. def play_game(): # def the plag game function which is the main control of the game level = get_level() quiz = game_data[level]['quiz'] print quiz answers_list = game_data[level]['answers'] blanks_index = 0 answers_index = 0 guesses = 3 while blanks_index < len(blanks): user_answer = raw_input("So what's your answer to question " + blanks[blanks_index] + "? : ") #while, if and else to increment the blanks, answers, and guesses if check_answer(user_answer,answers_list,answers_index) == "right_answer": print "\n Lucky Guess!\n" quiz = quiz.replace(blanks[blanks_index], user_answer.upper()) #prints appropriate responses blanks_index += 1 answers_index += 1 guesses = 3 print quiz if blanks_index == len(blanks): return you_win() else: guesses -= 1 if guesses == 0: return you_lost() break print "Incorrect. Try again only " + str (guesses) + " guesses left!" play_game()
Here's the play_game() subroutine reduced to 18 lines of code: def play_game(): data = game_data[get_level()] quiz, answers = data['quiz'], data['answers'] index, guesses = 0, 3 print quiz while index < len(blanks): user_answer = raw_input("So what's your answer to question " + blanks[index] + "? : ") if check_answer(user_answer, answers, index) == "right_answer": quiz = quiz.replace(blanks[index], user_answer.upper()) print "\nLucky Guess!\n\n" + quiz guesses = 3 index += 1 else: guesses -= 1 if guesses == 0: return you_lost() print "Incorrect. Try again only " + str(guesses) + " guesses left!" return you_win() Tricky to do without being able to actually run the code. Mostly just code cleanup.
Invalid Syntax. No area highlighted [closed]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself. Closed 8 years ago. Improve this question In here somewhere. P.S. Its a cricket game. Nowhere in the code is highlighted. What can I do? Thanks in advance for answering. I need this for an assignment. It worked fin untill I edited the area where it displays the runs scored by the player. I was going to add how many wickets had fallen, but somwhere in this time frame I messed up. Thanks playruns = playtemp playscore = playscore + playruns print("You scored" ,playruns, "runs.", team, "is on", playscore," runs.") elif playruns == 5: print("Your player is out! ", team,"'s current score is:", playscore,"runs") playouts = playouts + 1 if playouts == 5: print("You are all out. Now it is your turn to bowl.") while compouts != 5: print("The Androidz scored", compruns,"runs. The total score of the Androidz is", compscore,"runs.") compruns = 0 comptemp = 0 compouts = compouts + 1 if compouts == 5: print("Game over man, game over.") print("Your score was:", playscore,) print("The Androidz score was:", compscore.) if playscore > compscore: playagain = input("You are the winner. print("The Androidz scored", compruns,"runs. The total score of the Androidz is", compscore.) compruns = 0 comptemp = 0 compouts = compouts + 1 if compouts == 5: print("The Androidz are all out. Congratulations.") while playouts != 5: print("You are now batting.") playmindset = input("For this ball would you like to play agressively 'a', or defensively 'd'") if playmindset == "a": playtemp = random.choice([1,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,]) elif playmindset == "d": playtemp = random.choice([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,5,5,5,]) playruns = playtemp playscore = playscore + playruns if playruns != 5: print("You scored" ,playruns, "runs.", team, "is on", playscore,"runs") elif playruns == 5: print("Your player is out! ", team,"'s current score is:", playscore.) playouts = playouts + 1 if playouts == 5: print("Game over man, game over.") print("Your score was:", playscore,) print("The Androidz score was:", compscore,) if playscore > compscore: playagain = input("You are the winner. Play againg?. 'y' for yes, 'n' for no.") elif playscore < compscore: playagain = input("You are the loser. Play againg?. 'y' for yes, 'n' for no.") elif coinguess != headsortails: while compouts != 5: print("You lost the toss. You are bowling.") print("The Androidz are at the crease. The hot sun beams down upon the ground.\nVictory is a must for", team, "if" , captainname, "wishes to remain as captain.") bowltodo = input("Would you like to bowl or forfeit?") comptemp = random.choice([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,]) if bowltodo == "bowl": compruns = comptemp compscore = compruns + compscore print("The Androidz scored", compruns,"runs. The total score of the Androidz is",compscore,"runs.") compruns = 0 comptemp = 0 compouts = compouts + 1 if compouts == 5: print("The Androidz are all out. Congratulations.") while playouts != 5: print("You are now batting.") playmindset = input("For this ball would you like to play agressively 'a', or defensively 'd'") if playmindset == "a": playtemp = random.choice([1,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,6,6,6,]) elif playmindset == "d": playtemp = random.choice([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,5,5,]) playruns = playtemp playscore = playscore + playruns if playruns != 5: print("You scored" ,playruns, "runs.", team, "is on", playscore.) elif playruns == 5: print("Your player is out! ", team,"'s current score is:", playscore.) playouts = playouts + 1 if playouts == 5: print("Game over man, game over.") print("Your score was:", playscore,) print("The Androidz score was:",compscore,) if playscore > compscore: playagain = input("You are the winner. Play againg?. 'y' for yes, 'n' for no.") elif playscore < compscore: playagain = input("You are the loser. Play againg?. 'y' for yes, 'n' for no.")
You have several syntax errors. The first one is here on line 33 elif playmindset == "d": playtemp = random.choice([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,5,5,]) playruns = playtemp playscore = playscore + playruns print("You scored" ,playruns, "runs.", team, "is on", playscore," runs.") elif playruns == 5: # this line print("Your player is out! ", team,"'s current score is:", playscore,"runs") playouts = playouts + 1 That second elif raises a syntax error because there is no if that precedes it. Perhaps you meant to place the 3 lines in between the 2 elifs in the first one, or maybe make the second elif a new if. That is for you to fix. Furhermore syntax errors are raised because you print stuff like this at several places in your program (lines 52, 66, 84, 120, 122) print("The Androidz score was:", compscore.) the . behind compscore insinuates you are going to call a function on it, or a property or something. Because you do not do that it raises a syntax error. I think you just want to print a dot at the end of the line, in that case just change them to print("The Androidz score was:", compscore + ".")