简体   繁体   中英

If statement inside a function python

If statement inside per only executes the else line, none of the above works. Also, if salary is defined as salary(hour, worktype) again it does not work. Why?

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)

Your code works fine.

IPython session:

>>> 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

What could be tripping you up here is that you enter the work type in lower case. You could allow this by adding

worktype = worktype.upper()

as the first line of per .

Also, I would move

x = per(worktype)

inside of the salary function. It has no business as a global variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM