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