Femnar Femnar - 2 months ago 6
Python Question

Elif statements not printing

I'm doing a basic rock paper scissors code for school, but my elif statements aren't running.

def player1(x):
while x != 'rock' and x != 'paper' and x != 'scissors':
print("This is not a valid object selection")
x = input("Player 1? ")

def player2(x):
while x != 'rock' and x != 'paper' and x != 'scissors':
print("This is not a valid object selection")
x = input("Player 2? ")

def winner():
player1(input("Player 1? "))
player2(input("Player 2? "))
if player1 == 'rock' and player2 == 'rock':
print('Tie')
elif player1 == 'paper' and player2 == 'paper':
print('Tie')
elif player1 == 'rock' and player2 == 'paper':
print('Player 2 wins')
elif player1 == 'paper' and player2 == 'rock':
print('Player 1 wins')
elif player1 == 'rock' and player2 == 'scissors':
print('Player 1 wins')
elif player1 == 'scissors' and player2 == 'rock':
print('Player 2 wins')
elif player1 == 'paper' and player2 == 'scissors':
print('Player 2 wins')
elif player1 == 'scissors' and player2 == 'paper':
print('Player 1 wins')
elif player1 == 'scissors' and player2 == 'scissors':
print('Tie')

winner()


When I run this code, it asks for 'Player 1?' and won't accept anything other than rock, paper, or scissors. It then proceeds to do the same for player2. However, this is where the code ends, and it will not run my elif statements and print which player wins.

Edit: Solved. Thanks for helping a beginner. I was completely forgetting to return the strings and assign them to variables.

Answer

Your comparisons:

elif player1 == "rock" and player2 == "rock":
# etc

will always fail, since both player1 and player2 are functions.

Instead, you need to return from your functions and assign those to variables. Let's cut out the validation for a minute and reduce this a little.

def choose(prompt):
    return input(prompt)

def winner(a, b):
    if a == 'rock':
        if b == 'rock': return None
        elif b == 'paper': return 2
        elif b == 'scissors': return 1
    elif a == 'paper':
        # etc

def play_game():
    p1_choice = choose("Player 1: ")
    p2_choice = choose("Player 2: ")
    return winner(p1_choice, p2_choice)

Note that a nicer-looking trick for these chains of elifs is to put them in a dictionary and index the dictionary instead.

RESULT_DICT = {"rock": {"rock": None,
                        "paper": 2,
                        "scissors": 1},
               "paper": {"rock": 1,
                         "paper": None,
                         "scissors": 2},
               "scissors": {"rock": 2,
                            "paper": 1,
                            "scissors": None}}

def winner(a, b):
    return RESULT_DICT[a][b]