Why does my else statement trigger all the time - python

I made a simple rock paper scissors game in python to learn. Everything is working except the last else statement. I simply want to check if none of the previous if statements are true then it prints out 'not a valid command' but for some reason it prints it out regardless what i type. Must be something very basic I'm missing but I just can't see it.
import random
while True:
cpu_choice = random.randint(0, 2)
cpu = ["Rock", "Paper", "Scissors"]
print("Pick Rock,Paper or Scissors")
choice = input("")
if choice.capitalize() == "Paper":
if cpu_choice == 2:
print("You lose")
elif cpu_choice == 1:
print("Tied!")
else:
print("You won!")
if choice.capitalize() == "Rock":
if cpu_choice == 1:
print("You lose")
elif cpu_choice == 0:
print("Tied!")
else:
print("You won!")
if choice.capitalize() == "Scissors":
if cpu_choice == 0:
print("You lose")
elif cpu_choice == 2:
print("Tied!")
else:
print("You won!")
if choice.capitalize() == "Exit":
print("Exiting...")
break
else:
print("Not a valid command")
print("Computer picked: " + cpu[cpu_choice])

Your else statement will run whenever choice.capitalize() == "Exit" evaluates to False. You need to turn all your other if statements into elif statements to treat it all as one if/elif/else block.
if choice.capitalize() == "Paper":
...
elif choice.capitalize() == "Rock":
...
elif choice.capitalize() == "Scissors":
...
elif choice.capitalize() == "Exit":
...
else:
print("Not a valid command")

Related

Tricks and tips for beginners to shorten and simplify code

I am looking for ways to shorten and simplify my python code. Here is one example of one small rock/paper/scissors game I wrote earlier. The code kinda looks too long to me and I want to try to learn how to shorten my code.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
if game_limit == 5 and comp_wins > user_wins:
print("The game is over, YOU LOST!")
elif game_limit == 5 and comp_wins < user_wins:
print("The game is over, YOU WON!")
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "rock":
print("its a draw")
elif user_input == "rock" and comp_input == "paper":
print("You lose!")
comp_wins += 1
if user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "scissors" and comp_input == "scissors":
print("its a draw")
elif user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
if user_input == "paper" and comp_input == "rock":
print("You win")
user_wins += 1
elif user_input == "paper" and comp_input == "paper":
print("its a draw")
elif user_input == "paper" and comp_input == "scissors":
print("You lose!")
comp_wins += 1
Yes. You could simplify your logic by having compound and/or tests for the player and user. Following is a revised version of your code with some simplified logic.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
if game_limit >= 5: # Tweak
if comp_wins > user_wins:
print("The game is over, YOU LOST!")
break
if comp_wins < user_wins:
print("The game is over, YOU WON!")
break
else:
print("We go to sudden death!")
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors" or user_input == "paper" and comp_input == "rock" or user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "paper" or user_input == "paper" and comp_input == "scissors" or user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
else:
print("It's a draw")
This way all of the scenarios where the user can win are in one logical test and all of the scenarios where the computer can win are in another logical test. If neither test is true, then the default would have to be a draw.
Also, I tweaked game limit test because if the computer and user have the same score when the game limit is reached, the test result would be false and the game would then continue on and not stop. So there is a bit of additional code to handle a tie after five rounds.
Give that a try.

Python: Conditional Exit based on user input

Just need this for a game program. At the end of the Rock-Paper-Scissors program it asks if the user wants to play again or not, and uses sys.exit() to terminate the program. However, instead of terminating the program if the user enters something that isn't 'Y' or 'y' in the replayFunc() function, it goes into the code under the except: block in main(). Any help is appreciated.
import random
import os
import sys
userOS = str(sys.platform)
def clearFunc():
if "win32" not in userOS:
os.system('clear')
else:
os.system('cls')
def replayFunc():
exitPrompt = input("Do you want to play again? (Y/N): ")
if exitPrompt == 'Y' or exitPrompt == 'y':
main()
else:
sys.exit(0)
def main():
oppChoice = random.randint(1,3)
playerChoice = int
print("Welcome to Rock-Paper-Scissors!")
input("\nPress Enter to continue: ")
clearFunc()
try:
playerChoice = int(input("Please use 1-3 to select from the list below:\n\n1. Rock\n2. Paper\n3. Scissors\n"))
if playerChoice == 1 and oppChoice == 1:
print("You tied!")
replayFunc()
elif playerChoice == 1 and oppChoice == 2:
print("Computer Wins!")
replayFunc()
elif playerChoice == 1 and oppChoice == 3:
print("You win!")
replayFunc()
elif playerChoice == 2 and oppChoice == 1:
print("You win!")
replayFunc()
elif playerChoice == 2 and oppChoice == 2:
print("You tied!")
replayFunc()
elif playerChoice == 2 and oppChoice == 3:
print("Computer Wins!")
replayFunc()
elif playerChoice == 3 and oppChoice == 1:
print("Computer wins!")
replayFunc()
elif playerChoice == 3 and oppChoice == 2:
print("You win!")
replayFunc()
elif playerChoice == 3 and oppChoice == 3:
print("You tied!")
replayFunc()
else:
print("Didn't get that")
main()
except:
print("TypeError")
main()
main()
sys.exit(0) is basically implemented as raise SystemExit(0). It's an exception, because you need to bubble up so context managers (with statements) and finally blocks can clean up properly.
The reason bare except: is frowned upon is because it catches even exceptions that shouldn't be caught, e.g. SystemExit. So stop using it, and catch only exceptions you know how to handle, or at least change it to except Exception: which won't catch the special, shouldn't be caught exceptions (like SystemExit and KeyboardInterrupt).

rock paper scissor python program input error

import random
def rpc():
a = ["rock", "paper", "scissor"]
b = random.choice(a)
print(b)
userinput = input('please type rock, paper or scissor:')
if userinput == "":
print("please print the right thing")
rpc()
if userinput != "rock":
print("type the right thing!")
rpc()
if userinput != "paper":
print("type the right thing!")
rpc()
if userinput != "scissor":
print("type the right thing!")
rpc()
while b == userinput:
print("it is a draw, do you want to play another one?")
c = input("type 'y' if you want to play one more time or press 'n': ")
if c == 'y':
rpc()
elif c =='n':
break
else:
print("print the right words please")
if b == 'rock' and userinput == 'paper':
print("you win!")
rpc()
elif b == 'rock' and userinput == 'scissor':
print("you lost")
rpc()
elif b == 'paper' and userinput == 'scissor':
print("you win!")
rpc()
elif b == 'paper' and userinput == 'rock':
print("you lost!")
rpc()
elif b == 'scissor' and userinput == 'rock':
print("you win!")
rpc()
elif b == 'scissor' and userinput == 'paper':
print("you lost!")
rpc()
rpc()
This is my code for rock paper and scissor, it's pretty simple but when I run my code and input my rock, paper and scissor, I get my please print the right thing statement, O have no idea why it's happening, any help would be wonderful, thank you!
Lets clean this up....
userinput = input('please type rock, paper or scissor:')
while userinput not in acceptable_inputs:
userinput = input('please type rock, paper or scissor:')
opponents_choice = random.choice(objects)
# Check and print. Loop to keep playing - 2 out of 3 wins....
import random
def winner(riya,siya):
if (riya==siya):
return None
elif (riya=="s"):
if (siya=="p"):
return False
elif(siya=="k"):
return True
elif (riya=="p"):
if (siya=="s"):
return False
elif (siya=="k"):
return True
elif (riya=="k"):
if (siya=="s"):
return True
elif (siya=="p"):
return False
print("riya pick: stone(s) paper(p) sessior(k)")
a= random.randint(1,3)
if a==1:
riya="s"
elif a==2:
riya="p"
elif a==3:
riya="k"
siya=input(" siya pick: stone(s) paper(p) sessior(k)")
b=winner(riya,siya)
print(f"riya pick{riya}")
print(f"siya pick {siya}")
if b==None:
print("tie")
elif b:
print("winner")`enter code here`
else:enter code here
print("loose")

restarting while loop in a game

I'm trying to write a rock-paper-scissors game in python.this is the code:
D_0 = {1: "rock", 2: "scissors", 3: "paper"}
from random import randint
play = False
name = input("What is your name?: ")
print("%s you have to pick among rock,paper and scissors." % name)
while play == False:
p_1 = input("which one?")
computer = D_0[randint(1, 3)]
print("my choice is: ",computer)
if p_1 == computer:
print("it's a draw")
elif p_1 == "scissors" and computer == "paper":
print("you won!")
elif p_1 == "paper" and computer == "scissors":
print("you lost!")
elif p_1 == "scissors" and computer == "rock":
print("you lost!")
elif p_1 == "rock" and computer == "paper":
print("you lost!")
elif p_1 == "rock" and computer == "scissors":
print("you won!")
elif p_1 == "paper" and computer == "rock":
print("you won!")
else:
print("Invalid input")
break
again = input("do you want another round?:")
if again == "yes":
play = False
else:
play = True
the program works well but I want it to ask the player whether or not he/she wants to do another round.If the answer is yes the program must restart the loop.
The problem is I don't know how to do that.I know it's probably related to True and False and I attempted to do something as you can see in the code but it didn't work.
please Help me.
A simple fix might be just putting your while loop as True and continuing to loop until you break the execution:
D_0 = {1: "rock", 2: "scissors", 3: "paper"}
from random import randint
name = input("What is your name?: ")
print("%s you have to pick among rock,paper and scissors." % name)
while True:
p_1 = input("which one?")
computer = D_0[randint(1, 3)]
print("my choice is: ", computer)
if p_1 == computer:
print("it's a draw")
elif p_1 == "scissors" and computer == "paper":
print("you won!")
elif p_1 == "paper" and computer == "scissors":
print("you lost!")
elif p_1 == "scissors" and computer == "rock":
print("you lost!")
elif p_1 == "rock" and computer == "paper":
print("you lost!")
elif p_1 == "rock" and computer == "scissors":
print("you won!")
elif p_1 == "paper" and computer == "rock":
print("you won!")
else:
print("Invalid input")
again = input("do you want another round?:")
if again != "yes":
break

rock paper scissors lizard spock, Python

I am creating a rock paper scissors lizard spock game in Python for my class and i am trying to figure out why whatever choice I make I am always winning even though I set up all my if statements correct. `
import random
def instructions():
play = input("Would you like to play Rock, Paper, Scissors, Lizard, Spock(y/n): ").lower()
if play == "y":
print("1.Rock")
print("2.Paper")
print("3.Scissors")
print("4.Lizard")
print("5.Spock")
elif play != "n":
print("error has accured please type y for yes or n for no:")
instructions()
def getPlayerChoice():
choice = int(input("What is your choice user?: "))
if choice > 5:
print("Invalid number please try again....")
getPlayerChoice()
elif choice < 1:
print("Invalid number please try again....")
getPlayerChoice()
elif choice == 1:
print("You picked Rock")
elif choice == 2:
print("You picked Paper")
elif choice == 3:
print("You picked Scissors")
elif choice == 4:
print("You picked Lizard")
elif choice == 5:
print("You picked Spock")
return choice
def getCPUChoice():
choice = random.randint(1,5)
if choice == 1:
print("CPU picked Rock")
elif choice == 2:
print("CPU picked Paper")
elif choice == 3:
print("CPU picked Scissors")
elif choice == 4:
print("CPU picked Lizard")
elif choice == 5:
print("CPU picked Spock")
return choice
def winner(playerChoice, CPUChoice, playerWins, CPUWins, ties):
if playerChoice == 1 and CPUChoice == 3 or CPUChoice == 4:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 2 and CPUChoice == 1 or CPUChoice == 5:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 3 and CPUChoice == 2 or CPUChoice == 4:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 4 and CPUChoice == 2 or CPUChoice == 5:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 5 and CPUChoice == 1 or CPUChoice == 3:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == CPUChoice:
print("Tie")
ties = ties.append(1)
else:
print("CPU won")
CPUWins = CPUWins.append(1)
return
def gameTotal(playerWins, CPUWins, ties):
playerWins = sum(playerWins)
CPUWins = sum(CPUWins)
ties = sum(ties)
print("Player final score: ", playerWins)
print("CPU final Score: ", CPUWins)
print("Total ties: ",ties)
def main():
playerChoice = 0
playerWins = []
CPUChoice = 0
CPUWins = []
ties = []
finalPlayerWins = 0
finalCPUWins = 0
finalTies = 0
Continue = 'y'
instructions()
while Continue == 'y':
playerChoice = getPlayerChoice()
CPUChoice = getCPUChoice()
winner(playerChoice,CPUChoice,playerWins, CPUWins, ties)
Continue = input("Would you like to play again (y/n):").lower()
if Continue == 'n':
print("Printing final scores.")
break
gameTotal(playerWins, CPUWins, ties)
main()
`
To summarize all of the things you should pay attention to:
boolean conditions - the result changes with the parentheses that are inside the condition.
if True or (True and False) --> this basically calculates the True and False part first (like in regular math) and then you have True or False which evaluates to True.
if True or True and False --> this basically calculates the True or True part first (like in regular math) and then you have True and False which evaluates to False - because you don't use parentheses.
Do not call a function within the same function - this is called recursion, and it's not relevant for what you need. Use a while loop, that runs as long as i.e. - you didn't get a proper choice input (while choice!='n' and choice!='y':).
Your instructions choice - the choice made by the user doesn't really change the flow of the game. the game starts also if the user entered no. You should add an exit statement in the instructions function.
The reason is you are missing parentheses on all of the "if" conditions.
if False and True or True # =True
if False and (True or False) # =False

Categories