hello below is where my code is coming with an issue at line 64 near quiz = difficulty_level(user_level) can anyone help? every time i run this it comes in with this error and for the life of me i cannot figure out what is going on or what is wrong
def play():
quiz = difficulty_level(user_level):
print
print quiz
print "\nYou have only 5 tries best of luck.\n"
answers_list = relate_answer(user_level)
blanks_index = 0
answers_index = 0
number_of_guesses = 5
guesses_limit = 0
while blanks_index < len(blanks):
user_answer = raw_input("type in your answer for " + blanks[blanks_index] + ": ")
if check_answer(user_answer,answers_list,answers_index) == "Correct":
print "nice job! that is the right answer!\n"
quiz = quiz. replace(blanks[blanks_index],user_answer)
blanks_index += 1
answers_index += 1
number_of_guesses = 5
print quiz
if blanks_index == len(blanks):
print "Congrats"
else:
number_of_guesses -= 1
if number_of_guesses == guesses_limit:
print "Game over!"
break
elif number_of_guesses < guesses_limit:
print "invalid"
break
else:
print "incorrect try one more time"
print "You have" + str(number_of_guesses) + "This many guesses left"
play()
Change
while blanks_index < len(blanks):
user_answer = raw_input("type in your answer for " + blanks[blanks_index] + ": ")
if check_answer(user_answer,answers_list,answers_index) == "Correct":
to
while blanks_index < len(blanks):
user_answer = raw_input("type in your answer for " + blanks[blanks_index] + ": ")
if check_answer(user_answer,answers_list,answers_index) == "Correct":
Related
I'm trying to make a guessing game with an additional line: You have "x" guesses left.
I basically wrote these codes :
correctanswer = "Stackoverflow"
useranswer = ""
guesscount= -2
guesslimit = 4
outofguesses = False
while useranswer != correctanswer and not outofguesses == True:
if guesscount <= guesslimit:
useranswer = input("Enter your answer : ")
guesscount += 1
guesslimit -= 1
print("Wrong answer , you have " + str(guesslimit) + " guess rights left")
else: outofguesses = True
if outofguesses:
print("You lost , sorry")
else:
print("You won!")
But what I can't make it, that when the answer is correct, it still says :
("Wrong answer , you have " + str(guesslimit) + " guess rights left") and then "You won!"
What I want to do is, when given the correct answer I don't want that line to appear. Can you help me?
Aside from doing some weird stuff with guesslimit, you are always printing "wrong answer" directly after the user answers, without performing any check to see if it's correct.
correctanswer = "Stackoverflow"
guesscount = 0
guesslimit = 3
user_won = False
while guesscount < guesslimit:
answer = input("Enter your answer : ")
if answer == correctanswer:
user_won = True
break
else:
print(f"Wrong answer, you have {guesslimit - guesscount} guesses left")
guesscount += 1
if user_won:
print("You won!")
else:
print("You lost , sorry")
your print line is in the while loop after guessing and before checking if it is true, which means it will still execute.
One way to fix this is by using a simple if statement. Your code could look something like this
(note that the guesslimit and guesscount will still be changed, if you dont want this simply put the if statement above the code that changes them).
correctanswer = "Stackoverflow"
useranswer = ""
guesscount= -2
guesslimit = 4
outofguesses = False
while useranswer != correctanswer and not outofguesses == True:
if guesscount <= guesslimit:
useranswer = input("Enter your answer : ")
guesscount += 1
guesslimit -= 1
if (useranswer != correctanswer):
print("Wrong answer , you have " + str(guesslimit) + " guess rights left")
else: outofguesses = True
if outofguesses:
print("You lost , sorry")
else:
print("You won!")
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).
import random
import time
print ("Welcome to the Game")
print ("You must complete the next 10 Multiplication Questions to be truly ready for the challenges of life")
print ("")
choice = input("Are you ready? Y / N: ")
print("")
def play():
while questions != 10:
num1 = random.randrange(9,17)
num2 = random.randrange(6,17)
print("What does " + str(num1) + " x " + str(num2) + " = ")
guess1 = input("Your guess?: ")
answer1 = (num1*num2)
if int(guess1) == answer1:
print("Correct")
time.sleep(1)
counter = counter + 1
questions = questions + 1
print("")
else:
print("Your answer was Wrong")
time.sleep(1)
print("The real answer was")
time.sleep(1)
print (str(answer1))
questions = questions + 1
print("")
if questions == 10:
print ("You got " + str(counter) + " out of 10")
return
play()
From the information available for now, I would say that this is because you did not assign any value for
questions
variable
To solve this, simply add
questions = 10 # or other value you may want
at the very start of the play() function
You need to initialize questions variable to 0 before while loop and also initialize counters variable to 0 and return statement should be outside while loop.
Below is the corrected code
import random
import time
print ("Welcome to the Game")
print ("You must complete the next 10 Multiplication Questions to be truly ready for the challenges of life")
print ("")
choice = input("Are you ready? Y / N: ")
print("")
def play():
#initialization
questions,counter =0,0
while questions != 10:
num1 = random.randrange(9,17)
num2 = random.randrange(6,17)
print("What does " + str(num1) + " x " + str(num2) + " = ")
guess1 = input("Your guess?: ")
answer1 = (num1*num2)
if int(guess1) == answer1:
print("Correct")
time.sleep(1)
counter = counter + 1
questions = questions + 1
print("")
else:
print("Your answer was Wrong")
time.sleep(1)
print("The real answer was")
time.sleep(1)
print (str(answer1))
questions = questions + 1
print("")
if questions == 10:
print ("You got " + str(counter) + " out of 10")
# return outside while loop
return
play()
An example for you:
#!/usr/bin/env python3.6
import time
from random import randrange
def play():
counter = 0
for i in range(10):
num1 = randrange(9, 17)
num2 = randrange(6, 17)
print(f"What does {num1} x {num2} = ")
guess = input("Your guess?: ")
answer = str(num1 * num2)
if guess == answer:
print("Correct\n")
counter += 1
else:
print("Your answer was Wrong")
print(f"The real answer was {answer}\n")
time.sleep(0.5)
print("You got " + str(counter) + " out of 10")
def main():
print(
"Welcome to the Game\n"
"You must complete the next 10 Multiplication Questions "
"to be truly ready for the challenges of life\n"
)
choice = input("Are you ready? Y / N: ")
if choice.upper() == "N":
return
print()
play()
if __name__ == "__main__":
main()
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.
I am new to Stack overflow and have only recently began learning Python Programming. I am currently using Python 2.7 so there will be differences in my code compared to Python v3.
Anyway, I decided that I wanted to write a program that I can let my nephew and niece try out. The program created is a test with mathematics.
The code may not be the best or compact as it should be but it's my first go at it.
I have attached the code I have typed so far here. Please let me know your thoughts and any feedback.
My main question though is here:
I want to store the correct answers that the user-inputs in a variable. I want to then be able to output the number of questions that the user has got correct at the end of the test.
For example, if the user decides to take on a challenge of 5 problem sets and gets 3 correct, I want the program to output, you got 3/5 correct. I have a feeling that this will be something very simple but I have not yet thought of it.
I have tried to create a variable such as answersCorrect = 0 and then just answersCorrect += 1 to increment each time an answer is correct but I can't seem to make that work so I have left it off.
Any suggestions for this?
from sys import exit
import random
from random import randint
import math
def addition():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "+" + str(num_2) + "? "))
generatedAnswer = (num_1 + num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
print "Would you like to solve more problems?"
repeatAnswer = raw_input("> ")
if repeatAnswer == "Yes" or repeatAnswer == "Y" or repeatAnswer == "YES":
start()
elif repeatAnswer == "No" or repeatAnswer == "N" or repeatAnswer == "NO":
print "Thank you for completing the test anyway..."
exit()
else:
print "You have not entered a valid response, goodbye!"
exit()
def subtraction():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "-" + str(num_2) + "? "))
generatedAnswer = (num_1 - num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
print "Would you like to solve more problems?"
repeatAnswer = raw_input("> ")
if repeatAnswer == "Yes" or repeatAnswer == "Y" or repeatAnswer == "YES":
start()
elif repeatAnswer == "No" or repeatAnswer == "N" or repeatAnswer == "NO":
print "Thank you for completing the test anyway..."
exit()
else:
print "You have not entered a valid response, goodbye!"
exit()
def multiply():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "x" + str(num_2) + "? "))
generatedAnswer = (num_1 * num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
print "Would you like to solve more problems?"
repeatAnswer = raw_input("> ")
if repeatAnswer == "Yes" or repeatAnswer == "Y" or repeatAnswer == "YES":
start()
elif repeatAnswer == "No" or repeatAnswer == "N" or repeatAnswer == "NO":
print "Thank you for completing the test anyway..."
exit()
else:
print "You have not entered a valid response, goodbye!"
exit()
def divide():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "/" + str(num_2) + "? "))
generatedAnswer = (num_1 / num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
print "Would you like to solve more problems?"
repeatAnswer = raw_input("> ")
if repeatAnswer == "Yes" or repeatAnswer == "Y" or repeatAnswer == "YES":
start()
elif repeatAnswer == "No" or repeatAnswer == "N" or repeatAnswer == "NO":
print "Thank you for completing the test anyway..."
exit()
else:
print "You have not entered a valid response, goodbye!"
exit()
def start():
# Welcome messages
print "Welcome to this amazing game called Mathemagica!"
print "I hope you are ready for an amazing challenge :D"
print "My name is Mr MATHEMAGIC and i'm here to test you on your abilities"
print "...."
print "So, to begin please enter your Name: "
name = raw_input("> ")
print "Right. ", name, " Please enter your Age: "
age = raw_input("> ")
print "Thanks! So, ", name, " are you ready to begin your Mathematics Test? (Yes / No)"
response = raw_input("> ")
# Response Dependant directing to a particular function to be CALLED
if response == "Yes" or response == "YES" or response == "Y" or response == "y":
print """Which test would you like to take first? Please select an option below:
\t1. Addition
\t2. Subtraction
\t3. Multiplication
\t4. Division
"""
# Resonse here
problemSolver = raw_input("> ")
# Evaluating what option has been selected
if problemSolver == "1":
addition()
elif problemSolver == "2":
subtraction()
elif problemSolver == "3":
multiply()
elif problemSolver == "4":
divide()
else:
print "You have not entered a valid option, Goodbye!"
exit()
elif response == "No" or response == "NO" or response == "N" or response == "n":
print "That's fine. Have a good day :)"
exit(0)
else:
print"You have not entered a valid response, Bye"
start()
You need to be careful about where you place statements with respect to whether they are inside ifs and loops or not. Here is the correct code for addition, the others will be similar:
def addition():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "+" + str(num_2) + "? "))
generatedAnswer = (num_1 + num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
start()