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!")
Related
print("Welcome to my quiz page!")
playing = input("Do you want to play? ")
if playing.lower() == "yes": #when people answer no here, the quiz should stop but it doesn't. why?
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
When I answer "no" it still let me carry on playing the quiz instead of quitting. How can I stop it running when people answer no instead of yes?
The quiz does not stop because you have not included any code to stop the quiz when the user enters "no". To fix this, you can add an else statement after the if statement that checks if the user wants to play. The else statement should contain a break statement to exit the loop.
Here How you can do so:
print("Welcome to my quiz page!")
while True:
playing = input("Do you want to play? ")
if playing.lower() == "yes" or playing.lower() == "y":
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
else:
break
You can make this more manageable by constructing a list of questions and answers rather than writing discrete blocks of code for each.
You need to be asking the user if they want to answer questions (or not).
So...
Q_and_A = [
('What is the capital of Japan', 'Tokyo'),
('What is a female Japansese dress called', 'kimono'),
('What are Japanese gang members called', 'yakuza')
]
score = 0
for q, a in Q_and_A:
if input('Would you like to try to answer a question? ').lower() in {'n', 'no'}:
break
if input(f'{q}? ').lower() == a.lower():
print('Correct')
score += 1
else:
print('Incorrect')
print(f'Your total score is {score} out of a possible {len(Q_and_A)}')
Thus if you want to add more questions and answers you just change the list of tuples. The rest of the code doesn't need to be changed
Hi I'm literally new to python and programming in general ---- a complete beginner. I'm 2 hours in in some youtube python beginner course and he made some guessing game to demonstrate the application of a while loop.
I replicated it so I can practice coding but I made some modifications to it on my own.
He made the guessing game where you can have 3 tries to guess the word using a combination of while loop, if and else functions, and Boolean variable.
My version is similar but I wanted it to have a counter where you are informed of how many tries you have left.
secret_word = "Aircraft"
answer = ""
guess_count = 0
guess_limit = 3
remaining_guess = guess_limit - guess_count
while answer != secret_word and remaining_guess != 0:
if guess_count < guess_limit and remaining_guess == 3:
def re_guesses(remaining_guess_1):
print("You have " + str(remaining_guess_1) + " remaining guesses")
int(remaining_guess_1)
return remaining_guess_1
remaining_guess = re_guesses(remaining_guess)
def guess_word(guess_count_1):
answer = input("Enter answer: ")
guess_count_1 += 1
return guess_count_1
guess_count = guess_word(guess_count)
elif guess_count < guess_limit and remaining_guess == 2:
def re_guesses(remaining_guess_1):
print("You have " + str(remaining_guess_1) + " remaining guesses")
int(remaining_guess_1)
return remaining_guess_1
remaining_guess = re_guesses(remaining_guess)
def guess_word(guess_count_1):
answer = input("Enter answer: ")
guess_count_1 += 1
return guess_count_1
guess_count = guess_word(guess_count)
else:
def re_guesses(remaining_guess_1):
print("You have " + str(remaining_guess_1) + " remaining guesses")
int(remaining_guess_1)
return remaining_guess_1
remaining_guess = re_guesses(remaining_guess)
def guess_word(guess_count_1):
answer = input("Enter answer: ")
guess_count_1 += 1
return guess_count_1
guess_count = guess_word(guess_count)
if remaining_guess == 0:
print("You lost!!")
else:
print("I can't believe you won!")
I tried to store the return value (remaining_guess_1) again to the remaining_guess as I converted into an integer. I did the same to the return value of guess_count_1 and stored it in the orginal variable of guess_count.
I was expecting the result to be that the counter will subtract 1 try after every wrong answer but instead it is stuck to "You have 3 remaining guesses".
Please someone explain what I'm doing wrong and how to make it work. Thank you.
I tried out your code and found some ways to simplify the while loop process so that you don't have all of those "if/else" blocks. Moving around the definitions and the "while" loop, I came up with the following code.
secret_word = "Aircraft"
answer = ""
guess_limit = 3
remaining_guesses = guess_limit
def re_guesses(remaining_guess_1):
print("You have " + str(remaining_guess_1) + " remaining guesses")
int(remaining_guess_1)
def guess_word():
answer = input("Enter answer: ")
return answer
re_guesses(remaining_guesses)
while remaining_guesses != 0:
answer = guess_word()
if (answer == secret_word):
break
else:
print(answer, ' was not the correct answer')
remaining_guesses -= 1
re_guesses(remaining_guesses)
if remaining_guesses == 0:
print("You lost!!")
else:
print("I can't believe you won!")
The function definitions and the initial prompt are moved before the while loop is called. Also, instead of returning the guess count, I revised the "guess_word" function to return the entered answer. Then based on the correctness (or incorrectness) of the answer, the loop is exited with a "break" call if the answer was correct, or the remaining guess count gets decremented if incorrect. If the user answers correctly before the remaining count hits zero, they are notified that they won. Also, I didn't see a use anymore for the guess count so I removed that variable both from the variable list and from the input parameter for the "guess_word" function.
Go ahead and study the code and see if it meets your needs and provides you with some ideas.
Regards.
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)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm unable to understand what is wrong in my code why I'm not getting any output?
I have checked my code thoroughly but still, I'm unable to find any error.
when I try to run it on pycharm it doesn't do anything.
import random
def ques():
name=input("What's your name?:")
print("Hi",name,"!")
choice=random.choice("+x")
finish=False
quesno=0
correctques=0
while finish == False:
if quesno<10|questno>=0:
no1=random.randrange(1,10)
no2=random.randrange(1,10)
print((no1),(choice),(no2))
ans=int(input("What's the answer?:"))
quesno=quesno+1
if choice==("+"):
realans=no1+no2
if ans==realans:
print("That's the correct answer!")
correctques=correctques+1
else:
print("That's incorrect!,the answer was",realans,"!")
if choice==("x"):
realans=no1*no2
if ans==realans:
print("That's the correct answer!")
correctques=correctques+1
else:
print("That's incorrect!,the answer was",realans,"!")
elif choice==("-"):
realans=no1-no2
if ans==realans:
print("That's the correct answer")
correctques=correctques+1
else:
print("That's incorrect!,the answer was",realans,"!")
else:
finish=True
else:
print("Good Job",name,"! You have finished the quiz")
Did you run it? add this to the end of your code
ques()
if __name__ == "__main__":
ques()
You need to call the function.
At the end of your code just type ques() and that should call your fucntion and you should be able to get output.
import random
def ques():
name = input("What's your name?:")
print("Hi", name, "!")
choice = random.choice("+x")
finish = False
quesno = 0
correctques = 0
while finish == False:
if quesno < 10 | quesno >= 0:
no1 = random.randrange(1, 10)
no2 = random.randrange(1, 10)
print((no1), (choice), (no2))
ans = int(input("What's the answer?:"))
quesno = quesno + 1
if choice == ("+"):
realans = no1 + no2
if ans == realans:
print("That's the correct answer!")
correctques = correctques + 1
else:
print("That's incorrect!,the answer was", realans, "!")
finish = True
if choice == ("x"):
realans = no1 * no2
if ans == realans:
print("That's the correct answer!")
correctques = correctques + 1
else:
print("That's incorrect!,the answer was", realans, "!")
finish = True
elif choice == ("-"):
realans = no1 - no2
if ans == realans:
print("That's the correct answer")
correctques = correctques + 1
else:
print("That's incorrect!,the answer was", realans, "!")
finish = True
else:
finish = True
else:
print("Good Job", name, "! You have finished the quiz")
ques()
so i have run this code 3 times as there is 3 loops, however after every loop, the score variable seems to add itself on from the previous loop for e.g 1st loop (first user) gets a score of 2, then 2nd user get 4 and the last user gets 6. when i want to individually output all 3 users scores seperately, the code just adds on the scores. therefore this results in false scores. any solution to fix the score variable to reset every loop but still be attached to the 'schooldata[x]['score']' (x being the user number for e.g user 2 score would be 'schooldata[1]['score']) and which this outputs 3 seperate scores, specific to each user.
score = 0
schooldata = []
for x in range (0,3):
quiz = dict()
print ("Enter your name")
quiz['name'] = input()
print ("what class")
quiz['class_code'] = input()
print("1. 9+10=")
answer = input()
answer = int(answer)
if answer == 19:
print("correct")
score = score + 1
else:
print("wrong")
print("2. 16+40=")
answer = input()
answer = int(answer)
if answer == 56:
print("correct")
score = score + 1
else:
print("wrong")
print("3. 5+21=")
answer = input()
answer = int(answer)
if answer == 26:
print("correct")
score = score + 1
else:
print("wrong")
print("4. 5-6=")
answer = input()
answer = int(answer)
if answer == -1:
print("correct")
score = score + 1
else:
print("wrong")
print("5. 21-9=")
answer = input()
answer = int(answer)
if answer == 12:
print("correct")
score = score + 1
else:
print("wrong")
print("6. 12-11=")
answer = input()
answer = int(answer)
if answer == 1:
print("correct")
score = score + 1
else:
print("wrong")
print("7. 5*6=")
answer = input()
answer = int(answer)
if answer == 30:
print("correct")
score = score + 1
else:
print("wrong")
print("8. 1*8=")
answer = input()
answer = int(answer)
if answer == 8:
print("correct")
score = score + 1
else:
print("wrong")
print("9. 4*6=")
answer = input()
answer = int(answer)
if answer == 24:
print("correct")
score = score + 1
else:
print("wrong")
print("10. 9*10=")
answer = input()
answer = int(answer)
if answer == 90:
print("correct")
score = score + 1
else:
print("wrong")
quiz['score'] = score
schooldata.append(quiz)
user1=("name - ", schooldata[0]['name'],", user score - ", schooldata[0]['score'],", class number - ", schooldata[0]['class_code'])
print ("if you want student 1's results and information, please type 'user[0][0]'")
user = input()
if user == "user1":
print ("name - ", schooldata[0]['name'],", user score - ", schooldata[0]['score'],", class number - ", schooldata[0]['class_code'])