更具体地说,我想从里面调用函数get_hours_worked calc_gross_pay。我意识到另一种方法是将参数传递给calc_gross_pay,但我想知道我试图做的是否可行。我有一种感觉它没有。谢谢你的帮助。
def main():
#
print("This employee's gross pay for two weeks is:",calc_gross_pay())
def get_input():
def get_hours_worked():
#get_hours_worked
x = float(input("How many hours worked in this two week period? "))
return x
def get_hourly_rate():
#get_hourly_rate()
y = float(input("What is the hourly pay rate for this employee? "))
return y
def calc_gross_pay():
#
gross = get_input(get_hours_worked) * get_input(get_hourly_rate)
return gross
main()
答案 0 :(得分:1)
这是您的代码的重组版本。我们不是在get_hours_worked
中定义get_hourly_rate
和get_input
,而是将它们定义为调用get_input
的单独函数。
def get_input(prompt):
return float(input(prompt))
def get_hours_worked():
return get_input("How many hours worked in this two week period? ")
def get_hourly_rate():
return get_input("What is the hourly pay rate for this employee? ")
def calc_gross_pay():
return get_hours_worked() * get_hourly_rate()
def main():
print("This employee's gross pay for two weeks is:", calc_gross_pay())
main()
<强>演示强>
How many hours worked in this two week period? 50
What is the hourly pay rate for this employee? 20.00
This employee's gross pay for two weeks is: 1000.0
答案 1 :(得分:0)
正如PM 2Ring指出的那样,更好地改变层次结构本身。但是如果你想要相同的话,请按以下步骤操作:
def get_input():
def get_hours_worked():
x = float(input("How many hours worked in this two week period? "))
return x
def get_hourly_rate():
y = float(input("What is the hourly pay rate for this employee? "))
return y
return get_hours_worked, get_hourly_rate # IMP
def calc_gross_pay():
call_worked, call_rate = get_input() # get the functions
gross = call_worked() * call_rate() # call them
return gross
def main():
print("This employee's gross pay for two weeks is:",calc_gross_pay())
#How many hours worked in this two week period? 3
#What is the hourly pay rate for this employee? 4
#This employee's gross pay for two weeks is: 12.0
main()