函数python中的If语句

问题描述 投票:-4回答:1

如果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)
python function if-statement
1个回答
0
投票

您的代码可以正常工作。

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与全局变量无关。

© www.soinside.com 2019 - 2024. All rights reserved.