簡體   English   中英

function python 中的 If 語句

[英]If statement inside a function python

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

在這里可能會絆倒您的是您以小寫形式輸入工作類型。 您可以通過添加來允許這樣做

worktype = worktype.upper()

作為per的第一行。

另外,我會搬家

x = per(worktype)

里面的salary function。 它與全局變量無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM