I keep getting this error message that says expected an indent block.
The shell highlights the bold spot as the error. Any suggestions on how I fix it?
I am just a beginner so any and all help would be appreciated! Thank you in advance!
from random import *
s = choice( [ 'rock', 'paper', 'scissors' ])
def rps( ):
""" runs a game of Rock Paper Scissors between the program and the user by returning the user's choice and the program's choice and signaling a winner
input: the user's choice which is one of three responses in the game Rock-Paper- Scissors - all are a string of letters
"""
print ('rps( )')
print ('Welcome to a game of Rock Paper Scissors!')
print ('I just made my choice.')
print ('I promise no cheating this time!')
r = input('Now you choose rock, paper, or scissors!')
print
if r == 'paper':
print ('You chose paper.')
if s == 'scissors':
print ('I chose scissors. Haha, I win fair and square!')
elif s == 'rock':
print ("I chose rock. Maybe I'll have better luck next time...")
elif s == 'paper':
print ('We need a rematch!')
elif r == 'scissors':
print ('You chose scissors.')
if s == 'rock':
print ('I chose rock. Haha, I win fair and square!')
elif s == 'paper':
print ("I chose paper. Maybe I'll have better luck next time...")
elif s == 'scissors':
print ('We need a rematch!')
elif r =='rock':
print ('You chose rock.')
if s == 'paper':
print ('I chose paper. Haha, I win fair and square!')
elif s == 'scissors':
print ("I chose scissors. Maybe I'll have better luck next time...")
elif s == 'rock':
print ('We need a rematch!'
else:
print ("Don't you know the rules? Choose rock, paper or scissors!")
I think I fixed it!
from random import *
s = choice( [ 'rock', 'paper', 'scissors' ])
def rps( ):
""" runs a game of Rock Paper Scissors between the program and the user by returning the user's choice and the program's choice and signaling a winner
Technically this function has no inputs and no return value; the function is an interaction between the user and the program
"""
print ('Welcome to a game of Rock Paper Scissors!')
print ('I just made my choice.')
print ('I promise no cheating this time!')
r = input('Now you choose rock, paper, or scissors!')
if r == 'paper':
print ('You chose paper.')
if s == 'scissors':
print ('I chose scissors. Haha, I win fair and square!')
elif s == 'rock':
print ("I chose rock. Maybe I'll have better luck next time...")
elif s == 'paper':
print ('We need a rematch!')
elif r == 'scissors':
print ('You chose scissors.')
if s == 'rock':
print ('I chose rock. Haha, I win fair and square!')
elif s == 'paper':
print ("I chose paper. Maybe I'll have better luck next time...")
elif s == 'scissors':
print ('We need a rematch!')
elif r =='rock':
print ('You chose rock.')
if s == 'paper':
print ('I chose paper. Haha, I win fair and square!')
elif s == 'scissors':
print ("I chose scissors. Maybe I'll have better luck next time...")
elif s == 'rock':
print ('We need a rematch!')
else:
print ("Don't you know the rules? Choose rock, paper or scissors!")
Ok... all of this is really confused.
First of all, there is nothing inside the function rps() except for a comment. This is how you define a function:
def hi_im_a_function():
hi im inside the function
hi, im not inside the function.
hi_im_a_function()
^calling the function
In fact, that whole function appears to be obsolete. I don't know what you were trying to accomplish with that print('rps()') thing, but it isn't doing anything. I suggest you drop it.
The error is coming from that random floating print on the line right before the error. The error is landing on the if r == paper line because that is where the compiler first feels the effects of the error you set in the line before it.
As before, I don't know what you were trying to do there, but that statement has no purpose there. Delete it.
Fix those errors, and it should work like a charm.
Related
I am trying to create a rock, paper, scissors game in PyCharm using Python 3.6.3 but it will not return any output upon execution and I have not received any code errors in my IDE.
import random
class RPS:
rock = 1
paper = 2
scissors = 3
def __init__(self, choice):
self.choice = choice
def play(self):
print("Enter: \n1 for Rock, \n2 for Paper, \nor 3 for Scissors")
choice = int(input("Enter in a number between 1 and 3: "))
while (choice != 1 or choice != 2 or choice != 3):
print("You have selected an invalid choice!")
print("Enter: \n1 for Rock, \n2 for Paper, \nor 3 for Scissors")
choice = int(input("Enter in a number between 1 and 3: "))
print("You have selected", choice)
computer = random.randint(1, 3)
if computer == 1:
print("The computer chose rock")
if computer == 2:
print("The computer chose paper")
if computer == 3:
print("The computer chose scissors")
if choice > computer:
print("You win!")
elif choice < computer:
print("You lose!")
elif choice == computer:
print("It is a tie!")
play_again = input('Do you want to play again[yes/no]? ')
if play_again.lower() == 'yes':
self.play()
if play_again.lower() == 'no':
print("Thanks for playing! \nBYE!")
as jasonharper said, you aren't instancing the class and running it's play method.
to do that, add to the bottom of the file:
game = RPS()
game.play()
There are some other issues too, but I'll let you try to solve those yourself.
I am making a rock, paper, scissors game for a programming class. This is where I got and then PowerShell spits out that error. I don't understand what is wrong (I am a beginning Python programmer). My programming teacher is not much help and prefers the "Figure it out" approach to learning. I am genuinely stuck at this point. Any help is appreciated, thank you!
import random
def rps():
computer_choice = random.randint(1,3)
if computer_choice == 1:
comuter_choice_rock()
elif computer_choice == 2:
comuter_choice_paper()
else:
comuter_choice_scissors()
def computer_choice_rock():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("It's a Tie!")
try_again()
if user_choice == "2":
print ("You Win! Paper covers Rock!")
try_again()
if user_choice == "3":
print ("I Win and You Lose! Rock crushes Scissors!")
try_again()
else:
print ("Please type in 1, 2, or 3")
computer_choice_rock()
def computer_choice_paper():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("I Win and You Lose! Paper covers Rock!")
try_again()
if user_choice == "2":
print ("It's a Tie!")
try_again()
if user_choice == "3":
print ("You Win! Scissors cut Paper!")
try_again()
else:
print ("Please type in 1, 2, or 3")
computer_choice_paper()
def computer_choice_paper():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == ("1"):
print ("You Win! Rock crushes Scissors")
try_again()
if user_choice == "2":
print ("I Win! Scissors cut Paper!")
try_again()
if user_choice == "3":
print ("It's a Tie!")
try_again()
else:
print ("Please type in 1, 2, or 3")
computer_choice_paper()
def try_again():
choice = input("Would you like to play again? Y/N: ")
if choice == "Y" or choice == "y" or choice == "Yes" or choice == "yes":
rps()
elif choice == "n" or choice == "N" or choice == "No" or choice == "no":
print ("Thanks for Playing!")
quit()
else:
print ("Please type Y or N")
try_again()
rps()
You have a typo in you code
if computer_choice == 1:
comuter_choice_rock()
elif computer_choice == 2:
comuter_choice_paper()
else:
comuter_choice_scissors()
Comuter
Your code can be simplified to an extreme degree. See the following example program. To replace either of the players with a NPC, set player_1 or player_2 with random.choice(priority). If you want to, you could even have the computer play against itself.
priority = dict(rock='scissors', paper='rock', scissors='paper')
player_1 = input('Player 1? ')
player_2 = input('Player 2? ')
if player_1 not in priority or player_2 not in priority:
print('This is not a valid object selection.')
elif player_1 == player_2:
print('Tie.')
elif priority[player_1] == player_2:
print('Player 1 wins.')
else:
print('Player 2 wins.')
You could also adjust your game so people can play RPSSL instead. The code is only slightly different but shows how to implement the slightly more complicated game. Computer play can be implemented in the same way as mentioned for the previous example.
priority = dict(scissors={'paper', 'lizard'},
paper={'rock', 'spock'},
rock={'lizard', 'scissors'},
lizard={'spock', 'paper'},
spock={'scissors', 'rock'})
player_1 = input('Player 1? ')
player_2 = input('Player 2? ')
if player_1 not in priority or player_2 not in priority:
print('This is not a valid object selection.')
elif player_1 == player_2:
print('Tie.')
elif player_2 in priority[player_1]:
print('Player 1 wins.')
else:
print('Player 2 wins.')
I'm practicing conditionals and logical operators.
How do I make the following rock, paper, scissors game print "This is not a valid object selection." immediately after Player 1's input, if Player 1 enters an invalid object? Right now the string is not printed until both players have entered an object.
Also, any suggestions for making the following code more elegant?
player1 = input('Player 1? ')
player2 = input('Player 2? ')
if (player1.lower() == 'rock' and
player2.lower() == 'rock'):
print('Tie.')
elif (player1.lower() == 'rock' and
player2.lower() == 'paper'):
print('Player 2 wins.')
elif (player1.lower() == 'rock' and
player2.lower() == 'scissors'):
print('Player 1 wins.')
elif (player1.lower() == 'paper' and
player2.lower() == 'paper'):
print('Tie.')
elif (player1.lower() == 'paper' and
player2.lower() == 'scissors'):
print('Player 2 wins.')
elif (player1.lower() == 'paper' and
player2.lower() == 'rock'):
print('Player 1 wins.')
elif (player1.lower() == 'scissors' and
player2.lower() == 'scissors'):
print('Tie.')
elif (player1.lower() == 'scissors' and
player2.lower() == 'rock'):
print('Player 2 wins.')
elif (player1.lower() == 'scissors' and
player2.lower() == 'paper'):
print('Player 1 wins.')
else:
print('This is not a valid object selection.')
How about a function to ask each player their choice? Only if the player enters a valid selection will they be allowed to proceed through the code to your logic statements.
def get_choice(Player_number):
print('Player', Player_number, 'please enter your choice: ', end='')
while True:
choice = input().lower() #lower converts input to all lowercase
if choice in ('rock', 'paper', 'scissors'): # check if valid choice
return choice # if valid return choice
else:
print('Incorrect choice, try again: ', end='') # else print this and start loop agan
player1 = get_choice('1')
player2 = get_choice('2')
For the logic part, note that if player1 choice == player 2 choice, this will substitute 3 elif blocks in your code, ie.
if player1 == player2:
print('tie')
Now replaces pl==rock and p2 == rock, p1 == scissors and p2 == scissors, ect.
edit:
1) The problem if you move the print statement in 2 to inside the input in 4 is you can no longer specify the ,end='' parameter, as it does not work with input. As you said it will generate SyntaxError. The code looks much cleaner when run this way in terminal as it all lines up, but do test it for yourself.
2) end='' prints an empty string at the end of the print statement. you are confusing this with end='\n' which prints a new line after print. As my way keeps the cursor on the same line after the print, it lines up with the input to make it look nice, see above question. Note the print statement in python by default passes , end='\n'. This is why
print('hello') #same as print('hello', end='\n')
print('world)
hello
world
print('hello', end='')
print('world', end='')
helloworld
3) The while True loop will alway evaluate to true. So the body of the while loop will constantly cycle - However, it can return out of the entire function with the 'return choice' function. The only way to leave this function if to get down the logical steps required to reach the return statement. In this case unless the choice is in that tuple('rock', 'paper', 'scisors') it will just print invalid entry try again, finishing the block. However, As while is still true the loop will begin again and ask the user to input again. This will repeat until a valid choice is selected.
4) You could concatenate it onto the player_number eg..
print('Player', Player_number + ',' , 'please enter your choice: ', end='')
Writing a little RPS game and I ran into a problem.
1) When I run the function to play the game, it always returns as a "Tie"
even if I choose a losing variable ex. cpu = rock, player = scissors
I'm kind of stumped on this. I usually lurk the stackoverflow forum when I'm having troubles, but I haven't encountered someone that has the same problem (even with the plethora of RPS questions on here).
Now, I'm not asking for anybody to write and test it 100% for me, but rather just show me the error spot and I'll go troubleshoot.
Thanks!
def showRules():
print("********** Rock, Paper, Scissors **********")
print("Rules: Each player chooses either Rock, Paper, or Scissors.")
print(" The winner is determined by the following rules:")
print(" Scissors cuts Paper -> Scissors wins")
print(" Paper covers Rock -> Paper Wins")
print(" Rock smashes Scissors -> Rock Wins")
print("*******************************************")
def getCPUChoice():
choices = ["rock", "paper", "scissors"]
from random import randint
randNum = randint(0,2)
cpuchoice = choices[randNum]
print(cpuchoice)
return
def getUserChoice():
choices = ["rock", "paper", "scissors"]
userchoice = input('Please choose either rock, paper or scissors:').lower()
print(userchoice)
return
def declareWinner(user, computer):
if user == computer:
print("Tie!!")
elif user == "rock" and computer == "paper":
print("You lose!")
elif user == "paper" and computer == "scissors":
print("You lose!")
elif user == "scissors" and computer == "rock":
print("You lose!")
def playGame():
showRules()
computer = getCPUChoice()
user = getUserChoice()
declareWinner(user, computer)
In getCPUChoice and getUserChoice, you are printing the choices instead of returning them. Change the returns at the end of those functions to
return cpuchoice
and
return userchoice
respectively.
I am using Python and I am trying to write a simple program that simulates a rock, paper, scissors game. Everything works except for when I enter an invalid response (something other than rock, paper, or scissors) when I get this error.
Traceback (most recent call last):
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 88, in <module>
main()
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 14, in main
number = user_guess()
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 48, in user_guess
return number
UnboundLocalError: local variable 'number' referenced before assignment
I understand that this is telling me that number isn't referenced, but from what I understand of the code, it shouldn't need a number when the qualifier is false.
#import random module
import random
#main function
def main():
#intro message
print("Let's play 'Rock, Paper, Scissors'!")
#call the user's guess function
number = user_guess()
#call the computer's number function
num = computer_number()
#call the results function
results(num, number)
#computer_number function
def computer_number():
#get a random number in the range of 1 through 3
num = random.randrange(1,4)
#if/elif statement
if num == 1:
print("Computer chooses rock")
elif num == 2:
print("Computer chooses paper")
elif num == 3:
print("Computer chooses scissors")
#return the number
return num
#user_guess function
def user_guess():
#get the user's guess
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
#while guess == 'paper' or guess == 'rock' or guess == 'scissors':
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
user_guess()
def is_valid_guess(guess):
if guess == 'rock' or 'paper' or 'scissors':
status = True
else:
status = False
return status
def restart():
answer = input("Would you like to play again? Enter 'y' for yes or \
'n' for no: ")
#if/elif statement
if answer == 'y':
main()
elif answer == 'n':
print("Goodbye!")
else:
print("Please enter only 'y' or 'n'!")
#call restart
restart()
#results function
def results(num, number):
#find the difference in the two numbers
difference = num - number
#if/elif statement
if difference == 0:
print("TIE!")
#call restart
restart()
elif difference % 3 == 1:
print("I'm sorry! You lost :(")
#call restart
restart()
elif difference % 3 == 2:
print("Congratulations! You won :)")
#call restart
restart()
main()
Thank you for your help!
Here's your problem:
if guess == 'rock' or 'paper' or 'scissors':
This line in is_valid_guess doesn't do what you think it does. Instead, it always returns True. What you're looking for is something like this:
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
or more concisely:
if guess in ('rock', 'paper', 'scissors'):
The problem is that what you have always returns True because of how Python evaluates strings in a boolean context. The line if guess == 'rock' or 'paper' or 'scissors': evaluates as:
if (guess == 'rock') or ('paper') or ('scissors'):
What this means is that Python checks to see if guess == 'rock'. If that's true, the conditional evaluates to True. If it's false, the interpreter tries to evaluate bool('paper'). This always evaluates to True because all non-empty strings are "truthy". Therefore, your whole conditional is always True, and every string is "valid".
As a result, your code considers all strings "valid" and then blows up when it fails to assign a number to a guess that is not actually supported.
As a final note, your is_valid_guess method could be trimmed a bit, since you're just returning the result of your boolean expression. Rather than using the status variable as an intermediate, you can just compute the expression and return it right away. I also use the lower() method of string objects to allow for case-insensitive guessing, in case that's something you want to allow.
def is_valid_guess(guess):
return guess.lower() in ('rock', 'paper', 'scissors')
You've got another issue, which you mentioned in the comments: you've implemented user_guess in a recursive fashion, so that it calls itself if the user enters an invalid guess. However, in this case, it does not return the result of the recursive call. You need to either return the recursive result by changing the last line of user_guess to:
return user_guess()
Or else you should make that function use a loop instead of recursion, which is what I would do, since the function is not inherently recursive. You can do something like this:
def user_guess():
# get first guess
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
# If that guess is invalid, loop until we get a valid guess.
while not is_valid_guess(guess):
print('That response is invalid.')
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
# Now assign the (valid!) guess a number
# This dictionary is just shorthand for your if/elif chain.
guess_table = {
'rock' : 1,
'paper' : 2,
'scissors' : 3
}
# Return the number associated with the guess.
return guess_table[guess.lower()]
Change
if guess == 'rock' or 'paper' or 'scissors':
to
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
In fact, to make the function as streamlined as possible, just do this:
def is_valid_guess(guess):
return guess == 'rock' or guess == 'paper' or guess == 'scissors'
As other users have pointed out, you need to change your validation in is_valid_guess to:
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
While this won't solve your immediate problem, it is good (upvote-worthy) advice, and will let you avoid some errors you would have run into.
Additionally, no matter what the user inputs, you always return what they type in. To prevent this, you must return user_guess() in your else block:
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
return user_guess() # <-- right here
Just change input to raw_input