簡體   English   中英

如何使用兩個用戶輸入來簡化ifif代碼?

[英]How can I simplify my if elif code with two user inputs?

with open("bankaccount.txt", 'a+') as f:
    if User1_working_status =="1":
        f.write("{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n".format("Name: "     + user1_title + " " + user1_name,        
        "Gender:" + user1_gender,"Town and country: "
        + user1_town, "Age: " + user1_age,"Country and town of birth: "+ user1_country_of_birth,"Nationality: "
        + user1_nationality,"Country residence:"+user1_country_residence,"Tax resident country: "
        + user1_tax_res,"Working status: Employed"))
        print("Working status: Employed")


    elif User1_working_status=="2":
        f.write("{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n".format("Name: " + user1_title + " " + user1_name, "Gender:"
        + user1_gender,"Town and country: " + user1_town, "Age: " + user1_age,"Country and town of birth: "
        + user1_country_of_birth,"Nationality: "+ user1_nationality,
        "Country residence:"+user1_country_residence,"Tax resident country: "+ user1_tax_res,
        "Working status: Self Employed"))
        print("Working status: Self Employed")

有什么辦法可以縮短時間? 我對用戶2具有相同的功能,但隨后我必須再次對user2_working_status進行所有操作,並且由於我有9個選項,因此代碼變得太長。

長格式字符串也很不可讀。 這個怎么樣?

with open("bankaccount.txt", 'a+') as f:
    if User1_working_status in ("1", "2"):
        working_status_label = "Employed" if User1_working_status == "1" else "Self Employed"
        for label, value in [
                ("Name", user1_title),
                ("Gender", user1_gender),
                ("Town and country", user_1_town),
                ("Age", user1_age),
                ("Country and town of birth",  user1_country_of_birth),
                ("Nationality", user1_nationality),
                ("Country residence", user1_country_residence),
                ("Tax resident country", user1_tax_res),
                ("Working status", working_status_label)]:
            f.write("{0}: {1}\n".format(label, value))
        print("Working status: {0}".format(working_status_label)

您可以使用每個狀態值的標簽創建字典,如下所示:

status_labels = {
    "1": "Employed",
    "2": "Self Employed"
}

with open("bankaccount.txt", 'a+') as f:
    ...
    print("Working status: {}".format(status_labels[User1_working_status]))

編輯 :對於多個用戶,最好是遍歷字典列表,並根據如何使用python-3.x中的字典格式化字符串來使用str.format(** dict) ,例如:

users = [{"title": "dd", "working_status": ...}, ...]

with open("bankaccount.txt", 'a+') as f:
    for user in users:
        ..."Name: {title}, Working status: {working_status}".format(**user)

暫無
暫無

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

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