Is there a way to repeat code in a simple way? - python

I am making a python quiz and everything is going well but there are some things that aren't working. Such as when the user has answered all the questions, I want the code to ask the user if they would like to play the quiz again. I have done the part where the code asks the user if they would like to play again but I don't know how to repeat the quiz. I have tried things such as making the quiz a variable and printing the variable but that didn't work. Please help me.
Here's the code, the part where I ask if the user wants to play again is at the bottom.
import random
import time
Question_list = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
question = list (Question_list.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Your Answer: ' )
# if correct, moves onto next question
if answer.lower() == Question_list[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer. Try again")
question.remove(ques)
play_again = input("Would you like to play the quiz again\n")
if play_again == "yes":
print()
# i want it to repeat the quiz but don't know how to do that.
# this part works fine
else:
print("Thanks for playing")
time.sleep(2)
exit()

You already have an infinite loop for asking multiple questions. You can also put an infinite loop to play multiple quizes like this:
import random
import time
Question_list = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
while True:
question = list (Question_list.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Your Answer: ' )
# if correct, moves onto next question
if answer.lower() == Question_list[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer. Try again")
question.remove(ques)
play_again = input("Would you like to play the quiz again\n")
#if answer is not yes, break the outer infinite loop
if play_again != "yes":
print("Thanks for playing")
break
time.sleep(2)
exit()

You could try this, use the while True outside, then it could always run if play_again is yes and add break in the bottom if want to stop.
import random
import time
while True:
Question_list = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
question = list (Question_list.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Your Answer: ' )
# if correct, moves onto next question
if answer.lower() == Question_list[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer. Try again")
question.remove(ques)
play_again = input("Would you like to play the quiz again\n")
if play_again == "yes":
print()
# i want it to repeat the quiz but don't know how to do that.
else:
break
# this part works fine
print("Thanks for playing")
time.sleep(2)
exit()

You can set a while loop which repeats the question until a certain condition is met. Use a variable which is true and while it is true the game continues, but once a condition is met which should end the game, switch the variable to false and the while loop should stop.

Related

Can't get string user input working (Python)

I've searched the web and this site and been messing around all day, trying 100 ways to get this simple little program working. I'm practicing endless While loops and string user inputs. Can anyone explain what I'm doing wrong? Thank you!
while True:
print("This is the start.")
answer = input("Would you like to continue? (Y/N) ")
answer = answer.islower()
if answer == "n":
print("Ok thank you and goodbye.")
break
elif answer == "y":
print("Ok, let's start again.")
else:
print("You need to input a 'y' or an 'n'.")
your code has one thing wrong answer.islower() will return boolean values True or False but you want to convert it into lower values so correct method will be answer.lower()
while True:
print("This is the start.")
answer = input("Would you like to continue? (Y/N) ")
answer = answer.lower() # change from islower() to lower()
if answer == "n":
print("Ok thank you and goodbye.")
break
elif answer == "y":
print("Ok, let's start again.")
else:
print("You need to input a 'y' or an 'n'.")
You just need one amendment to this line:
Instead of
answer = answer.islower()
Change to
answer = answer.lower()

Control flow - Jump to another loop?

I did not find any duplicates of this question, i understand that Python has no "goto" functionality in itself and how i can make use of "continue" in a loop to get the same effect, but i'm not really sure if it's any recommended method of "jumping back" to another loop for eg? Let me show you an example below
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
pass
# Here i would want to be able to send the user back to the 1st loop if user gives any other input than "yes" or "no"
The only thing i can think of right now that makes any sense (to not have to simply rewrite the whole thing again) is to simply set the first loop to a function and call that from the second loop to get the result i want, this works as i intend it to:
def firstloop():
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
firstloop()
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
firstloop()
But somehow it feels like i'm over complicating something, or is this the "best" way i can go by with something like this? Thanks
You should put the second loop inside the first one (or inside an enclosing while for both). GOTOs are never needed, See here: https://en.wikipedia.org/wiki/Structured_programming

Number guessing game python (make the game ask to play every time)

import random
def game():
number = random.randint(0, 10)
guess = 0
print("Guess a number from 0-10:")
while number != guess:
try:
guess = int(input(""))
if number != guess:
print("you haven't guessed the number, keep trying")
else:
print("You guessed it!")
break
except ValueError:
print("Please enter an integer")
game()
choose = input("Would you like to play again?\n")
while choose == "yes":
game()
if choose == "no":
break
I'm trying to add a feature where every time the game is won, the user has the option to play again, right now the game runs, then you win, it asks if you want to play again, you say yes, it runs again then you win and it runs again without asking.
Choose is only set one time, so the while-loop never breaks. You could simply add:
choose = input("Would you like to play again?\n")
while choose == "yes":
game()
choose = input("Would you like to play again?\n")
if choose == "no":
break
Or somewhat more elegantly:
choose = input("Would you like to play again?\n")
while choose != "no":
game()
choose = input("Would you like to play again?\n")
You're currently only asking the user if he wants to play again once, and keep it going with the while loop. You should ask the user again after every time the game is played, like so:
choose = input("Would you like to play again?\n")
while choose == "yes":
game()
choose = input("Would you like to play again?\n") #add this line
if choose == "no":
break

How to make this program ask user to replay game? [duplicate]

This question already has answers here:
Repeat Game - Python Rock, Paper, Scissors
(2 answers)
Closed 2 years ago.
I would like to know how to ask a user "Would you like to play again?" and how to loop that so it works.
I have tried a few different things but nothing has worked yet. This is only my 4th day learning code and I decided I wanted to try and make my own mini game. All the code so far is done without looking anything up online and is done through memory of what I have learned the past few days so forgive me if its not the best.
'''
import random
import time
user_answer = input("Would you like to try and guess the number the die will roll? : ")
def guess_number():
dice_sides = ["1", "2", "3", "4", "5", "6"]
r_roll = random.choice(dice_sides)
if user_answer == "yes" or "Yes":
print("Excellent, lets play!")
else:
print("Okay, have a great day!")
user_guess = input("What is your guess? : ")
time.sleep(1)
print("The number is.....")
time.sleep(1.5)
print(r_roll)
if user_guess == r_roll:
print("Congrats! You won!")
else:
print("Sorry, you lose....")
guess_number()
'''
Try the following:
guess_number()
while True:
response = input("wanna play again?")
if response.lower() == "yes":
guess_number()
else:
break

not restarting for program and input integer not working

I'm trying to develop a program wherein at the finish of the game the user will input "Yes" to make the game restart, while if the user inputed "Not" the game will end. For my tries, I can't seem to figure out how to make the program work. I'm quite unsure if a double while True is possible. Also, it seems like when I enter an integer the game suddenly doesn't work but when I input an invalidoutpit the message "Error, the inputed value is invalid, try again" seems to work fine. In need of help, Thank You!!
import random
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
while True:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
else:
guess1=int(guess[0])
guess2=int(guess[1])
guess3=int(guess[2])
guess4=int(guess[3])
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
answer=input("Would you like to play again? (Yes or No) ")
if answer==Yes:
print ('Yay')
continue
else:
print ('Goodbye!')
break
Wrap your game in a function eg:
import sys
def game():
#game code goes here#
Then at the end, call the function to restart the game.
if answer=='Yes': # You forgot to add single/double inverted comma's around Yes
print ('Yay')
game() # calls function game(), hence restarts the game
else:
print ('Goodbye!')
sys.exit(0) # end game
try this
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
gueses=[]
while len(gueses)<=3:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
gueses.append(guess)
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
guess1=gueses[0]
guess2=gueses[1]
guess3=gueses[2]
guess4=gueses[3]
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
if P1=="x" and P2=="x" and P3=="x" and P4=="x":
print("you won")
else:
print("YOUE LOSE")
print("TRUE ANSWERS", A1,A2,A3,A4)
print("YOUR ANSWER", gueses)
game()
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print ('Yay')
game()
else:
print ('Goodbye!')
The previous answers are good starts, but lacking some other important issues. I would, as the others stated, start by wrapping your game code in a function and having it called recursively. There are other issues in the guess=int(input("\nTry and Guess the Numbers :). ")). This takes one integer as the input, not an array of integers. The simplest solution is to turn this into 4 separate prompts, one for each guess. I would also narrow the scope of your error test. I've included working code, but I would read through it and make sure you understand the logic and call flow.
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
if P1=="O" or P2=="O" or P3=="O" or P4=="O":
print("Here is your Clue :) :")
print(P1,P2,P3,P4)
try:
guess1=int(input("\nGuess 1 :). "))
guess2=int(input("\nGuess 2 :). "))
guess3=int(input("\nGuess 3 :). "))
guess4=int(input("\nGuess 4 :). "))
except ValueError:
print("Invalid Input")
continue
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
break
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print('Yay')
game()
else:
print('Goodbye!')
game()

Categories