在python中,如何从一个问题添加到两个列表中

2024-06-17 08:17:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道我是否走错了方向,但我希望你能帮我睁开眼睛。我也不太确定这个问题的措辞是否正确,但我需要这个问题来询问用户他们会选择哪个模块两次,然后将其添加到单独的列表中。我想有更好的方法可以做到这一点

重要的是,我要将用户输入插入列表,而不是其他类型的容器

def Module_selection(lss=[]):
    print("Welcome, you can pick your module here")
    modules = ["Programming 1", "Programming 2", "Networking 1", "Mathematics"]
    print(lss)
    StudID = input("Please enter your student ID: ")
    Password = input("Please enter your password: ")
    if StudID.isnumeric():
        StudID = int(StudID)
    found = 0
    for item in lss:
        if StudID == item[5] and Password == item[4]:
            option = input("""Please select the first module you want to take
                                1)Programming 1
                                2)Programming 2
                                3)Networking 1
                                4)Mathematics""")

            found = 1

            if option == "1":
                item[6] = modules[0]
                break


            elif option == "2":
                item[6] = modules[1]
                break


            elif option == "3":
                item[6] = modules[2]
                break


            elif option == "4":
                item[6] = modules[3]
                break



    if found == 0:
        print("There is no student with this information")

Tags: 用户modulesinputyourifitemprogrammingoption
1条回答
网友
1楼 · 发布于 2024-06-17 08:17:51

我可以看出,在计算机编程中,你需要关注的最重要的原则是尽可能将不同的任务分开

例如,您有:

  • 检查用户名和密码是否正确的代码
  • 询问学生想要学习的课程的代码:
    • 联网
    • 英式
    • 数学等等

检查登录凭证和选择课程是两项截然不同的任务

但是,您将它们的代码交织在一起

它有助于将检查用户名和密码的代码放在一个单独的函数中

def get_and_check_login_credentials(lss=[]):
    StudID = input("Please enter your student ID: ")
    Password = input("Please enter your password: ")
    if StudID.isnumeric():
        StudID = int(StudID)
    found = 0
    for item in lss:
        if StudID == item[5] and Password == item[4]:    
            found = 1    
    if found == 0:
        print("There is no student with this information")

我注意到另外一件事:

You defined a function which contains code for both of the following:

  • processes many items
  • processing only one item
# One function, to do it all
def Module_selection(lss=[]):
    # this function processes many items
    # `lss` contains many items
    for item in lss:
        # inside of the for-loop you have
        # a *LOT* of code for processing one item  

以下内容应写成两个独立的函数:
代码不应全部包含在一个函数中:

  1. 用于处理多个项目的代码
  2. 仅处理一个项目的代码

以下更好:

def process_many(lss=[]):
    for item in lss:
        # process one item  
        process(item)  
        # almost no in-line code
        # just call the function for processing one item    

def process_one(item):
    pass
    # put code here which processes one item.   

下面,我试图清理您检查用户名和密码的代码,但这对我来说毫无意义:

def get_and_check_credentials(item):
    StudID = input("Please enter your student ID: ")
    Password = input("Please enter your password: ")
    if StudID.isnumeric():
        StudID = int(StudID)
        if StudID == item[5] and Password == item[4]:
            return True # ALLOW ACCESS
    return False # PROHIBIT ACCESS

请注意:

  • item[5]包含“正确的”学生ID
  • item[6]包含“正确的”密码

我不知道为什么item被命名为item
变量名称应始终有意义。
比如说,

  • shirt_size”是比“s”更好的变量名

为什么用户名和密码存储在“item”中

另外,假设您正在使用一个网站,例如gmail.comstackoverflow.com

你输入你的用户名

以下内容与您的代码非常相似:

StudID = input("Please enter your student ID: ")
if StudID == correct_username:
    # select a course to sign-up for
else:
    # forbid access. 
    # disallow the end-user from signing-up for college courses.   

网站如何提前知道正确的学生ID

这就好像计算机已经知道用户应该输入什么用户名

如果stackoverflow.com是那样的话,那就意味着地球上只有一个人可以登录stackoverflow.com,没有其他人可以使用stackoverflow.com

我建议搜索学生ID

如果您有一个很长的学生ID列表,您可以搜索该列表以查看是否有用户输入


# Just as an example,
# maybe a student named "John Miller" has student id
# "8623462"
#
# "8623462", "3974923", and "2973942" are all examples
# of valid student ids
#

logins = {
  "8623462": "secret_password1234",
  "3974923": "PA$$WORD",      
  "2973942": "hE11oWoR1D"   
}

def get_and_check_credentials(logins):
    """
            +    +                      +
            | OUTPUT |                  MEANING                   |
            +    +                      +
            |      0 | End-user entered                           |
            |        | valid student id and password.             |
            |        | ALLOW ACCESS.                              |
            +    +                      +
            |      1 | Error 1: student id is not a number        |
            +    +                      +
            |      2 | Error 2: student id is not in the database |
            +    +                      +
            |      3 | Error 3: username is correct, but          |
            |        | password is wrong                          |
            +    +                      +

        There is only one way for things to go right
        and a millions ways for things to go wrong.   
        That is why error code 0 means everything went well.       
        
    """
    raw_id = input("Please enter your student ID: ")
    raw_password = input("Please enter your password: ")
    if raw_id.isnumeric():
        raw_id = int(raw_id)
        password = logins.get(raw_id , None)
        if password != None:
            if raw_password == password:    
                # valid username and password entered
                # allow access
                return (0, raw_id)
            else:
                # username is correct, but
                # password is wrong
                return (3, raw_password)
        else: 
            # student id is not in the database
            # student id is syntactically okay (numbers only, etc...) 
            # there is no student having the student-id `raw_id`
            return (2, raw_id)
    else: 
        # raw student id number is not numeric
        return (1, raw_id) 

注:

Generally, student id numbers are not numeric.
The student id number S0165139B contains the letters S and B
student id numbers often contain letters, such as A, B, C, etc...
However, you wrote your code to forbid non-numbers.
Therefore, my code also makes sure to allow only numbers.

另一项说明:

ALWAYS call strip() on user-input. In python the same of the function is strip(), but in almost all other programming languages, the name of the function is trim() As an example, a trim function will remove space characters from the end of a phone-number.
"(303)-111-2222 " becomes "(303)-111-2222" with no space character at the end

还有一个注意事项:

Suppose that your goal was to cook a 5-course dinner.
Maybe one function makes only dessert ... ice-cream, Gulab Jamun, German chocolate cake, tiramisu.... I don't know.
A different function in your code will make the entire feast.
The function which makes the the entire feast is called the "main" function.
In your case, you named your main function "Module_selection"
The name is okay, but your main function should NOT contain code.
main() should be short (at most 15 lines of code)
main should do almost nothing but call other functions
If you are cooking a large feaast, main should call make_dessert() and main should call make_side_dish().
main() should not contain any of the details.
main() should not contain any "in-line" code
Your main function Module_selection() currently contains a million little detailed lines of code.
I cannot seperate making_dessert() from make_the_drinks()
Next time, KEEP EVERYTHING SEPERATE
The principle of "modularity" will help you write better programs in the future.

def main():
    while True:
        login_result = get_and_check_login_credentials()
        if not is_valid(login_result):
            continue # go back to the start of the loop
        # otherwise...
        sign_up_for_classes(login_result.username)

def sign_up_for_classes():
    while(True):
        print_the_menu()
        user_input = get_the_menu_selection()
        if user_want_to_quit(user_input):
            return
        sign_up_for_chosen_class(user_input)

最后一点注意:

I have not fixed all of the mistakes in your code.
However, I hope that my suggestions will give you a good start.

相关问题 更多 >