如果per内部的语句仅执行else行,则以上方法均无效。同样,如果将工资再次定义为工资(小时,工作类型),则它将不起作用。为什么?
hour=int(input("Enter your hours of work: "))
worktype=input("Enter your worktype: ")
def per(worktype):
if worktype =="A":
return(8)
elif worktype =="B":
return(10)
else:
return(15)
x=per(worktype)
def salary(hour, x):
print("Your total salary is:", hour * x)
salary(hour, x)
您的代码可以正常工作。
IPython会话:
>>> hour=int(input("Enter your hours of work: "))
...: worktype=input("Enter your worktype: ")
...:
...: def per(worktype):
...: if worktype =="A":
...: return(8)
...: elif worktype =="B":
...: return(10)
...: else:
...: return(15)
...:
...:
...: x=per(worktype)
...: def salary(hour, x):
...: print("Your total salary is:", hour * x)
...:
...: salary(hour, x)
Enter your hours of work: 10
Enter your worktype: B
Your total salary is: 100
这里可能使您绊倒的是,您以小写形式输入工作类型。您可以通过添加
worktype = worktype.upper()
作为per
的第一行。
此外,我将salary
重写为
def salary(hour, worktype):
print("Your total salary is:", hour * per(worktype))
X
与全局变量无关。