python函数输出无

时间:2018-12-28 22:14:57

标签: python python-3.x

import random
def getAnswer (answerNumber):
    if getAnswer == 1:
        return 'It is certain'
    elif getAnswer == 2:
        return 'It is decidedly so'  
    elif getAnswer == 3:
        return 'Yes' 
    elif getAnswer == 4:
        return "Reply hazy try again"
    elif getAnswer == 5:
        return 'Ask again later'
    elif getAnswer == 6:
        return "Concentrate and ask again"
    elif getAnswer == 7:
        return 'My reply is no'
    elif getAnswer == 8:
        return 'not so good'
    elif getAnswer == 9:
        return 'doubtful'

r = random.randint(1 , 9)
future = getAnswer(r)
print(future)

2 个答案:

答案 0 :(得分:6)

您将随机数作为answerNumber传递,然后检查getAnswer的值。因此,该函数正在尝试将对具有整数的函数的引用进行比较,该整数显然不会求值为True。因为没有if语句的求值结果为True,所以它到达函数的末尾而没有命中return语句,因此默认情况下返回None

getAnswer替换函数主体中的所有answerNumber引用,您应该已经全部设置好。像这样:

import random
def getAnswer(answerNumber):
    if answerNumber == 1:
        return 'It is certain'
    elif answerNumber == 2:
        return 'It is decidedly so'  
    elif answerNumber == 3:
        return 'Yes' 
    elif answerNumber == 4:
        return "Reply hazy try again"
    elif answerNumber == 5:
        return 'Ask again later'
    elif answerNumber == 6:
        return "Concentrate and ask again"
    elif answerNumber == 7:
        return 'My reply is no'
    elif answerNumber == 8:
        return 'not so good'
    elif answerNumber == 9:
        return 'doubtful'

r = random.randint(1 , 9)
future = getAnswer(r)
print(future)

答案 1 :(得分:1)

import random
def getAnswer (answerNumber):
    if answerNumber == 1:
        return 'It is certain'
    elif answerNumber == 2:
        return 'It is decidedly so'  
    elif answerNumber == 3:
        return 'Yes' 
    elif answerNumber == 4:
        return "Reply hazy try again"
    elif answerNumber == 5:
        return 'Ask again later'
    elif answerNumber == 6:
        return "Concentrate and ask again"
    elif answerNumber == 7:
        return 'My reply is no'
    elif answerNumber == 8:
        return 'not so good'
    elif answerNumber == 9:
        return 'doubtful'

r = random.randint(1 , 9)
future = getAnswer(r)
print(future)

您正在将函数getAnswer与整数值进行比较,并且由于那里没有定义else语句,因此函数调用返回None

我所做的只是将实际数字answerNumber与代码中的数字进行比较。