我有一个非常基本的问题,我知道你们很容易发现错误.
现在我正在尝试编写一个计算加班费的脚本.我没有编写很多代码,所以我现在只是想坚持基本问题.我已经通过代码学院,我将以艰难的方式开始学习Python,但是我认为我需要制作更多的项目才能更好地理解.
这是我现在的代码.我很困惑为什么它认为变量尚未定义,因为我显然正在定义顶部需要的三个变量.
### California overtime payment calculator.
### Based on an 8 hour normal day, 1.5x day rate after 8 hours, and 2x pay after 12 hours.
### Enter your rate, then the number of hours you worked and you will get a result.
rate = raw_input("Enter your current rate:")
print "This is your rate: %s" % (rate)
normal = 0
overtime = 0
doubleOT = 0
def enteredHours():
userInput = raw_input("Enter your hours for given day: ")
if int(userInput) >= 12:
print "Greater than 12"
normal = normal + 8
overtime = overtime + 4
doubleOT = doubleOT + (userInput - 12)
elif int(userInput) >= 8:
print "Greater or equal to 8"
normal = normal + 8
overtime = overtime + (userInput - 8)
elif int(userInput) < 8:
normal = normal + userInput
elif str(userInput) == "calculate":
hoursTotal = normal + overtime + doubleOT
print "Total amount of hours is: " + str(hoursTotal)
payTotal = (normal * 250) + (overtime * 250 * 1.5) + (doubleOT * 250 * 2)
print "Total amount of pay is: " + str(payTotal)
return normal
return overtime
return doubleOT
enteredHours()
enteredHours()
Run Code Online (Sandbox Code Playgroud)
这对初学者来说是一个非常普遍的问题.这些变量超出了函数的范围.
在函数内部定义它们就像这样:
def enteredHours():
normal = 0
overtime = 0
doubleOT = 0
Run Code Online (Sandbox Code Playgroud)
或使用global关键字将它们放在范围内:
normal = 0
overtime = 0
doubleOT = 0
def enteredHours():
global normal
global overtime
global doubleOT
Run Code Online (Sandbox Code Playgroud)
因为您似乎正在使用这些变量来累积enteredHours函数的多个调用,所以您应该选择带有global关键字的第二个选项.
编辑:你还有一些其他问题.您的代码将在第一个return语句中返回:
return normal # exit function here
return overtime # not executed!
return doubleOT # not executed!
Run Code Online (Sandbox Code Playgroud)
如果要返回所有3个值,则需要使用相同的return语句返回它们:
return normal, overtime, doubleOT
Run Code Online (Sandbox Code Playgroud)
编辑#2
不要递归地运行代码(通过enteredHours在函数末尾调用- 无论如何都不运行此语句,因为函数退出return语句).而是在while循环中运行它:
def enteredHours():
...
while True:
enteredHours()
Run Code Online (Sandbox Code Playgroud)
这样做的原因是你的堆栈随着每次递归调用而增长,最终你会遇到"堆栈溢出":)
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |