首页 > 解决方案 > Python:要求打印时不输出

问题描述

尝试从它们各自的函数中获取变量 compHand 和 playerHand 并在主函数中打印它们。输出无而不是选择的选项

def GetCompHand():

    compHand= random.randint(1,3)
    if compHand==1:
        compHand="r"

    elif compHand==2:
        compHand="p"

    elif compHand==3:
        compHand="s"




def GetPlayerHand():

    playerHand= input("Enter r, p, or s:")
    if playerHand.lower() == "r":
       print("You picked rock")
    elif playerHand.lower()=="p":
       print("You picked paper")
    elif playerHand.lower()=="s":
       print("You picked scissors")
    else:
       print("Please enter ONLY r, p, or s")
       return GetPlayerHand()


def main():
    pWins = 0
    cWins = 0
    ties = 0



    compHand=GetCompHand()
    playerHand=GetPlayerHand()

    print(compHand)
    print(playerHand)




main()

我的问题是为什么它没有输出两次而不是 r、p 或 s 用于任何一个函数。

标签: python

解决方案


你的两个函数都没有'return'语句,除了你递归回同一个函数的一种情况(你真的应该尽量不要这样做,顺便说一句)。所以你的函数返回 None 因为如果你没有明确告诉它返回某些东西,它们就是定义要做的。

看起来你想添加:

return compHand

在你的第一个函数的底部,和

return playerHand

在第二个的底部

哦...欢迎来到 StackOverflow!


推荐阅读