Python:请求prin时输出none

2024-10-03 17:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

我的问题是,为什么它会两次输出none,而不是r、p或s


Tags: or函数youifmaindef选项lower
2条回答

代码中有一些错误:

  1. 函数中没有实际返回函数值的return语句
  2. 您有main函数的定义,但它不是从任何地方调用的

    if __name__== "__main__":
        main()
    
  3. 您还需要导入random来使用它

下面是代码的修改版本,现在可以完美地工作了:

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

    elif compHand==2:
        compHand="p"

    elif compHand==3:
        compHand="s"
    return compHand




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

def main():
    compHand=GetCompHand()
    playerHand=GetPlayerHand()
    print(compHand)
    print(playerHand)

if __name__== "__main__":
    main()

如果你什么都不懂就告诉我。我很乐意帮助你。谢谢

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

似乎要添加:

return compHand

在第一个函数的底部

return playerHand

在第二个底部

哦…欢迎来到StackOverflow

相关问题 更多 >