首页 > 解决方案 > 在 Python 3 中定义函数:返回 None 值

问题描述

我编写了一个函数,旨在根据用户自己输入的日期和时间告诉您用户依赖于哪个成本段。

一切似乎都很好,但我不太明白为什么函数在正确和预期的输出之后返回 None 输出。

请在下面查看我的代码:

day = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
hour = list(range(0, 24))
segments = {'Cheap': hour[:8], 'Intermediate': hour[8:10] + hour[14:18] + hour[22:], 'Costly': hour[10:14] + hour[18:22]} 
dayEvaluate = "z"
hourEvaluate = 25
#Let's define the function:
def power_price_calculator(dayEvaluate, hourEvaluate):
    while (dayEvaluate not in day): 
        dayEvaluate = input('Enter the day you want to check: ')
        if dayEvaluate not in day:
            print('Please, enter a valid day name (Monday-Sunday)')
    if dayEvaluate in day[:4]:
        while (hourEvaluate not in hour):
            hourEvaluate = int(input('Enter the hour you want to check: '))
            if((hourEvaluate > 24) or (hourEvaluate < 0)): 
                print('Please, enter a valid hour (0-24h)')
            if hourEvaluate in segments['Cheap']:
                print('Congratulations! You are in the cheap segment')
            elif hourEvaluate in segments['Intermediate']: 
                print('It is OK, you are in the intermediate segment')
            elif hourEvaluate in segments ['Costly']: 
                print('Beware of your consumption, you are in the costly segment')
    else: 
        print('Congratulations! You are in the cheap segment')

        
print(power_price_calculator(dayEvaluate, hourEvaluate))

任何人都可以对此有所了解吗?

非常感谢!

标签: pythonfunction

解决方案


像这样拆分您的问题:

result = power_price_calculator(dayEvaluate, hourEvaluate) # result is None
print(result) # Does not print anything

这是因为你的函数只打印数据,它不返回任何东西


推荐阅读