【发布时间】: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