Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用def*在此处插入名称*():函数?_Python - Fatal编程技术网

Python 如何使用def*在此处插入名称*():函数?

Python 如何使用def*在此处插入名称*():函数?,python,Python,我是python新手,在代码中除了def main之外,我还想使用更多函数: 我下面的代码可以工作,但我正在尝试向各自的区域添加新的def 因此,就像一个名为def calcPay:的新def一样,输入的小时数计算为regPay、overtimePay和total三个单独的项目。 & 同时添加一个名为def displayOutput:的新def,该函数将从overtimePay、regPay和totalPay接收所有三个值,并打印下面的消息 如果有人能向我解释如何使用除main之外的新功能,我

我是python新手,在代码中除了def main之外,我还想使用更多函数:

我下面的代码可以工作,但我正在尝试向各自的区域添加新的def

因此,就像一个名为def calcPay:的新def一样,输入的小时数计算为regPay、overtimePay和total三个单独的项目。 & 同时添加一个名为def displayOutput:的新def,该函数将从overtimePay、regPay和totalPay接收所有三个值,并打印下面的消息

如果有人能向我解释如何使用除main之外的新功能,我将不胜感激

谢谢,这是我的代码:

def main():

    try:
        hoursWorked = float(input("How many hours did you work? "))


        if hoursWorked > 40:
                overtimePay = (hoursWorked - 40) * 15
                regPay = 40 *10
                totalPay =( overtimePay + regPay)

        else:
            regPay = hoursWorked * 10
            overtimePay = 0
            totalPay = (regPay + overtimePay)


        print("You earned",'${:,.2f}'.format(regPay),"in regular pay",'${:,.2f}'.format(overtimePay),
              "in overtime for a total of",'${:,.2f}'.format(totalPay))
    except:
        print("Sorry, that wasn't a valid number. Ending program")


main()

看看这些类似的问题:

名为main的函数没有什么特别之处。您可以根据需要命名函数

当你调用一个函数时,你只是从一个代码块跳到另一个代码块。当函数返回时,它返回到调用它的行

def something():
    print('something')

def other():
    print('else')

def a_value():
    return 100

something()
other()
x = a_value()
print(x)

# ~~~~~ output
something
else
100
在您的示例中,函数的一个好用法是计算员工的工资

def total_pay(hours_worked, hourly_rate, overtime_after=40):
    base_pay = min(overtime_after, hours_worked) * hourly_rate
    overtime_pay = max(0, hours_worked - overtime_after) * (hourly_rate * 1.5)
    return base_pay + overtime_pay

这个函数允许我们定义决定工人工资的三个因素。基本工资最多为加班前的小时数。加班费将从0到此处未定义的其他限制。超时时间为1.5秒。

您可以在主函数声明之外声明您的函数,然后在主函数中或主函数中的其他函数内部使用它们

所以你可以这样做:

def calcPay(hours):
    # Does logic
    return [400, 30, 430]

def displayOutput(regPay, overtimePay, totalPay):
    # Prints formatted string

def main():
    hoursWorked = float(input("How many hours did you work? "))
    pay = calcPay(hoursWorked)
    displayOutput(pay[0], pay[1], pay[2])

main()

名为main的函数没有什么特别之处。只需定义一个具有所需名称的函数,编写其参数,然后编写函数体。就像你对main做的那样。我不清楚你在努力做什么。如果你是Python新手,请联系我们。你问的是非常基础的语言知识,这个问题太宽泛了。