Проверка по списку с использованием if if statment - PullRequest
0 голосов
/ 02 марта 2011

Я рассмотрел большинство связанных вопросов, и ни один из них, похоже, не дает мне идеи, которая мне нужна для моей программы.

users = ["Block Harris",
         "Apple Mccoy",
         "Plays Terry",
         "Michael Strong",
         "Katie Blue"]

nicknames = ["Block",
             "Apple",
             "Plays",
             "Michael",
             "Katie"]


passwords = ["abc",
             "def",
             "ghi",
             "jkl",
             "mno"]

levels = [5,2,1,4,3]

security = 0
found_user = False

username = ""
while not username:
    username = input("Username: ")

password = ""
while not password:
    password = input("Password: ")

for i in range(5):
    if username == users[i]:      
        found_user = True        
        if password == passwords[i]:
            security = levels[i]
            print("Welcome, ", nicknames[i])
            break                  
        else:
            print("Sorry, you don't know the password.")  

if found_user == levels[0]:
    print("Security level 1: You have little privelages. Congratulations.")
elif found_user == levels[1]:
    print("Security level 2: You have more than little privelages. Congratulations.")
elif found_user == levels[2]:
    print("Security level 3: You have average privelages. Congratulations.")
elif found_user == levels[3]:
    print("Security level 4: You have more than average privelages. Congratulations.")
elif found_user == levels[4]:
    print("Security level 5: You have wizard privelages. Congratulations.")

else:
    print("Apparently you don't exist.")

data_network()

То, что я пытаюсь сделать здесь, - это попытаться проверить уровень безопасности каждого из этих участников или найденных пользователей в базе данных, а затем распечатать соответствующее сообщение на основе их уровня безопасности, используя if-Другие заявления ниже.Я понятия не имею, что делает программа, но она не оценивает найденного пользователя в соответствии с его уровнем в списке.Например, для первого лица уровень в списке соответственно равен 5, но он печатает сообщение для «найденный пользователь == уровень [2]».

Ответы [ 3 ]

7 голосов
/ 02 марта 2011

Вы устанавливаете «FoundUser» на «True» или «False», но затем проверяете уровень в списке, который является целым числом. Всегда печатается 2, потому что ваш второй элемент в списке - 1.

Предложение:

Вместо формирования списков, которые только незначительно связаны в соответствии с их порядком, вы должны создать класс, содержащий всю информацию, связанную вместе:

class User(object):
    def __init__(self, name, nickname, password, security_level):
        self.name = name
        self.nick = nickname
        self.pw = password
        self.level = security_level

    def authenticate(self, name, password):
        return self.name == name and self.pw == password

    def getLevel(self, name, password):
        if self.authenticate(name, password):
            print("Welcome", self.nick)
            return self.level
        else:
            return None
2 голосов
/ 02 марта 2011

Посмотрите на wheaties ответ, который является хорошим советом. Что касается вашего кода, вы пытаетесь использовать found_user для доступа к уровню безопасности. found_user - логическое значение, а не уровень. Вам следует использовать переменную security.

При попытке напечатать информацию об уровне, используйте переменную security и проверьте уровень, а не список, содержащий уровни разных пользователей:

if security == 1:
    print("Security level 1: You have little privelages. Congratulations.")
elif security == 2:
    print("Security level 2: You have more than little privelages. Congratulations.")
elif security == 3:
    print("Security level 3: You have average privelages. Congratulations.")
elif security == 4:
    print("Security level 4: You have more than average privelages. Congratulations.")
elif security == 5:
    print("Security level 5: You have wizard privelages. Congratulations.")

else:
    print("Apparently you don't exist.")

Или даже

   levels_info = [
        "Security level 1: You have little privelages. Congratulations.",
        "Security level 2: You have more than little privelages. Congratulations.",
        "Security level 3: You have average privelages. Congratulations.",
        "Security level 4: You have more than average privelages. Congratulations.",
        "Security level 5: You have wizard privelages. Congratulations."
    ]

    if security in levels_info:
        print levels_info[security]
    else
        print "Apparently you don't exist."
0 голосов
/ 02 марта 2011
dic = {"Block Harris":("Block","abc",5),
       "Apple Mccoy":("Apple","def",2),
       "Plays Terry":("Plays","ghi",1),
       "Michael Strong":("Michael","jkl",4),
       "Katie Blue":("Katie","mno",3)}

message = dict(zip(1,2,3,4,5),("Security level 1: You have little priveleges. Congratulations.",
                               "Security level 2: You have more than little priveleges. Congratulations.",
                               "Security level 3: You have average priveleges. Congratulations.",
                               "Security level 4: You have more than average priveleges. Congratulations.",
                               "Security level 5: You have wizard priveleges. Congratulations."))


username = ""
while not username:
    username = raw_input("Username: ")

password = ""
while not password:
    password = raw_input("Password: ")

try:
    if password==dic[username][1]:
        security = dic[username][2]
        print("Welcome, ", dic[username][0])
        print(message[security])
    else:
        print("Sorry, you don't know the password.")
except:
    print("You are not registered")

РЕДАКТИРОВАТЬ:

вышеупомянутое сообщение как словарь с целыми числами в качестве ключей глупо;этот лучше

message = ("Security level 1: You have little priveleges. Congratulations.",
           "Security level 2: You have more than little priveleges. Congratulations.",
           "Security level 3: You have average priveleges. Congratulations.",
           "Security level 4: You have more than average priveleges. Congratulations.",
           "Security level 5: You have wizard priveleges. Congratulations.")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...