这个简短的用户定义函数有什么问题?

时间:2019-10-18 23:11:56

标签: python function user-defined-functions

它说“工资”没有定义,或者我不能乘以。 我想用def命令来使用它,所以请以这种形式来纠正错误,这是全新的,所以就让它尽可能地简单。非常感谢:)

def computepay(Hours,RatePerHour):
    if float(Hours)-40<0:
        salary=float(Hours)*float(RatePerHour)
    else:
        salary=40.0*float(RatePerHour)+(float(Hours)-40.0)*float(RatePerHour*1.5)

Hours=input("Hours:\n")
RatePerHour=input("RatePerHour:\n")
computepay(Hours,RatePerHour)
print("Salary:")
print(salary)

我希望有人可以帮助我这个小程序如何正常工作

3 个答案:

答案 0 :(得分:2)

您需要return salary,然后将其分配给变量。这是您代码的改进版本:

def compute_pay(hours: float, rate_per_hour: float) -> float:
    if hours - 40 < 0:
        salary = hours * rate_per_hour
    else:
        salary = 40 * rate_per_hour + (hours - 40.0)* rate_per_hour * 1.5
    return salary  # This is the line you are missing!

hours = input("Hours:\n")
rate_per_hour=input("RatePerHour:\n")
computer_salary = computepay(float(hours), float(rate_per_hour))  # You also need to assign the output of a function to a variable, I've given it a different name from salary just to show you that this is a different variable from the one inside your function. Also, cast to float here so you don't have to do it all over your function. 
print(f"Salary: {computer_salary}")

您需要在此处学习的概念称为scope

答案 1 :(得分:0)

您需要返回计算出的薪水。

此外,如果对输入执行浮点转换,则更为简单。

def computepay(Hours,RatePerHour):
    if float(Hours)-40<0:
        salary=Hours*RatePerHour
    else:
        salary=40.0*RatePerHour+ (Hours-40.0)*(RatePerHour*1.5)
    return salary  # return value

Hours = float(input("Hours:\n"))  # float conversion
RatePerHour = float(input("RatePerHour:\n"))  # float conversion
salary = computepay(Hours,RatePerHour)
print("Salary:")
print(salary)

答案 2 :(得分:0)

这是更正,下面有一些解释。

def computepay(Hours,RatePerHour): 
    salary = 0
    if float(Hours)-40<0:    
        salary=float(Hours)*float(RatePerHour) 
    else: 
        salary=40.0*float(RatePerHour)+(float(Hours)-40.0)*float(RatePerHour) *1.5) #<=== here you multiply with out turning rateperhour as float
    return salary 

Hours=input("Hours:\n") RatePerHour=input("RatePerHour:\n") 
salary = computepay(Hours,RatePerHour) 
print("Salary:") 
print(salary)

首先,薪金是函数内部的一个变量,在函数外部不是可用的。

第二,由于将字符串乘以整数,因此会出现错误。将其转换为之前浮动的。

float(RatePerHour*1.5) #wrong
float(RatePerHour) *1.5 # correct