Где разместить цикл «В то время как» цикл прерывается, как только условие было нарушено - PullRequest
0 голосов
/ 29 сентября 2019

У меня есть следующие команды и переменные, которые работают так, как должны в настоящее время.Теперь мне нужно вставить цикл while, который продолжает работать, когда условная переменная равна False, но заканчивается, когда условная переменная равна True.Где я могу разместить его?

loggedIn = False

# Create a function called `getCreds` that will prompt the user for their username, password
def getCreds():

    # Prompt the user for their username and store it in a variable called username
    username = input("Username: ")

    # Prompt the user for their password and store it in a variable called password
    password = input("Password: ")

    # Create a dictionary that will store all of the user data collected inside of it and call it userInfo
    userInfo = {"username":username,"password":password}

    # Return the above dictionary (called userInfo)
    return userInfo

# Create a function called `checkLogin` that checks if the credentials match the admin list.    
def checkLogin(userInfo):

    # If userInfo matches either set of credentials in the adminList, print "YOU HAVE LOGGED IN!" and return True
    if userInfo == adminList[0] or userInfo == adminList[1]:
        print("YOU HAVE LOGGED IN!")
        loggedIn = True
        return True                

    # Otherwise, print "---------" and return False
    else:
        print("---------")
        loggedIn = False
        return False                

    # Return user
    return user

# Get user information
userInfo = getCreds()

# Create user
user = checkLogin(userInfo)

Ответы [ 2 ]

0 голосов
/ 29 сентября 2019

Попробуйте так.

userInfo = getCreds()
loggedIn = checkLogin(userInfo)
while loggedIn:
    userInfo = getCreds()
    loggedIn = checkLogin(userInfo)

Или может быть добавлена ​​еще одна защита во избежание дублирования кода

def login():
    userInfo = getCreds()
    return checkLogin(userInfo)

while login():
    pass
0 голосов
/ 29 сентября 2019

Вы можете попробовать что-то вроде этого:

# Get user information
while True:
    userInfo = getCreds()
    # Create user
    is_logged_in = checkLogin(userInfo)
    if is_logged_in:
        break

Кстати, строка return user в вашей функции checkLogin является избыточной, поскольку она уже вернулась в условии if-else

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...