【问题标题】:Python function returns None. Don't quite understand whyPython 函数返回无。不太明白为什么
【发布时间】:2023-03-15 16:05:01
【问题描述】:
import random

def diceroll():
    x = random.randrange(1, 6)
    print(x)
    repeatroll()

def repeatRoll():
    roll = input(print("Would you like to roll again?"))

    if roll.upper()=="Y":
        return diceroll()
    elif roll.upper()=="N":
        return print("You have chosen not to roll again")
    else:
        return print("Invalid input")

    return roll



repeatRoll()

谁能向我解释为什么在代码要求输入后返回 None ?

一直以为是没有返回函数的原因。

我完全糊涂了,我觉得答案很明显,但我不太明白。

我们将不胜感激,谢谢。

【问题讨论】:

  • diceroll 不返回任何内容。应该是return xreturn repeatroll()
  • 另外,print 返回None。您无需调用 print 即可返回值。
  • 那么输出中出现“None”的原因是因为我对“roll”变量使用了打印语句?
  • 这能回答你的问题吗? Why does my recursive function return None?

标签: python python-3.x function nonetype


【解决方案1】:

print() 总是返回 None

它不返回任何值;返回无。

由于您在 input() 中调用了 print()。print() 不返回任何内容,因此 input() 将其作为输入

使用:

print("Would you like to roll again?")
roll = input()

【讨论】:

  • 啊,我明白了!谢谢!
【解决方案2】:

您的代码需要稍作修改:

试试这个sn-p

在 diceroll() 中调用 repeatRoll() 将不起作用,因为它不在同一范围内。而且你的输入格式也无效

import random

def repeatRoll():
    roll='Y'
    while(roll=='Y'):
        print("Would you like to roll again?")
        roll = input()
        if roll.upper()=="Y":
            diceroll()
        elif roll.upper()=="N":
            return print("You have chosen not to roll again")
        else:
            return print("Invalid input")


def diceroll():
    x = random.randrange(1, 6)
    print(x)


repeatRoll()

希望对你有帮助:")

【讨论】:

    【解决方案3】:

    这可能是因为 print 语句在 python 中没有返回任何内容,或者只是说 print 语句具有 None 类型作为返回。

    【讨论】:

    • 我明白了。那我的方法应该是什么?由于使用 print 语句的 'roll' 变量,似乎出现了 'None'?
    • 可以使用输入语句为roll = input("Would you like to roll again")
    猜你喜欢
    • 2015-09-12
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多