使两个while循环一个循环

时间:2018-10-03 09:00:19

标签: python loops

我有两个while循环,除了几个数字外几乎完全相同。我一直在环顾四周,但找不到解决问题的方法。任何帮助,将不胜感激。我想使两个while循环一个循环,但我不知道如何。我一直在寻找答案,但是似乎没有什么适合我的问题。

while True:
    print("User 1")
    login=input("Do you have an account? (yes/no) ")
    loggedin=False
    if login.lower()=="yes":
        login1=open("login.csv")
        reader = csv.reader(login1)
        username1=input("What is your username: ")
        password1=input("What is your password: ")
        for row in reader:
            if row[0]==username1:
                if row[1]==password1:
                    print("Welcome " + username1)
                    loggedin=True
                    break
        if loggedin==False:
            print("Invalid username or password. Please try again.")
            continue

    elif login.lower()=="no":
        print(" ")
        print("Make an account.")
        print(" ")
        username1=input("What is your username: ")
        password1=input("What is your password: ")
        break

    else:
        print("Invalid input.")
        continue

唯一改变的是数字1已更改为数字2(row [1]除外) 再次,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

根据您的说法,唯一的区别是1变为2我猜您只是想再次为第二个用户运行循环,也许是这里的字典,然后您可以迭代已经为每个用户构建的循环在二分法中,您将不得不修改循环,而我无法运行它们,但是格式化的想法会像这样

while True:
    users = {'User 1': [username1, password1], 'User 2': [username2, password2]}
    for k in users:
        print('{}'.format(k))
        login=input("Do you have an account? (yes/no) ")
        loggedin=False
        if login.lower()=="yes":
            login1=open("login.csv")
            reader = csv.reader(login1)
            users[k][0]=input("What is your username: ")
            users[k][1]=input("What is your password: ")
            for row in reader:
                if row[0]==users[k][0]:
                    if row[1]==users[k][1]:
                        print("Welcome " + users[k][0])
                        loggedin=True
                        break
            if loggedin==False:
                print("Invalid username or password. Please try again.")
                continue

        elif login.lower()=="no":
            print(" ")
            print("Make an account.")
            print(" ")
            users[k][0]=input("What is your username: ")
            users[k][1]=input("What is your password: ")
            break

        else:
            print("Invalid input.")
            continue

答案 1 :(得分:-1)

假设while循环在列出的函数之内,这是我想到的最简单的方法。

from threading import Thread
    t1 = Thread(target = firstFunction)
    t2 = Thread(target = secondFunction)
    t1.start()
    t2.start()