Home > Software design >  What is the difference between calling a function and printing a function?
What is the difference between calling a function and printing a function?

Time:12-09

In this simple project I tried to create a simple rock, paper, sccissors program.

import random
def play():
    user = input(f"'r' for rock, 'p' paper, 's' for scissors: ")
    computer = random.choice(['r', 'p', 's'])
    if user == computer:
        return 'It\'s a tie'
    #r > s, s > p, p > r
    if is_win(user, computer):
        return 'you won!'
    return 'You lost!'

def is_win(player, opponent):
# return true if player wins
# r>s, s>p, p>r
    if (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') \
        or (player == 'p' and opponent == 'r'):
        return True

Now if I want to play rock, paper, scissors against the computer I obviously need to call the function:

#1
play() #The issue I am having is, if I call this function that way, the program doesnt run
#2
print(play()) # Only if I add an print statement, then I can play rock, paper, scissors against the computer

Why do I have to use a print statement and cannot just call the function, like in example #1

CodePudding user response:

The reason you need to use a print statement in order to see the output of the play function is because the play function itself doesn't actually produce any output. When you call a function in Python, it will execute the code inside the function, but it won't automatically print anything unless you explicitly tell it to do so.

In this case, the play function returns a string containing the result of the game (e.g. "It's a tie", "You won!", "You lost!"), but it doesn't actually print anything to the screen. To see the result of the game, you need to print the return value of the play function by using a print statement, as shown in your second example. Here's an example of how you might use the print statement to see the result of the game:

# call the play function to play a game of rock, paper, scissors
result = play()

# print the result of the game
print(result)

In this example, the play function is called and the return value is stored in a variable called result. Then, the result variable is passed to the print function, which prints the result of the game to the screen. This allows you to see the result of the game without modifying the play function itself.

CodePudding user response:

The play() here is working as expected and it still runs and gives the output. print(play()) just prints what the function did. Both are doing what they are supposed to do.

  • Related