【问题标题】:What is the difference between calling a function and printing a function?调用函数和打印函数有什么区别?
【发布时间】:2022-12-11 06:55:09
【问题描述】:

在这个简单的项目中,我尝试创建一个简单的剪刀石头布程序。

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

现在如果我想和电脑玩剪刀石头布,我显然需要调用函数:

#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

为什么我必须使用 print 语句而不能像示例 #1 那样只调用函数

【问题讨论】:

  • 您使用 print 语句是因为 play 函数返回一个字符串。要查看输出,您需要打印语句。但是,您可以将 print 语句移动到函数中,并消除 print(play()) 的需要

标签: python python-3.x function printing


【解决方案1】:

之所以需要使用 print 语句来查看 play 函数的输出,是因为 play 函数本身实际上并不产生任何输出。当你在 Python 中调用一个函数时,它会执行函数内部的代码,但它不会自动打印任何东西,除非你明确告诉它这样做。

在这种情况下,play 函数返回一个包含游戏结果的字符串(例如“It's a tie”、“You won!”、“You lost!”),但它实际上不会在屏幕上打印任何内容。要查看游戏结果,您需要使用 print 语句打印 play 函数的返回值,如第二个示例所示。 以下是您如何使用 print 语句查看游戏结果的示例:

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

# print the result of the game
print(result)

在此示例中,调用了 play 函数并将返回值存储在名为 result 的变量中。然后,result 变量被传递给 print 函数,它将游戏结果打印到屏幕上。这允许您在不修改 play 函数本身的情况下查看游戏结果。

【讨论】:

    【解决方案2】:

    play() 在这里按预期工作,它仍然运行并提供输出。 print(play()) 只打印函数做了什么。 双方都在做他们应该做的事情。

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 1970-01-01
      • 2013-03-30
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多