简体   繁体   中英

Python function returns None. Don't quite understand why

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

Can anyone explain to me why this returns None after the code asks for an input?

I always thought that it would be due to not having a return function.

I'm completely confused, I feel like the answer is obvious but i'm not quite getting it.

Help would be appreciated, thank you.

print() always return None

It doesn't return any value; returns None.

Since you called print() inside input().The print() returns none which is take as input by input()

Use:

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

Your code required small modifications:

Try using this snippet

Calling repeatRoll() inside diceroll() wont work because it is not in the same scope. And your inputting format was also invalid

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

Hope it helps:")

It can be because print statements do not return anything in python or simply saying print statements have a None type as return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM