Python Code Condensation - python

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.

Related

how can i give a boolean a value inside a function with a while loop

i'm trying to make a guessing game, and i want to give the user 5 chances, but the loop keeps going after the chances given if the answer is incorrect.
if the answer is correct the program will print the losing text
i think the problem is with the value of full but the solutions i've tried broke the code
def proceso(ingreso, correcto, usos, usos_completos, usos_visibles, full):
if usos < usos_completos:
while ingreso != correcto and not full:
print("you have " + str(usos_visibles) + " chances")
ingreso = input("guess the word: ")
usos += 1
int(usos_visibles)
usos_visibles -= 1
else:
full = True
if full:
print("you lost. Correct answer was: " + correcto)
else:
print("you won")
palabra_secreta1 = "cellphone"
palabra_ingresada = ""
oportunidades = 0
limite_oportunidades = 5
contador_visible = 5
sin_oportunidades = False
print("5 oportunities")
proceso(palabra_ingresada, palabra_secreta1, oportunidades, limite_oportunidades, contador_visible, sin_oportunidades)
You should use break if the correct word is inputted and then count the number of chances taken in the while loop and then use else to print if the correct input has not been given after the desired number of attempts. I've removed some arguments because they seemed to be the same and I'm not sure what they mean, but maybe they're useful? Also, you should use f-strings for formatting variables into strings:
def proceso(correcto, usos_completos):
usos = 0
while usos != usos_completos:
print(f"you have {usos_completos-usos} chances")
ingreso = input("guess the word: ")
if ingreso == correcto:
print("you won")
break
else:
usos += 1
else:
print(f"you lost. Correct answer was: {correcto}")
palabra_secreta1 = "cellphone"
limite_oportunidades = 5
print("5 oportunities")
proceso(palabra_secreta1, limite_oportunidades)

Repeated prints from loop

I am trying to create a program similar to the game Mastermind. I am having an issue in my while loop where it constantly prints "You got " + str(correct) + " correct!"
import random
import replit
def useranswer(input):
userinput.append(input)
return input
number = 0
answer = 0
guesses = 0
correct = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
for i in range(0,4):
answer = str(input('Give me a number: '))
useranswer(answer)
print(generation)
while userinput != generation:
guesses += 1
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got " + str(correct) + " correct! ")
correct = 0
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " + str(guesses) + " tries!")
If you want it to exit the while loop after printing the line print("You got " + str(correct) + " correct! ") then you'll need to do something within the while loop to make the check not true.
Right now if userinput != generation is true then it will loop forever because nothing in the loop ever changes that to be false.
You need to get the player's input within the while loop if you want it to keep looping until something happens, otherwise an if statement might be better.
Ive made couple of changes to your code. Take a look at it
Removed def userinput().
Moved userinput inside the while loop.
import random
import replit
number = 0
answer = 0
guesses = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
while userinput != generation:
guesses += 1
correct = 0
userinput = []
for i in range(0,4):
answer = int(input('Give me a number: '))
userinput.append(answer)
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got ",correct, " correct! ")
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " ,guesses, " tries!")

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).

I have an indentationerror: Expected an indented block

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":

How would I be able to add a score counter to a math quiz that includes functions?

Below I have created a Maths quiz in python. It consists of random equations to solve. The questions are generated using random numbers and functions that determine whether the question is add or subtract. I have completed the quiz, but I have tried adding a score counter so that if the user gets a question right, a point is added on. I am unsure how to do this, as I have tried implementing the score into the functions and it does not work. Here is the code:
import random
#Asks for name
name = input("What's your name?")
#Stops user from entering invalid input when entering their class
classchoices = ["A","B","C"]
classname = input("What class are you in?")
while classname not in classchoices:
classname = input("Not a valid class, try again:")
print(name, ",", classname)
print("Begin quiz!")
questions = 0
a = random.randint(1,12)
b = random.randint(1,12)
def add(a,b):
addQ = int(input(str(a) + "+" + str(b) + "="))
result = int(int(a) + int(b))
if addQ != result:
print ("Incorrect! The answer is", result)
else:
print("Correct")
def multiply(a,b):
score = 0
multQ = int(input(str(a) + "X" + str(b) + "="))
results = int(int(a) * int(b))
if multQ != results:
print ("Incorrect! The answer is", results)
else:
print("Correct")
def subtract(a,b):
subQ = int(input(str(a) + "-" + str(b) + "="))
resultss = int(int(a) - int(b))
if subQ != resultss:
print ("Incorrect! The answer is", resultss)
else:
print("Correct")
for questions in range(10):
Qlist = [add, subtract, multiply]
random.choice(Qlist)(random.randint(1,12), random.randint(1,12))
questions += 1
if questions == 10:
print ("End of quiz")
You can return a score for each task. An example for the add function:
if addQ != result:
print ("Incorrect! The answer is", result)
return 0
else:
print("Correct")
return 1
Of course you can give higher scores for more difficult tasks (e.g. 2 points for multiplications).
and then below:
score = 0
for questions in range(10):
Qlist = [add, subtract, multiply]
score += random.choice(Qlist)(random.randint(1,12),random.randint(1,12))
questions += 1
Use a global var and add +1 on every correct solution. The only negative is as soon as the programm is closed the score is lost.
something like this
You missed to define score globally and then access it within the function and updating it, Here's a working version:
import random
#Asks for name
name = input("What's your name?")
#Stops user from entering invalid input when entering their class
classchoices = ["A","B","C"]
classname = input("What class are you in?")
while classname not in classchoices:
classname = input("Not a valid class, try again:")
print(name, ",", classname)
print("Begin quiz!")
score = 0
questions = 0
a = random.randint(1,12)
b = random.randint(1,12)
def add(a,b):
global score
addQ = int(input(str(a) + "+" + str(b) + "="))
result = int(int(a) + int(b))
if addQ != result:
print ("Incorrect! The answer is", result)
else:
score += 1
print("Correct")
def multiply(a,b):
global score
multQ = int(input(str(a) + "X" + str(b) + "="))
results = int(int(a) * int(b))
if multQ != results:
print ("Incorrect! The answer is", results)
else:
score += 1
print("Correct")
def subtract(a,b):
global score
subQ = int(input(str(a) + "-" + str(b) + "="))
resultss = int(int(a) - int(b))
if subQ != resultss:
print ("Incorrect! The answer is", resultss)
else:
score += 1
print("Correct")
for questions in range(10):
Qlist = [add, subtract, multiply]
random.choice(Qlist)(random.randint(1,12), random.randint(1,12))
questions += 1
if questions == 10:
print ("End of quiz")
print('Score:', score)
Using return values of your functions as demonstrated by cello would be my first intuition.
But since you are already using a global variable to track your questions, you can introduce another one for the score.
questions = 0
score = 0
a = random.randint(1,12)
b = random.randint(1,12)
To use it (and not a local variable score, which would be only available in the function), your functions have to reference it by using globals:
def add(a,b):
global score
You can then increment it in the else-statements of your functions:
else:
print("Correct")
score += 1
At the end, you can print the score:
print("End of quiz")
print("Your score:", score)
Notice, that you are using questions variable in a strange fashion:
You first initialize it with 0:
questions = 0
Then you overwrite it during a loop:
for questions in range(10):
questions += 1
The for will give questions the values 0..9, so it is totally unneccessary to increase the number manually inside the loop. This increased value will immediately be overwritten by the next value of the loop.
After your loop exits, you are sure to have asked 10 questions. The following if-condition is superfluous (and only works, because you additionally increase questions in the loop). Just lose it:
print("End of quiz")

Categories