从一个函数到另一个函数使用局部变量

2024-04-20 11:59:19 发布

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

编写一个程序,用两个函数计算员工的周工资。一个函数计算工资。其他函数打印工资。如果员工加班,他的加班费应该是一次半。假设没有税。在代码中编写适当的注释。不要使用全局变量。 到目前为止,我的情况是:

def payrate():
     hours = int(input('How many hours did you work?\n'))
     rate = int(input('What is your hourly rate?\n'))
     if hours <= 40:
         total = hours * rate
     else:
         total = 40 * rate + (hours - 40) * (1.5 * rate)

def salary():
     for total in payrate():
         print('Your weekly salary is $%d' %total)
         return payrate(total)
salary()

我知道这是不对的,但我是一个初学者和学习,因为我去


Tags: 函数代码程序inputrateisdef员工
3条回答

干得好你很亲密。您的salary函数需要从payrate函数接收总薪资,payrate函数需要将总薪资返回到salary,以便可以打印它。这个代码对我来说很好:

    def payrate():

      hours = int(input('How many hours did you work?\n'))
      rate = int(input('What is your hourly rate?\n'))

      if hours <= 40 :
        total = hours * rate
      else :
        total = 40 * rate + (hours - 40) * (1.5 * rate)

      return total


    def salary():
      pay = payrate()
      print('Your weekly salary is $%d' % pay)


    salary()

我希望这有帮助

在Python中,可以将参数传递给def中的函数。。。():例如,您可以将变量rate和hours传递给函数payrate,该函数返回您计算的总计:

def payrate(rate, hours):
    ... 
    return total

如果需要一个名为salary的函数,它只打印payrate函数的结果,可以执行以下操作:

def salary(hours, rate):
   print(payrate(hours, rate))

上面的函数调用payrate函数并打印返回值。你知道吗

然后用变量“hours”和“rate”调用salary函数。你知道吗

salary(hours, rate)

希望有帮助

这应该起作用:

def payrate():
     hours = int(input('How many hours did you work?\n'))
     rate = int(input('What is your hourly rate?\n'))
     if hours <= 40:
         total = hours * rate
     else:
         total = 40 * rate + (hours - 40) * (1.5 * rate)
     return total

def salary():
     total = payrate()
     print('Your weekly salary is $%d' %total)
salary()

要使用函数中的“局部变量”,必须返回它(使用return关键字),如下所示:

return local_variable

要从另一个函数接收它,可以调用第二个函数中的第一个函数,如下所示:

recieved_local_variable = first_function() 

相关问题 更多 >