This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
My code is below, it's prompting for the desired info, but if/when user is re-prompted the first time to re-enter number of games, if its not the expected number, I am not sure how to re-loop/keeping asking the question?
print('Welcome to my Rock, Paper, Scissors Game!')
print ()
user_action = eval(input('Enter Number of Games -- Odd Number between 3 and 11:'))
REMAINDER = user_action % 2
if REMAINDER != 0:
if user_action > 3 or user_action < 13:
print()
print()
print("Game 1 \n Enter (R)ock, (P)aper, or (S)cissors")
else:
print("\"Sorry, try again. \n Enter the Number of Games -- Off Number 3 to 11")
print
print`enter code here`
user_action = eval(input('Enter Number of Games -- Odd Number between 3 and 11:'))
Start a If/Elif statement.
For eg. 'If' contains the range value for num of games. And 'Elif' contains if user input number is out of range. Then in the 'Elif' start a 'While Loop'. Inside the loop, ask the user for another input. to check if this input is correct or not, do If/Elif once again with same conditions as before. This time if the 'If' is satisfied, 'break' the loop. If the 'Elif' is satisfied, make an increment in the 'While Loop' variable.
What this will do?
First it will check if the input is in range or not. If Yes, then no problem. If No, then it will start a loop which will keep asking the user for correct input. Once it gets the correct input, it will break out from that loop and you get a perfectly well-defined input.
Maybe you could create like a helper function called something like get_int_input that handles the vailidation:
from random import randint
MIN_NUM_GAMES = 3
MAX_NUM_GAMES = 11
CHOICES = ['rock', 'paper', 'scissors']
LOSER_TO_WINNER = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}
def rock_paper_scissors():
user_choice = CHOICES[get_int_input('\nEnter 1 for rock, 2 for paper, or 3 for scissors: ', 1, 3) - 1]
computer_choice = CHOICES[randint(0, 2)]
if user_choice == computer_choice:
print(f'It is a draw, both you and the computer chose {user_choice}...')
return 0 # draw
elif LOSER_TO_WINNER[computer_choice] == user_choice:
print(f'You win! The computer threw {computer_choice} while you chose {user_choice}.')
return 1 # win
else:
print(f'You lose... The computer threw {computer_choice} while you chose {user_choice}.')
return -1 # loss
def get_int_input(prompt, min_num, max_num):
num = -1
while True:
try:
num = int(input(prompt))
if min_num <= num <= max_num:
break
print(f'Error: Integer outside of allowed range {min_num}-{max_num} inclusive, try again...')
except ValueError:
print('Error: Enter an integer, try again...')
return num
def main():
print('Welcome to my Rock, Paper, Scissors Game!\n')
num_games = get_int_input(f'Enter the number of games: ', MIN_NUM_GAMES, MAX_NUM_GAMES)
num_wins = num_losses = num_draws = 0
for _ in range(num_games):
game_outcome = rock_paper_scissors()
if game_outcome == 1:
num_wins += 1
elif game_outcome == -1:
num_losses += 1
else:
num_draws += 1
print(f'\nYou played {num_games} games, with {num_wins} win(s), {num_losses} loss(es), {num_draws} draw(s).')
print('Goodbye!')
if __name__ == '__main__':
main()
Example Usage:
Welcome to my Rock, Paper, Scissors Game!
Enter the number of games: 2
Error: Integer outside of allowed range 3-11 inclusive, try again...
Enter the number of games: 12
Error: Integer outside of allowed range 3-11 inclusive, try again...
Enter the number of games: 4
Enter 1 for rock, 2 for paper, or 3 for scissors: 3
You lose... The computer threw rock while you chose scissors.
Enter 1 for rock, 2 for paper, or 3 for scissors: 2
You win! The computer threw rock while you chose paper.
Enter 1 for rock, 2 for paper, or 3 for scissors: 1
It is a draw, both you and the computer chose rock...
Enter 1 for rock, 2 for paper, or 3 for scissors: 2
It is a draw, both you and the computer chose paper...
You played 4 games, with 1 win(s), 1 loss(es), 2 draw(s).
Goodbye!
Related
I'm having issues with this random number guessing game. There are 2 issues: The first issue has to do with the counting of how many tries you have left. it should give you 3 changes but after the 2nd one it goes into my replay_input section where I am asking the user if they want to play again.
import random
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
break
The second part has to do with the replay input, I can't seem to get it to loop back to the beginning to restart the game.
replay_input = input("Yes or No ").lower()
if replay_input == "yes":
guess = input("Enter in your numerical guess. ")
The break statement exits a while loop. The code in the loop executes once, hits break at the end, and moves on to execute the code after the loop.
You can have the player replay the game by wrapping it in a function which I've called play_game below. The while True loop at the end (which is outside of play_game) will loop until it encounters a break statement. The player plays a game once every loop. The looping stops when they enter anything other than "yes" at the replay prompt which will make it hit the break statement.
import random
def play_game():
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
while True:
play_game()
replay_input = input("Yes or No ").lower()
if replay_input != "yes":
break
Please focus on the basics first before posting the questions here. Try to debug with tools like https://thonny.org/. However, I updated your code, just check.
import random
# guess the # game
random_number = random.randint(0, 10)
print(random_number)
# don't forget to convert to int
guess = int(input("Enter in your numerical guess. "))
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
number_of_guess_left -= 1
if guess == random_number:
print("You Win! ")
break
else:
if number_of_guess_left == 0:
print("You lose! You have no more chances left.")
break
else:
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = int(input("Enter in your numerical guess. "))
I am making a program that generates a random number and asks you to guess the number out of the range 1-100. Once you put in a number, it will generate a response based on the number. In this case, it is Too high, Too low, Correct, or Quit too soon if the input is 0, which ends the program(simplified, but basically the same thing).
It counts the number of attempts based on how many times you had to do the input function, and it uses a while loop to keep asking for the number until you get it correct. (btw, yes I realize this part is a copy of my other question. This is a different problem in the same program, so I started it the same way.)
Anyways, I am having an issue with the last part of the program not taking any values. It is supposed to take the input for keep_playing and continue going if it is equal to 'y'. The issue is that it isn't actually making the variable equal anything(at least I don't think so.) So, whatever value I put in, it just prints the same response every time. Here is the small part of the code which isn't working, though I feel like it is something wrong with the rest of the code:
def keep_playing(attempts,keep_playing):
keep_playing = 'y'
if keep_playing == 'y':
guess(attempts)
keep_playing = str(input("Another game (y to continue)? "))
else:
print()
print("Thanks for playing")
return keep_playing
The expected output is:
Enter a number between 1 and 100, or 0 to quit: 4
Too low, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 67
Too high, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 66
Congratulations! You guessed the right number!
There were 2 attempts
Another game (y to continue)? y
Enter a number between 1 and 100, or 0 to quit: 0
You quit too early
The number was 79
Another game (y to continue)? n
Thanks for playing!
But the actual output is:
Enter a number between 1 and 100, or 0 to quit: 4
Too low, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 67
Too high, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 66
Congratulations! You guessed the right number!
There were 2 attempts
Another game (y to continue)? y
Enter a number between 1 and 100, or 0 to quit: 0
You quit too early
The number was 79
Another game (y to continue)? n
Another game (y to continue)? y
>>>
Notice how no matter what I do, it continues to run. The first part with the higher and lower works fine, however the bottom part just seems to break, and I don't know how to fix it. If anyone has any solutions that would be greatly appreciated.
Also, in case anyone wanted to see the whole thing, in case there was in issue with that, here it is:
import random
def main():
global attempts
attempts = 0
guess(attempts)
keep_playing(attempts,keep_playing)
def guess(attempts):
number = random.randint(1,100)
print('')
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
while guess != 0:
if guess != number:
if guess < number:
print("Too low, try again It's",number, "for testing purposes") #printing the number makes it easier to fix :/
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again It's",number, "for testing purposes")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
else:
print()
print("Congratulations! You guessed the right number!")
print("There were", attempts,"attempts")
print()
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing
else:
print()
print("You quit too early")
print("The number was ",number)
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing
def keep_playing(attempts,keep_playing):
keep_playing = 'y'
if keep_playing == 'y':
guess(attempts)
keep_playing = str(input("Another game (y to continue)? "))
else:
print()
print("Thanks for playing")
return keep_playing
main()
I notice a couple things here
There is some issue with the naming of your function, python thinks that keep_playing is the str variable keep_playing and not the function. In my code below I will rename the function keep_playing to keep_playing_game.
You need to pass in the parameters when you call the function keep_playing_game so the function knows what the user input and attempts are.
Why are you setting keep_playing = 'y' in the first line of your function def keep_playing_game(attempts,keep_playing)? If you remove this line, your program should run as expected based on the value the user enters and not what the function assigns keep_playing to.
I would recommend trying something like this
import random
def main():
global attempts
attempts = 0
guess(attempts)
# keep_playing(attempts,keep_playing) -> this line should be removed
def guess(attempts):
number = random.randint(1,100)
print('')
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
while guess != 0:
if guess != number:
if guess < number:
print("Too low, try again It's",number, "for testing purposes") #printing the number makes it easier to fix :/
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again It's",number, "for testing purposes")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
else:
print()
print("Congratulations! You guessed the right number!")
print("There were", attempts,"attempts")
print()
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing_game(keep_playing, attempts)
else:
print()
print("You quit too early")
print("The number was ",number)
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing_game(keep_playing, attempts)
def keep_playing_game(keep_playing, attempts):
if keep_playing == 'y':
guess(attempts)
else:
print()
print("Thanks for playing")
return
return None
main()
this is what I have so far I just don't know where to go with it. extremely new with code in general.
# Write a program that lets the user play the game of Rock, Paper, Scissors against the computer.
# The program should work as follows:
# When the program begins, a random number in the range of 1 through 3 is generated.
# If the number is 1, then the computer has chosen rock.
# If the number is 2, then the computer has chosen paper.
# If the number is 3, then the computer has chosen scissors. (Don’t display the computer’s choice yet.)
The user enters his or her choice of “rock,” “paper,” or “scissors” at the keyboard.
The computer’s choice is displayed.
A winner is selected according to the following rules:
If one player chooses rock and the other player chooses scissors, then rock wins. (Rock smashes scissors.)
If one player chooses scissors and the other player chooses paper, then scissors wins. (Scissors cuts paper.)
If one player chooses paper and the other player chooses rock, then paper wins. (Paper wraps rock.)
If both players make the same choice, the game must be played again to determine the winner.
import random
def comp_choice():
comp = random.randint(1, 3)
if comp == 1:
print("rock")
if comp == 2:
print("paper")
if comp == 3:
print("scissors")
player = input("Enter a choice rock, paper, or scissors: ")
comp_choice()
if comp_choice()==player:
#start over
if comp_choice()= rock and player=scissors
We can save the data in a dict so that it makes us easier. Create a dict which has numbers as keys and it's corresponding representative as values. Then use random module to get random choice of the computer. Then ask for input from user. Now use while loop. If computer choice and user input is same, then continue the loop so that it can ask again for input, if not, break the loop. Inside loop, use if and else statements to find who is the winner. Your code:
import random
c={1:"rock",2:"paper",3:"scissors"}
comp=random.randint(1,3)
print(c[comp])
while True:
player=int(input("Enter your input= "))
if player==comp:
continue
elif player not in range(1,4):
print("Invalid input, enter again")
elif (player==1 and comp==2) or (player==2 and comp==3) or (player==3 and comp==1):
print("Computer wins")
break
else:
print("You win")
break
if you want a more data driven desining
from random import randint
#create object numbers
ROCK, PAPER, SCISSORS= '1', '2', '3'
LOST = {
ROCK : SCISSORS, #rock wins against scissors
PAPER: ROCK, #paper wins against rock
SCISSORS: PAPER #scissors wins against paper
}
while True:
#generate the randon number and cast to string
computer_choose = str(randint(a=1,b=3))
question = f'{"-"*50}\nEnter a choice rock({ROCK}) paper({PAPER}) scissors({SCISSORS}): '
user_choose = input(question)
#check if user input is valid
if user_choose not in [ROCK,PAPER,SCISSORS]:
print('invalid answer, only numbers in range(1,2,3) are valid')
continue
elif user_choose == computer_choose:
print(f'its a draw, lets try again:\nComputer Choice:{computer_choose}')
continue
elif user_choose == LOST[computer_choose]:
print(f'you lost\nComputer Choice:{computer_choose}')
else:
print(f'you win\nComputer Choice:{computer_choose}')
break
import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for (computer_choice) in range(1,6):
user_choice = input("What number between 1 and " + max_value + " do you choose? ")
if user_choice == computer_choice:
print("Thank you for playing. ")
Needs to give the user 5 chances to give the computer_choice before failing. For loop is required.
You can add a counter which will keep the track of the number of attemps that user has made so far.
Also need to convert user input from string to int type.
import random
max_value = int(input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? "))
computer_choice = random.randint(1, int(max_value))
count = 0
for (computer_choice) in range(1,6):
user_choice = int(input("What number between 1 and " + max_value + " do you choose? "))
count += 1
if user_choice == computer_choice:
print("Thank you for playing. ")
if count==5:
print("you have reached maximum attempt limit")
exit(0)
Run the for loop with separate variable then computer_choice. Also add eval to input statement as it gives string to conert the user_choice to integer and add a break statement in if user_choice == computer_choice to end the program, rest should work fine.
import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for (i) in range(1,6):
#input takes string convert choice to int using eval
user_choice = eval(input("What number between 1 and " + max_value + " do you choose? "))
if user_choice == computer_choice:
print("Thank you for playing. ")
break
if(i==5):
print("Sorry, maximum number of tries reached.")
One of the approach:
import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for i in range(1,6):
user_choice = input("What number between 1 and " + max_value + " do you choose? ")
if int(user_choice) == int(computer_choice):
print("Right choice. Thank you for playing. ")
break
elif(i == 5):
print ("Sorry, maximum attempts reached...")
break
else:
print ("Oops, wrong choice, pls choose again...")
Output:
I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? 5
What number between 1 and 5 do you choose? 1
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 3
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 4
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 5
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 6
Sorry, maximum attempts reached...
I am making a rock paper scissors game and for that I want the computer to choose a random choice excluding the player's choice so if a player chooses rock then it should choose randomly between paper and scissors. Can anyone help me out?
This is my code:
symbols = [rock,paper,scissors]
player_input = input("Please type 1 for rock, 2 for paper, and 3 for scissors. ")
player_choice = int(player_input) - 1
You could try this code. The first choice will be removed from the list of choices.
c = [1,2,3] # 3 choices
a = random.choice(c) # pick the first (e.g. by input player)
print (a)
c.remove(a) # remove it from the list of choices
b = random.choice(c) # pick the second (e.g. by computer)
print (b)
You can try something along this line (assuming I am continuing from your code above):
import random
remaining_symbol = symbols
remaining_symbol.pop(player_choice)
result = remaining_symbol[random.randint(0, len(remaining_symbol))]
print(result) #this should give you the answer
I have not tested this code but it should be along this idea.
You could do something like that:
from random import choice
symbols = ["rock","paper","scissors"]
try:
player_input = int(input("Please type 1 for rock, 2 for paper, and 3 for scissors. ")) - 1
except (ValueError, TypeError):
print("Not a valid input")
else:
symbols_two = [thing for thing in symbols if thing != symbols[player_input]]
print('random answer: {}'.format(choice(symbols_two)))
this code is not tested for errors