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()
Related
I want this number guessing game to be able to catch every possible exception or error the user enters. I've successfully prevented the use of strings when guessing the number, but I want the console to display a custom message when a float is entered saying something along the lines of "Only whole numbers between 1-20 are allowed". I realize my exception would work to catch this kind of error, but for learning purposes, I want to specifically handle if the user enters a float instead of an int. From what I could find online the isinstance() function seemed to be exactly what I was looking for. I tried applying it in a way that seemed logical, but when I try to run the code and enter a float when guessing the random number it just reverts to my generalized exception. I'm new to Python so if anyone is nice enough to assist I would also appreciate any criticism of my code. I tried making this without much help from the internet. Although it works for the most part I can't get over the feeling I'm being inefficient. I'm self-taught if that helps my case lol. Here's my source code, thanks:
import random
import sys
def getRandNum():
num = random.randint(1,20)
return num
def getGuess(stored_num, name, gameOn = True):
while True:
try:
user_answer = int(input("Hello " + name + " I'm thinking of a number between 1-20. Can you guess what number I'm thinking of"))
while gameOn:
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
user_answer = int(input())
elif isinstance(user_answer, int) != True:
print("Only enter whole numbers. No decimals u cheater!")
user_answer = int(input())
elif user_answer > stored_num:
print("That guess is too high. Try again " + name + " !")
user_answer = int(input())
elif user_answer < stored_num:
print("That guess is too low. Try again " + name + " !")
user_answer = int(input())
elif user_answer == stored_num:
print("You are correct! You win " + name + " !")
break
except ValueError:
print("That was not a number, try again")
def startGame():
print("Whats Your name partner?")
name = input()
stored_num = getRandNum()
getGuess(stored_num, name)
def startProgram():
startGame()
startProgram()
while True:
answer = input("Would you like to play again? Type Y to continue.")
if answer.lower() == "y":
startProgram()
else:
break
quit()
The only thing that needs be in the try statement is the code that checks if the input can be converted to an int. You can start with a function whose only job is to prompt the user for a number until int(response) does, indeed, succeed without an exception.
def get_guess():
while True:
response = input("> ")
try:
return int(response)
except ValueError:
print("That was not a number, try again")
Once you have a valid int, then you can perform the range check to see if it is out of bounds, too low, too high, or equal.
# The former getGuess
def play_game(stored_num, name):
print(f"Hello {name}, I'm thinking of a number between 1-20.")
print("Can you guess what number I'm thinking of?")
while True:
user_answer = get_guess()
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
elif user_answer > stored_num:
print(f"That guess is too high. Try again {name}!")
elif user_answer < stored_num:
print(f"That guess is too low. Try again {name}!")
else: # Equality is the only possibility left
print("You are correct! You win {name}!")
break
The if and elif conditions aren't working and I am not even getting an error. The code is intended to match the users input to what the computer selects and then make a call, if the user won or lost.
import random
def flip():
return random.choice(["Heads", "Tails"])
Users_Selection = (input("Choose: Heads or Tails?"))
print("Flipping the coin. Please wait!")
print ("It a", flip())
if flip()=="Heads" and "Heads"==Users_Selection:
print("Congratulations, you won!")
elif flip()=="Tails" and "Tails"==Users_Selection:
print("Sorry, You loose! Please try again")
All help is genuinely appreciated!
Everytime you call flip, it generates a new random output so you must store the value of flip in a variable.
c = flip()
print("It's a ", c)
if c=="Heads" and "Heads"==Users_Selection:
print("Congratulations, you won!")
elif c=="Tails" and "Tails"==Users_Selection:
print("Sorry, You loose! Please try again")
import time
import random
import sys
def code():
user_num=()
user_num=int(input("What number do you want from 0-30"))
if user_num>30:
print("number needs to be smaller")
print("restart code and try again")
else:
pass
if user_num<0:
print("your number needs to be greater")
print("restart code and try again")
else:
pass
code()
code()
random_num=random.randint(0,1)
if random_num==user_num:
print("your number is correct")
else:
print("your number is incorrect")
time.sleep(1)
try_again=input("do you want to try again (yes/no")
if try_again=="yes":
code()
else:
print("ok. Bye")
i am very new to functions so sorry if this is a rookie mistake. Any help with functions will be appreciated. Thank You.
At the very end of the "code" function you're calling it again
Try this:
import time
import random
import sys
def code():
user_num=()
user_num=int(input("What number do you want from 0-30"))
if user_num>30:
print("number needs to be smaller")
print("restart code and try again")
else:
pass
if user_num<0:
print("your number needs to be greater")
print("restart code and try again")
else:
pass
return user_num
random_num=random.randint(0,1)
user_num = code()
if random_num==user_num:
print("your number is correct")
else:
print("your number is incorrect")
time.sleep(1)
try_again=input("do you want to try again (yes/no")
if try_again in "yes":
user_num = code()
else:
print("ok. Bye")
I have been working on this guessing game but i just cant get it to repeat the game when the player says yes. The game gives you 5 attempts to guess the number that it thought of and then after it asks you if you would like to play again but when you say 'YES' it just keeps repeating the sentence and when you say 'NO' it does what its supposed to which is break the code
def main():
game = "your game"
print(game)
play_again()
import random #imports random number function
print("Welcome to the number guessing game!")
counter=1 #This means that the score is set to 0
number = int(random.randint(1,10))
while counter >0 and counter <=5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess>number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess!=number and guess<number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was ",number)#Prints this out when you guessed the number
print("it took you ",counter, "attempts!")#tells you how many attempts it took you to guess the number
if counter==2:
print("4 attempts left before program ends")
if counter==3:
print("3 attempts left before program ends")
if counter==4:
print("2 attempts left before program ends")
if counter==5:
print("1 attempts left before program ends")
def play_again():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
main()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()
It's because your game code isn't in the function. Try it in this manner:
<import statements>
def game():
<insert all game code>
def main():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
game()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
There's a few problems with your code that I'd like to point out.
The main one being that your game does not run again when typing yes. All it will do is run main() which will print your game and then ask you if you want to retry once again. It's easier if you put your game inside a definition that way you can call it whenever necessary.
Also, I don't know if it's just me, but if you guess the correct number, it will still ask you to guess a number. You need to exit your loop by putting your play_again() method in your else block.
Below is the code. I've polished it up a little just for optimization.
import random #imports random number function
def main():
print("Welcome to the number guessing game!")
game = "your game"
print(game)
run_game()
play_again()
def run_game():
counter = 1
number = random.randint(1, 10)
while counter > 0 and counter <= 5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess > number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess != number and guess < number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was " + str(number))#Prints this out when you guessed the number
print("it took you " + str(counter) + " attempts!")#tells you how many attempts it took you to guess the number
play_again()
if counter == 2:
print("4 attempts left before program ends")
if counter == 3:
print("3 attempts left before program ends")
if counter == 4:
print("2 attempts left before program ends")
if counter == 5:
print("1 attempts left before program ends")
def play_again():
while True:
retry = input("Would you like to play again?(yes or no) : ")
if retry == "yes":
main()
if retry == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()
I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.