I have a bug in my program that I cannot figure out - python

So, I just recently started coding and decided to make a rock paper scissors game; However, my program has a bug where if the user enters "rock" the correct code block doesn't run. Instead it runs an else statement that's only meant to run when the user enters, "no". I tried using a while loop instead of just if else statements but it didn't make a difference.
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
user = str(input("Great, select Rock Paper or Scissors:"))
if q_1 != "yes":
if q_1 == comp:
print("Oh No, a Tie!")
elif q_1 == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif q_1 == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
else:
print("Ok :(")

There are a few issues with your code.
First of all your code only plays the game if the user doesn't enter "yes". You need to change if q_1 != "yes": to if q_1 == "yes":.
Secondly, your code asks the user to choose rock, paper or scissors regardless of whether they have said they want to play or not. Fix this by moving user = str(input("Great, select Rock Paper or Scissors:")) to under the if q_1 == "yes": if statement.
Thirdly, your code uses q1 instead of user as it should.
Here is how your code should look:
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
if q_1 == "yes":
user = str(input("Great, select Rock Paper or Scissors:"))
if user == comp:
print("Oh No, a Tie!")
elif user == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif user == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
print("I played:",comp)
else:
print("Ok :(")

Related

Always receive 'You Lose' message in RPS against computer

For my exercise, I have to get the computer to play against the user in RPS. However, after both the computer and I input our action, the user will always receive a 'You Lose'.
import random
def get_computer_move():
"""Deterministic 'random' move chooser"""
options = ['rock', 'paper', 'scissors']
return options[random.randint(0, 2)]
def game_result(move1, move2):
"""game_result *exactly* as defined in question one"""
options = ["rock", "paper", "scissors"]
if move1 == move2:
return 0
elif move1 == "paper" and move2 == "rock":
return 1
elif move1 == "rock" and move2 == "scissors":
return 1
elif move1 == "scissors" and move2 == "paper":
return 1
else:
return 2
def main():
"""Runs a single game of PSR"""
print("Let's Play Paper, Scissors, Rock!")
user1 = input("Player one move: ").lower()
computer1 = print("The computer plays " + get_computer_move())
game_result(computer1, user1)
if user1 == computer1:
return print("It's a draw")
elif user1 == "paper" and computer1 == "rock":
return print("You win")
elif user1 == "rock" and computer1 == "scissors":
return print("You win")
elif user1 == "scissors" and computer1 == "paper":
return print("You win")
else:
return print("You lose")
main()
Here is my code although it is quite messy.
What I want to happen is:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
It's a draw
But it will always come out as:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
You lose
Help would be appreciated.
print returns none, you want to save the computers move and then print that separately
computer1 = get_computer_move()
print("The computer plays", computer1)

Do not want to let Computer play his turn once Player enters invalid choice. How to achieve?

I'm a beginner and writing a code for "Rock Paper Scissors" game. I don't want to run this game(code) over and over again, hence, used while loop. Now, at the "else:" step when any invalid choice is typed by the Player, Computer plays it's turn too after which "Invalid choice. Play your turn again!" is displayed.
I want when a Player types any invalid choice, the computer should not play it's turn and we get "Invalid choice. Play your turn again!" displayed, keeping the game running.
Please check my code and point me to the issue. Please explain with the correction. Thanks in advance!
print("Welcome to the famous Rock Paper Scissors Game. \n")
Choices = ["Rock", "Paper", "Scissors"]
while(True):
Player = input("Your turn: ")
Computer = random.choice(Choices)
print(f"Computer's turn: {Computer} \n")
if Player == Computer:
print("That's a tie, try again! \n")
elif Player == "Rock" and Computer == "Scissors":
print("You Won!!! \n")
elif Player == "Rock" and Computer == "Paper":
print("Computer won! \n")
elif Player == "Paper" and Computer == "Scissors":
print("Computer won! \n")
elif Player == "Paper" and Computer == "Rock":
print("You Won!!! \n")
elif Player == "Scissors" and Computer == "Paper":
print("You Won!!! \n")
elif Player == "Scissors" and Computer == "Rock":
print("Computer won! \n")
else:
print("Invalid choice. Play your turn again! \n")
You can check if the input is valid before the computer plays, and ask again if it is invalid using continue -
Choices = ["Rock", "Paper", "Scissors"]
while(True):
Player = input("Your turn: ")
if Player not in Choices: # If it is not in Choices list above
print("Invalid choice. Play your turn again! \n")
continue # This will re run the while loop again.
# If Player gives valid input, then continues this
Computer = random.choice(Choices)
print(f"Computer's turn: {Computer} \n")
# The next lines ....
Also check out - Break, Continue and Pass

I wrote a simple python game but functions in that are not executing

I am fairly new in python coding. I made a simple rock, paper, scissor game using random module. I wrote it in three functions. when I am executing it, I get no error but it is not executing the functions.
what I wrote:
import random
def main():
global comp
global user
global play
play = ''
#preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
#computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
#user inputs their choice
user = input("Rock, Paper or Scissor? ")
def user_choice():
global play
play = input("Do you want to continue? press y or n for yes and no respectively. ")
if play == y:
main()
elif play == n:
print("Thank you for playing!")
exit()
#conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
user_choice()
if __name__ == '__main__':
main()
play_game()
it is not executing play_game() and user_choice().
It only ask for the input.
The first thing which is wrong is that y and n are not under "" thus python is treating them as a variable. the second thing which was wrong is the position of the play game which should come below the main() to get executed. All user_choice() was not indented properly
Try this code
import random
def main():
global comp
global user
global play
play = ''
# preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
# computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
# user inputs their choice
user = input("Rock, Paper or Scissor? ")
def user_choice():
global play
play = input(
"Do you want to continue? press y or n for yes and no respectively. ")
if play == "y":
main()
elif play == "n":
print("Thank you for playing!")
exit()
# conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
user_choice()
if __name__ == '__main__':
main()
play_game()
Create another function main() and call play_game() and user_choice() within main.
The code calls the main() function and this takes an input, but it does not call any of the other functions.
This is why.
Expect that you mean to call play_game() and user_choice() from within main().
Working code.
import random
def main():
global comp
global user
global play
play = ''
#preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
#computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
#user inputs their choice
user = input("Rock, Paper or Scissor? ")
user_choice()
play_game()
def user_choice():
global play
play = input("Do you want to continue? press y or n for yes and no respectively. ")
if play == 'y':
main()
elif play == 'n':
print("Thank you for playing!")
exit()
#conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
if __name__ == '__main__':
main()

Rock, Paper And Scissors Program (Upper And Lower Case Problem)

I Was Practicing Programs Of Python And Then I Made This Rock, Paper, Scissors Program. And The Program Is Running Perfectly But The Problem Is Like This:
I Chose "Rock, Paper, Scissors" Like This Than It Runs.
But If I Enter Rock, Paper, Scissors In Any Other Way It Prints The Else Statment i.e., Invalid Choice.
I Want To Use Upper/Lower Case But How And Where.
import random
user = input("""Tell Me What Do You Choose:
~Rock
~Paper
~Scissors.
-> I Choose : """)
choose = ["Rock", "Paper", "Scissors"]
computer = random.choice(choose)
print(f"Computer Chose {computer}.")
#Function To Compare Choices
def compare(user, computer):
if user == computer:
return("It's A Tie :(....")
elif user == "Rock":
if computer == "Scissors":
return("User Wins!")
else:
return("Computer Wins!")
elif user == "Scissors":
if computer == "Paper":
return("User Wins!")
else:
return("Computer Wins!")
elif user == "Paper":
if computer == "Rock":
return("User Wins!")
else:
return("Computer Wins!")
else:
return("User Choose Out Of The Options!")
exit()
print(compare(user, computer))
just transform your input into lowercase with the lower() method
user = user.lower()
that makes sCiSsOrS into scissors
you also need to adjust your if statements to be all lowercase
elif user == "Rock": --> elif user == "rock":

Simplify Python code (Rock, Paper, Scissors)

I am a complete python newbie and this is my first question on stackoverflow, so please be patient with me :)
So to get some excersise, I tried programming my own rock, paper, scissors game in Python. However, my code is relatively long compared to other rock, paper, scissor programs. This is because I programmed every single possible option in the game. Is there a possibility to simplify this code? As in not having to programm every single possibiliy in the game? Because doing so might be possible in Rock, Paper, Scissors, but probably not in more advanced problems.
Let me know what you think, thank you!!!
All the best,
Luca Weissbeck
The code:
#Rock, Paper, Scissors
while True:
Game_list = ["Rock", "Paper", "Scissors"]
User_1 = str(input("Rock, Paper, Scissors?"))
#Let the computer make its choice
import random
Computer_1 = random.choice(Game_list)
#Possibility of a draw
if str(Computer_1) == User_1:
Draw_choice = str(input("It's a draw. Do you want to replay?(Y/N)"))
if Draw_choice == "Y":
continue
else:
break
#Possibility of player winning
if str(Computer_1) == "Rock" and User_1 == "Paper" or str(Computer_1) ==
"Paper" and User_1 == "Scissors" or str(Computer_1) == "Scissors" and User_1
== "Rock":
UW1 = str(input("You won. The computer chose:" + Computer_1 + " Do
you want to play again? (Y/N)"))
if UW1 == "Y":
continue
else:
break
#Possibility of computer winning
if str(Computer_1) == "Rock" and User_1 == "Scissors" or str(Computer_1)
== "Paper" and User_1 == "Rock" or str(Computer_1) == "Scissors" and User_1
== "Paper":
UL1 = str(input("You lost. The Compuer chose:" + Computer_1 + " Do
you want to play again? (Y/N)"))
if UL1 == "Y":
continue
else:
break
#End sentence
print("Bye, thank you for playing!")
There are a lot of repeated strings in this program. They can be collapsed.
import random
States = ['Rock','Paper','Scissors']
playAgain = True
while playAgain:
User = str(input("Choose your play: "))
try:
User = States.index(User)
except:
print('Your choice is not one of the choices in Rock, Paper, Scissors')
break
Comp = random.randint(0,2)
winner = (Comp-User)%3
if winner==0:
print("There is a tie. Both User and Computer chose " + States[User])
elif winner==1:
print("Computer wins. Computer chose "+States[Comp]+" and User chose "+States[User])
else:
print("User wins. Computer chose "+States[Comp]+" and User chose "+States[User])
if str(input("Do you want to play again? (Y/N)")) == "N":
playAgain = False
print("Thanks for playing!")
You can try to store the win possibilities.
win_case = [['rock','scissor'], ['scissor','paper'], ['paper','rock']]
Then the main program will be like
if (user == comp):
// draw
elif ([user,comp] in win_case):
// user win
else:
// comp win
Length of code is one thing. Organization and readability is another (more important) one. What often helps is a separation of code and config. Set constants, settings, messages first, then use them in the code:
import random
# game config
R, P, S = "Rock", "Paper", "Scissors"
BEATS = {R: S, P: R, S: P}
MESSAGES = {
"draw": "It's a draw. Play again? (Y/N)\n",
"win": "You won. Comp chose: {}. Play again? (Y/N)\n",
"loss": "You lost. Comp chose: {}. Play again? (Y/N)\n",
"invalid": "Invalid input: {}. Play again? (Y/N)\n",
}
# game code
play = "Y"
while play.upper() == "Y":
u1 = str(input("{}, {}, {}?\n".format(R, P, S)))
c1 = random.choice([R, P, S])
if u1 not in BEATS:
play = input(MESSAGES["invalid"].format(u1))
elif c1 == u1:
play = input(MESSAGES["draw"])
elif BEATS[u1] == c1:
play = input(MESSAGES["win"].format(c1))
else:
play = input(MESSAGES["loss"].format(c1))

Categories