如何使用两个用户输入来简化ifif代码?

时间:2019-01-06 10:56:27

标签: python

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个选项,因此代码变得太长。那么,是否有办法在此代码中同时组合user1和user2?:)

2 个答案:

答案 0 :(得分:1)

长格式字符串也非常不可读。怎么样?

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)

答案 1 :(得分:0)

您可以像这样为每个状态值创建带有标签的字典:

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

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

编辑:对于多个用户,最好遍历字典列表并按照How do I format a string using a dictionary in 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)