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

2024-10-01 09:37:31 发布

您现在位置:Python中文网/ 问答频道 /正文

它说“薪水”没有定义,或者我不能把它乘以。 我想有它与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)

我希望有人能帮助我这个小程序如何正确工作


Tags: 命令inputif定义deffloatelse形式
3条回答

您需要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。你知道吗

你需要把计算出来的薪水还给我。你知道吗

另外,如果对输入执行浮点转换,则更简单。你知道吗

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)

下面是更正,下面是一些说明。你知道吗

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)

首先,salary是一个包含在函数中的变量,它在函数之外是不可用的。你知道吗

第二,你得到一个错误,因为你用一个整数乘一个字符串。之前将其转换为float。你知道吗

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

相关问题 更多 >