How should I get the below loop to replay if the user types in an invalid response after being asked if they want to roll the dice again?
I can't get it to work without messing with the while loop. Here's what I have so far
# Ask the player if they want to play again
another_attempt = input("Roll dice again [y|n]?")
while another_attempt == 'y':
roll_guess = int(input("Please enter your guess for the roll: "))
if roll_guess == dicescore :
print("Well done! You guessed it!")
correct += 1
rounds +=1
if correct >= 4:
elif roll_guess % 2 == 0:
print("No sorry, it's", dicescore, "not", roll_guess)
incorrect += 1
rounds +=1
else:
print("No sorry, it's ", dicescore, " not ", roll_guess, \
". The score is always even.", sep='')
incorrect += 1
rounds +=1
another_attempt = input('Roll dice again [y|n]? ')
if another_attempt == 'n':
print("""Game Summary""")
else:
print("Please enter either 'y' or 'n'.")
I would suggest you do it with two while loops, and use functions to make the code logic more clear.
def play_round():
# Roll dice
# Compute score
# Display dice
# Get roll guess
def another_attempt():
while True:
answer = input("Roll dice again [y|n]?")
if answer == 'y':
return answer
elif answer == 'n':
return answer
else:
print("Please enter either 'y' or 'n'.")
def play_game():
while another_attempt() == 'y':
play_round()
# Print game summary
Related
from random import randint
play = "yes"
while play == "yes":
choice = int(input("Would you like to play yourself(1) or let machine(2) play? press '1' or '2': "))
if choice == 1:
print("You chose to play yourself")
num = randint(1,9999)
counter = 0
while True:
num_guess = int(input("Guess the number: "))
if num_guess == 0:
print("Player has left the game")
break
else:
if num_guess > num:
print("Your guess is too high")
elif num_guess < num:
print("Your guess is too low")
elif num_guess == num:
print("Yay,you found it")
print("It took you " + str(counter) + " tries to guess the number")
break
counter += 1
elif choice == 2:
print("You chose to let the machine play")
your_num = int(input("Enter your number: "))
lowest = 1
highest = 9999
counter = 0
machine_guess = randint(1,9999)
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
else:
while True:
print("My guess is ",machine_guess)
is_it_right = input("Is it too small(<) or too big(>) or machine found(=) the number?: ")
if is_it_right == ">":
if machine_guess > your_num:
highest = machine_guess
counter += 1
else:
print("!!!Don't cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" < " + str(your_number) + ",so you should have written '<' instead of what you wrote.Continue ")
elif is_it_right == "<":
if machine_guess < your_num:
lowest = machine_guess + 1
counter += 1
else:
print("!!!Don't Cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" > " + str(your_number) + ",so you should have written '>' instead of what you wrote.Continue ")
elif is_it_right == "=":
if machine_guess == your_num:
if your_num == machine_guess:
counter += 1
print("Yayy,I found it")
print("It took me " + str(counter) + " tries to guess the number")
else:
print("You cheated and changed the number during the game.Please play fairly")
your_number = input("What was your number?: ")
print(str(machine_guess) +" = " + str(your_number) + ",so you should have written '=' instead of what you wrote ")
break
elif is_it_right == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
machine_guess = (lowest+highest)//2
elif choice == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player has left the game")
break
request = input("Do you want to play again? Answer with 'yes' or 'no': ")
if request == "no":
print("You quitted the game")
break
elif request == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
This is my code for game "guess my number",here the complicated ones is me trying to make the program prevent user from cheating (It is a university task,due in 3 hours)
So choice 1 is when user decides to play game "guess my number" and 2nd choice when computer plays the game.The problem that I have is :
I can't make the code make the user input the number in range of(1,9999) and THEN continue the process
As you see I have a lot of "if ... == 0" --> .In task it is said that whenever(any of inputs) user types 0 the game has to stop.The others work well but the one in choice 2 the first if is not working
If somebody has solution for this,please help.I would be grateful
Whenever you want to ask a question repeatedly until the correct input is given, use a while loop
print("You chose to let the machine play")
your_num = -1
while your_num < 0 or your_num > 9999:
your_num = int(input("Enter your number [0..9999]: "))
1- To force the user to input a number in the range of (1,9999), you must have an a condition like:
while True:
try:
num_guess= int(input("Enter your number in range 1-9999: "))
except ValueError:
print("That's not a number!")
else:
if 1 <= num_guess <= 9999:
break
else:
print("Out of range. Try again")
Edit: I didn't understand which input you wanted to keep in the range of 1-9999. I gave answer with num_guess but you can use it with your_num, too.
2- Add play = "no" line to the condition when the user inputs 0:
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
play = "no"
break
With my guess the number program, when I try to run it tells me the the variable "number" is not defined. I would appreciate it and be thankful if someone came to my aid in this!
import random
guesses = 0
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
Your problem is that number is not defined in the function correct. number is defined in _main_. When you call correct in _main_, it does not get access to number.
This is the fixed version of your code:
import random
guesses = 0
number = random.randint(1, 100)
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
What I changed is I moved the definition of number to the top, which allowed it to be accessed by all functions in the module.
Also, your code style is not very good. Firstly, do not name your main function _main_, instead use main. Additionally, you don't need a function to print out 'lower' and 'higher.' Here is some improved code:
import random
def main():
number = random.randint(1, 100)
guesses = 0
while True:
guessed_num = int(input('Guess the number: '))
guesses += 1
if guessed_num > number:
print('Guess lower!')
elif guessed_num < number:
print('Guess higher!')
else:
print('Correct!')
print('The number was {}'.format(number))
print('It took you {} guesses.'.format(guesses))
break
main()
Your specific problem is that the variable number is not defined in function correct(). It can be solved by passing number as an argument to correct().
But even if you correct that problem, your program has another major issue. You have defined guesses globally, but you still pass guesses as an argument to lower(), higher() and correct(). This creates a duplicate variable guesses inside the scope of these functions and each time you call either of these functions, it is this duplicate variable that is being incremented and not the one you created globally. So no matter how many guesses the user takes, it will always print
You took 1 guesses.
Solution:
Define the functions lower() and higher() with no arguments. Tell those functions thatSo ultimately this code should work:
import random
guesses = 0
def higher():
global guesses
print("Lower")
guesses = guesses + 1
def lower():
global guesses
print("Higher")
guesses = guesses + 1
def correct(number):
global guesses
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_():
print("Welcome to guess the number")
guesses = 0
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher()
elif guess < number:
lower()
elif guess == number:
correct(number)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
_main_()
elif answer == "N":
exit()
else:
exit()
_main_()
Why wont this stop when 'n' is entered?
I've tried using break on the bottom else but I get errors doing that. That's a common problem I have with break. I have no idea why I'm thrown off with break.
import random
def game():
secret_num = random.randint(1, 10)
guesses = []
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("{} isn't a number".format(guess))
else:
if guess == secret_num:
print("You got it! The number was {}.".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower than {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it! My number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/n ")
if play_again.lower() != 'Y':
game()
else:
print("Bye!")
game()
You convert play_again to a lower-case letter but compare it to an upper-case letter.
You could simply change it to:
if play_again.lower() != 'n': # 'y' was wrong, right?
game()
else:
print("Bye!")
return # works also without the explicit return but it makes the intention clearer.
import random
def start():
print "\t\t***-- Please enter Y for Yes and N for No --***"
answer = raw_input("\t\t Would you like to play a Guessing Game?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
def end():
print("\t\t\t **Goodbye** ")
raw_input("\t\t\t**Press ENTER to Exit**")
def game():
print "\t\t\t Welcome to Williams Guessing Game"
user_name = raw_input("\n\t\t Please enter your name: ")
print "\n", user_name, "I am thinking of a number between 1 and 20"
print "You have 5 attempts at getting it right"
attempt = 0
number = random.randint(1, 20)
while attempt < 5:
guess = input("\t\nPlease enter a number: ")
attempt = attempt + 1
answer = attempt
if guess < number:
print "\nSorry", user_name, "your guess was too low"
print "You have ", 5 - attempt, " attempts left\n"
elif guess > number:
print "\nSorry ", user_name, " your guess was too high"
print "You have ", 5 - attempt, " attempts left\n"
elif guess == number:
print "\n\t\t Yay, you selected my lucky number. Congratulations"
print "\t\t\tYou guessed it in", attempt, "number of attempts!\n"
answer = raw_input("\n\t\t\t\tTry again? Y/N?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
start()
If you want the computer to guess your number, you could use a function like this:
import random
my_number = int(raw_input("Please enter a number between 1 and 20: "))
guesses = []
def make_guess():
guess = random.randint(1, 20)
while guess in guesses:
guess = random.randint(1, 20)
guesses.append(guess)
return guess
while True:
guess = make_guess()
print(guess)
if guess == my_number:
print("The computer wins!")
break
else:
print(guesses)
It's just a quick-and-dirty example, but I hope it gives you the idea. This way, the computer gets unlimited guesses, but you could easily change the while loop to limit its number of guesses.
EDIT: Thank you, the question has been answered!
The program works properly, asides from the fact that it does not loop to allow the user to play a new game. ie, after entering too many, too few, or the perfect amount of change, the program asks "Try again (y/n)?: " as it should. But I can't find out why it doesn't loop... And when it loops, it doesn't need to include the large paragraph about explaining the game. Just the line about "Enter coins that add up to "+str(number)+" cents, one per line." Any tips?
#Setup
import random
playagain = "y"
#Main Loop
if (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
By using break, you're completely leaving the while loop and never checking the playagain condition. If you want to see if the user wants to play again put the 'playagain' check in another while loop.
#Setup
import random
playagain = "y"
#Main Loop
while (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
You set playagain to y/n, but the code doesn't go back around to the beginning if playagain is equal to 'y'. Try making if playagain == "y" into while playagain == "y". That way, it goes through the first time and keeps going back to the beginning if playagain is still set to "y".
Also, indent your last line (playagain = str(....)) so it's part of the while playagain == "y" loop. If it's not, then the code will be stuck in an infinite loop because playagain isn't being changed inside the while loop.
Indent the last line as far as the while True line. And change the if (playagain == "y"): to a
while (playagain == "y"):
Your "Main loop" is not a loop, it is just an if statement. Also it is better to use raw_input because input will eval your input. Try something along the lines of this:
playagain = 'y'
#Main loop
while playagain == 'y':
print "do gamelogic here..."
playagain = raw_input("Try again (y/n)?: ")
Inside your gamelogic, you could use a boolean to check wether you need to print the game explanation:
show_explanation = True
while playagain == 'y':
if show_explanation:
print "how to play is only shown once..."
show_explanation = False
print "Always do this part of the code"
...
playagain = raw_input("Try again (y/n)?: ")