nested if/else/elsif not looping - python

I'm really new to coding and Python and have beent trying the "rock, paper, scissor" game. Everything seems to work except the looping and i'm really struggling to understand why, I thought that setting the player to False would reloop the code?
from random import randint
t = ["rock", "paper", "scissors"]
computer = t[randint(0, 2)]
player = False
while player == False:
player = input("rock, paper or scissors?")
if player == computer:
print("Tie!")
elif player == "rock":
if computer == "paper":
print ("sorry, you lose!", computer, "beats", player)
else:
print("Great, you win!", player, "destroys", computer)
elif player == "paper":
if computer == "scissors":
print("sorry, you lose", computer, "beats", player)
else:
print("Great, you win!", player, "destroys", computer)
elif player == "scissors":
if computer == "rock":
print("sorry, you lose!", computer, "beats", player)
else:
print("Great, you win!", player, "destorys", computer)
else:
print("not a valid input, try again")
player = False
computer = t[randint(0, 2)]
Any help is welcome!

You are overwriting player with an string in the line with input(). Then player is never equal to False. If you want to loop endless you can simply do it with a while True:. Then it is even better readable.

In Python, strings (text) are True as long as they are not empty.
Similarly, lists, sets and other collections are True unless empty.
It has a great advantage once you are aware of it.
Also, your indentation was wrong. You need to move the computer=t[randint(0,2)] into the loop to pick a new choice each time. Setting player=False at the end does not make sense.
from random import randint
t = ["rock", "paper", "scissors"]
player = None
while player != "quit":
computer = t[randint(0, 2)]
player = input("rock, paper or scissors?")
if player == computer:
print("Tie!")
elif player == "rock":
if computer == "paper":
print ("sorry, you lose!", computer, "beats", player)
else:
print("Great, you win!", player, "destroys", computer)
elif player == "paper":
if computer == "scissors":
print("sorry, you lose", computer, "beats", player)
else:
print("Great, you win!", player, "destroys", computer)
elif player == "scissors":
if computer == "rock":
print("sorry, you lose!", computer, "beats", player)
else:
print("Great, you win!", player, "destorys", computer)
elif player != "quit":
print("not a valid input, try again")

python creates code blocks based on indentation.
Look at the indentation of your second player = False statement, that should help :)

Indent these lines so they are in the while loop
player = False
computer = t[randint(0, 2)]

Your Player variable is a boolean and a string
The string is "rock", "paper" or "scissors" so it is bool(Player) = True.
You need 2 variables, game_loop (bool) and player_response (string)
The computer choice have to be in the loop (computer = t[randint(0, 2)])

Related

Python while True positioning confusion

I have made a rock paper scissors program as I am just beginning but I have discovered that the 2 positions I tried putting a while True: command have completely opposite effects. I can't understand the logic/reasoning behind it and was hoping someone would be able to explain it in simple terms.
the first copy of the code is the one that functions properly with the while True: on the 3rd line.
the second version of the code is what I had done first with the while True: on the 6th line.
the second version results in the result of the game being printed endlessly so E.G. "You win" a million times whereas when the while True: is on the 3rd line it runs as intended with the win/lose or tie message only printing once.
Can someone explain why that is just so I understand for future reference.
import random
moves = "rock", "paper", "scissors"
while True:
computer = moves[random.randint(0,2)]
player = input("Choose rock, paper or scissors... Or 'end' to end the game: ")
if player == "end":
print("Game over!")
break
elif player == "rock" and computer == "scissors" or player == "scissors" and computer == "paper" or player == "paper" and computer == "rock":
print("You win", player, "beats", computer)
elif player == computer:
print("Tie!")
else:
print("You lose!", computer, "beats", player)
import random
moves = "rock", "paper", "scissors"
computer = moves[random.randint(0,2)]
player = input("Choose rock, paper or scissors... Or 'end' to end the game: ")
while True:
if player == "end":
print("Game over!")
break
elif player == "rock" and computer == "scissors" or player == "scissors" and computer == "paper" or player == "paper" and computer == "rock":
print("You win", player, "beats", computer)
elif player == computer:
print("Tie!")
else:
print("You lose!", computer, "beats", player)

Why am I not getting the correct outputs for my game?

I am very new to Python and coding in general. I tried to create my own Rock, Paper, Scissors game. The issue I'm getting can be tested by doing the following: typing "rock", then typing "yes" to play again and repeating those two steps. Eventually, it gives me an "Invalid Input." It is only supposed to print this if the user types something besides rock, paper, or scissors. Is there any way I can fix this? I'd really appreciate any input and advice. Thank you for your time.
import random
# to loop the program
def Repeat():
Answer = input ("Do you want to play again? (Y/N): ")
if Answer == ("Yes") or Answer == ("yes") or Answer == ("Y") or Answer == ("y"):
Game()
if Answer == ("No") or Answer == ("no") or Answer == ("N") or Answer == ("n"):
exit()
else:
print ("Invalid Input")
Repeat()
def Game():
# Variable Reset
Choice = None
Opponent_Choice = None
# Choices
Opponent_Choices = ["Rock", "Paper", "Scissors"]
Choice = input ("Type Rock, Paper, or Scissors: ")
Opponent_Choice = random.choice(Opponent_Choices)
# Outcomes
# if you choose rock
if Choice == "Rock" or Choice == "rock":
if Opponent_Choice == "Paper":
print ("your opponent chose Paper. You lose!")
Repeat()
elif Opponent_Choice == "Scissors":
print ("your opponent chose Scissors. You win!")
Repeat()
elif Opponent_Choice == "Paper":
print ("your opponnent chose Rock. It was a tie!")
Repeat()
# if you choose paper
elif Choice == "Paper" or Choice == "paper":
if Opponent_Choice == "Paper":
print ("your opponent chose Paper. It was a tie!")
Repeat()
elif Opponent_Choice == "Scissors":
print ("your opponent chose Scissors. You lose!")
Repeat()
elif Opponent_Choice == "Paper":
print ("your opponent chose Rock. You win!")
Repeat()
# if you choose scissors
elif Choice == "Scissors" or Choice == "scissors":
if Opponent_Choice == "Paper":
print ("your opponent chose Paper. You win!")
Repeat()
elif Opponent_Choice == "Scissors":
print ("your opponent chose Scissors. It was a tie!")
Repeat()
elif Opponent_Choice == "Paper":
print ("your opponet chose Rock. You lose!")
Repeat()
else:
print ("Invalid input")
Game()
Game()
p.s. Sorry for the messy code :P Still very new to this.
The actual issue:
The actual issue
The reason you seem to be getting the invalid input is due to your check for the Opponent_choice not checking for Rock but instead checking for paper twice. Therefore it jumps all the way to the else statement at the end of the function which contains the invalid input print statement if the opponent chooses Rock.
if Opponent_Choice == "Paper":
print ("your opponent chose Paper. You lose!")
Repeat()
elif Opponent_Choice == "Scissors":
print ("your opponent chose Sciccors. You win!")
Repeat()
elif Opponent_Choice == "Paper": #error here
print ("your opponnet chose Rock. It was a tie!")
Repeat()
The fix would be
if Opponent_Choice == "Paper":
print ("your opponent chose Paper. You lose!")
Repeat()
elif Opponent_Choice == "Scissors":
print ("your opponent chose Sciccors. You win!")
Repeat()
elif Opponent_Choice == "Rock": #change made here
print ("your opponnet chose Rock. It was a tie!")
Repeat()
One problem with the code is that you have functions calling themselves.
The function Game() and Repeat() in your code do this. This is called recursion and can be very useful. But it can also cause problems if used incorrectly. For one thing, let's consider the code above DOES work, if you played it for very long, you would get a stack overflow exception. I would suggest some research on recursion and "the stack" to understand this better.
If you take out the recursion like so for example:
it should work.
I also noticed you are checking user input on the confirmation question. Very nice. But why not for the Rock Paper Scissors selection?
Example refactor without recursion:
import random
# to loop the program
def Repeat():
while True:
result = Confirm()
if (result is True):
break
def Confirm():
Answer = input ("Do you want to play again? (Y/N): ")
if Answer == ("Yes") or Answer == ("yes") or Answer == ("Y") or Answer == ("y"):
return True
if Answer == ("No") or Answer == ("no") or Answer == ("N") or Answer == ("n"):
exit()
else:
return False
def Game():
# Choices
Opponent_Choices = ["Rock", "Paper", "Scissors"]
Choice = input("Type Rock, Paper, or Scissors: ")
Opponent_Choice = random.choice(Opponent_Choices)
# Outcomes
# if you choose rock
if Choice == "Rock" or Choice == "rock":
if Opponent_Choice == "Paper":
print ("your opponent chose Paper. You lose!")
Repeat()
elif Opponent_Choice == "Scissors":
print ("your opponent chose Sciccors. You win!")
Repeat()
elif Opponent_Choice == "Paper":
print ("your opponnet chose Rock. It was a tie!")
Repeat()
# if you choose paper
elif Choice == "Paper" or Choice == "paper":
if Opponent_Choice == "Paper":
print ("your opponent chose Paper. It was a tie!")
Repeat()
elif Opponent_Choice == "Scissors":
print ("your opponent chose Sciccors. You lose!")
Repeat()
elif Opponent_Choice == "Paper":
print ("your opponet chose Rock. You win!")
Repeat()
# if you choose scissors
elif Choice == "Scissors" or Choice == "scissors":
if Opponent_Choice == "Paper":
print ("your opponent chose Paper. You win!")
Repeat()
elif Opponent_Choice == "Scissors":
print ("your opponent chose Sciccors. It was a tie!")
Repeat()
elif Opponent_Choice == "Paper":
print ("your opponet chose Rock. You lose!")
Repeat()
else:
print ("Invalid input")
while True:
Game()
I can't give you an answer about why there's an error, but here is a clue: the 'invalid input' message you get was from line 11, in Repeat(). The line will only be run if the if statement above it evaluates to false, and the if statement will only be run if the other if statement above it exits, which means you'll only get the message if the Game()-function somehow exited, which shouldn't happen. You can add a print()-statement after line 7 to confirm that. The REAL reason was because you used recursion, like #dominic has said. And you should try their code.
PS: don't feel bad about messy code. Mine is worse than yours. But you really don't have to capitalize the variables and function. Good luck with Python!

Sometimes my code doesn't work and sometimes it does

I am creating a rock,paper,scissors game but sometimes my output shows and sometimes it doesn't what's seems to be the problem here?
So far this is my code:
import random
round = 1
win = 0
lose = 0
tie = 0
while True:
choices = ["rock", "paper", "scissors"]
computer = random.choice(choices)
player = None
while player not in choices:
player = input("Rock, paper, or scissors??: ").lower()
if player == computer:
print("Player : ", player)
print("Computer: ", computer)
print("Tie!")
tie+=1
elif player == "rock":
if computer == "paper":
print("Player : ", player)
print("Computer: ", computer)
print("You lose")
lose+=1
elif player == "paper":
if computer == "rock":
print("Player : ", player)
print("Computer: ", computer)
print("You win")
win+=1
elif player == "scissors":
if computer == "rock":
print("Player : ", player)
print("Computer: ", computer)
print("You lose")
lose+=1
elif player == "rock":
if computer == "scissors":
print("Player : ", player)
print("Computer: ", computer)
print("You win")
win+=1
elif player == "paper":
if computer == "scissors":
print("Player : ", player)
print("Computer: ", computer)
print("You lose")
lose+=1
elif player == "scissors":
if computer == "paper":
print("Player : ", player)
print("Computer: ", computer)
print("You win")
win+=1
play_again = input("Would you like to play again? (yes/no): ").lower()
if play_again != "yes":
print("ROUNDS PLAYED: ",round)
print("TOTAL WINS:",win)
print("TOTAL LOSES: ",lose)
print("TOTAL TIME PLAYER TIED WITH COMPUTER: ",tie)
break
elif play_again == "yes":
rounds = round + 1
print("NEW ROUND, ROUND: ",rounds)
print("Bye, Thanks for playing this program")
now if I were to choose paper it won't work it will show me something like this:
(also I have realized that my rounds doesn't count.)
Rock, paper, or scissors??: paper
Would you like to play again? (yes/no): yes
NEW ROUND, ROUND: 2
Rock, paper, or scissors??: paper
Would you like to play again? (yes/no): yes
NEW ROUND, ROUND: 2
Rock, paper, or scissors??: scissors
Player : scissors
Computer: scissors
Tie!
Would you like to play again? (yes/no): yes
NEW ROUND, ROUND: 2
Rock, paper, or scissors??: rock
Player : rock
Computer: rock
Tie!
Would you like to play again? (yes/no): yes
NEW ROUND, ROUND: 2
Rock, paper, or scissors??: paper
Would you like to play again? (yes/no): no
ROUNDS PLAYED: 1
TOTAL WINS: 0
TOTAL LOSES: 0
TOTAL TIME PLAYER TIED WITH COMPUTER: 2
Bye, Thanks for playing this program
I am new to programming any help would be highly appreciated.
You have two different elif block with same conditions. For Example:
elif player == "scissors":
if computer == "rock":
print("Player : ", player)
print("Computer: ", computer)
print("You lose")
lose += 1
elif player == "scissors":
if computer == "paper":
print("Player : ", player)
print("Computer: ", computer)
print("You win")
win += 1
In this case, if player choose scissors what is gonna happen?
Python starts to search for this condition but only the first one will be valid.
Thus, you should construct your elif block like this:
elif player == "scissors":
if computer == "paper":
print("Player : ", player)
print("Computer: ", computer)
print("You win")
win += 1
elif computer == "rock":
print("Player : ", player)
print("Computer: ", computer)
print("You lose")
lose += 1
Let's look at your second question.
You have a variable named round and rounds. These are same I guess but you are incrementing rounds by the line rounds = round+1.
Instead, try
round = round+1
or
round+=1
Hope this helps.
Your code is not working sometimes because you have not applied all the condition for example what if player choses paper and computer choses rock.
Also the number of round is not increasing because you are saving it in new variable every time, hence not increasing .
rounds = round + 1
above line of code should be
round = round + 1
If you put the same condition more than once in any if-elif structure, only the first conditional if/elif branch will satisfy and the latter will never be executed. For example, in your code in the if-else statement, you have written the same condition elif player == "rock" twice.
elif player == "rock":
if computer == "paper":
print("Player : ", player)
print("Computer: ", computer)
print("You lose")
lose+=1
elif player == "paper":
if computer == "rock":
print("Player : ", player)
print("Computer: ", computer)
print("You win")
win+=1
elif player == "scissors":
if computer == "rock":
print("Player : ", player)
print("Computer: ", computer)
print("You lose")
lose+=1
elif player == "rock":
if computer == "scissors":
print("Player : ", player)
print("Computer: ", computer)
print("You win")
win+=1
Say, your player has entered rock and computer has chosen scissors. When the code executes, only the first elif player == "rock" will be evaluated, inside this statement, you only checked if the computer has chosen paper or not. But computer has chosen scissors which you did not check in this statement. So, the interpreter will do nothing and skip the rest of the if-else condition.
To make it work, you need to use only one else statement for the same condition, like this:
elif player == "rock":
if computer == "paper":
print("Player : ", player)
print("Computer: ", computer)
print("You lose")
lose+=1
elif computer == "scissors":
print("Player : ", player)
print("Computer: ", computer)
print("You win")
win+=1
You need to follow this for all the possible outcomes.

TypeError: input expected at most 1 arguments, got 3 (Rock, paper, scissors game)

Keep getting this syntax error
TypeError: input expected at most 1 arguments, got 3
Does anyone know how to fix this?
from random import randint
from tkinter import *
po = ["Rock", "Paper", "Scissors"]
player = False
cpu = po[randint(0, 2)]
while player == False:
player = input("Rock", "Paper", "Scissors?")
if player == computer:
print("Tie")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
else:
print("You win!", player, "smashes", computer)
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cuts", player)
else:
print("You win!", player, "covers", computer)
elif player == "Scissors":
if computer == "Rock":
print("You lose!", computer, "smashes", player)
else:
print("You win!", player, "cut", computer)
else:
print("That's not a valid play. Check your spelling!")
player = False
computer = po[randint(0,2)]
You're misusing input. The argument passed to it is merely the prompt presented, and thus can only be a single string.
player = input("Rock, Paper, Scissors?")
Is probably more like what you want.
It seems that you never really give the person a chance to input wether rock, paper, or scissors, you should probably do something along the lines of
player = str(input("Rock, Paper, or Scissors?"))
That way player is assigned to whichever the player chooses

Returning to the main menu in my game - Python

I am creating a Rock, Paper, Scissors game. The game has a main menu which I need to be able to return to from each sub menu. I've tried a few different method I could think of as well as looked here and elsewhere online to determine a method of solving my problem.
I want the user to be able to select an option from the main menu, go to the selected sub menu, then be prompted with an option to return to the main menu. For example, Select the rules sub menu, then return to the main menu. Or, select to play a round of Rock, Paper, Scissors, then select to play again or return back to the main menu.
# random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# module to run the program
#def main():
# menu()
def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
computer = WEAPON[randint(0,2)]
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
# two player mode
def twoPlayer():
fight = False
player1 = ""
player2 = ""
print("\n\tPlayer VS Player")
while fight == False:
player1 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player1 = player1.lower()
player2 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player2 = player2.lower()
if player1 == player2:
print(player1," vs ",player2)
print("It's a tie!\n")
elif player1 == "rock":
if player2 == "paper":
print(player1," vs ",player2)
print("Paper covers rock! Player 2 wins!\n")
else:
print("Rock smashes",player2,". Player 1 wins!\n")
elif player1 == "paper":
if player2 == "scissors":
print(player1," vs ",player2)
print("Scissors cut paper! Player 2 wins!\n")
else:
print("Paper covers",player2,". Player 1 wins!\n")
elif player1 == "scissors":
if player2 == "rock":
print(player1," vs ",player2)
print("Rock smashes scissors! Player 2 wins!\n")
else:
print("Scissors cut",player2,". Player 1 wins!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
def endGame():
print("Thank you for playing!")
main()
Currently my only test is within the onePlayer() module. The idea behind my code is to ask the user if they want to continue playing. If they don't want to continue playing, then I want the program to bring them back to the main menu.
You are using player variable for two works, instead of that you can use another variable to just check the condition and another to take user input.
Also you can check the condition like : if again in ["yes","y"]
def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
#computer = WEAPON[randint(0,2)]
#temporary
computer = "paper"
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again=="yes" or again=="y":
player = False
else:
player = True
main()
main()
Do a try and except command. If they say no your code should be quit(). If they say yes put a continue command and it will restart the whole thing.
put your main method in a while (True): loop, and if option 4 is called, use break like this:
elif menuSelect == 4:
break
add an indent to
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
else:
main()
and rather than calling main() just set player = True also, your Weapon array has not been defined. easy fix, just add WEAPON = ["rock", "paper", "scissors"] to the beginning of your onePlayer(): method. I can see another problem, change
if again == "yes" or "y":
to
if again == "yes" or again == "y":
one last thing, don't forget your imports! (put it at the top of your code.)
from random import randint
BTW, the break statement just tells python to leave whatever for loop or while loop it's in.

Categories

Resources