Matt
Matt

Reputation: 1

Python code not returning expected result

I was wondering if any of you could look at my code and tell me what I am missing here. Basically, it takes user input for their names (playerOne and playerTwo). It is supposed to pick the larger number from the random choice and display that user's name as the winner. It is displaying the random numbers chosen, but not the winner's name.

#Add libraries needed
import random

#The main function
def main():
    print
    #Initialize variables
    endProgram = 'no'
    playerOne = 'NO NAME'
    playerTwo = 'NO NAME'


    #Call to inputNames
    playerOne, playerTwo = inputNames(playerOne, playerTwo)

    #While loop to run program again
    while endProgram == "no":
        winnerName ='NO NAME'
        p1number = 0
        p2number = 0

        #Initialize variables

        #Call to rollDice
        winnerName = rollDice(p1number, p2number, playerOne, playerTwo,   winnerName)

        #Call to displayInfo
        displayInfo(winnerName)

        endProgram = raw_input('Do you want to end the program? (Enter yes or no): ')

#This function gets the players names
def inputNames(playerOne, playerTwo):
    playerOne = raw_input('Enter P1 name: ')
    playerTwo = raw_input('Enter P2 name: ')
    return playerOne, playerTwo

#This function will get the random values
def rollDice(p1number, p2number, playerOne, playerTwo, winnerName):
    p1number = random.randint(1,6)
    p2number = random.randint(1,6)
    return p1number, p2number
    if p1number == p2number:
        winnerName = "TIE"
    elif p1number > p2number:
        winnerName = playerOne
    elif p2number > p1number:
        winnerName = playerTwo
        return winnerName

#This function displays the winner
def displayInfo(winnerName):
    print winnerName

#Calls main
main()

Upvotes: 0

Views: 87

Answers (1)

idjaw
idjaw

Reputation: 26600

The reason this is happening is because you have a return statement before you run any of your logic to check the winner in your rollDice method.

Furthermore, you are then only going to be returning inside the last elif statement only if p2number > p1number. So, you should move the return statement outside of the condition so you always return a winner.

I commented and adjusted the code to indicate what should happen in your code for the rolLDice method:

#This function will get the random values
def rollDice(p1number, p2number, playerOne, playerTwo, winnerName):
    p1number = random.randint(1,6)
    p2number = random.randint(1,6)

    # You are returning too early here. Remove this return statement
    return p1number, p2number

    # CODE BELOW WILL NEVER RUN
    if p1number == p2number:
        winnerName = "TIE"
    elif p1number > p2number:
        winnerName = playerOne
    elif p2number > p1number:
        winnerName = playerTwo
    return winnerName

Simply remove that return statement, and your output will show the player name as expected.

Upvotes: 1

Related Questions