如何在python

时间:2017-11-10 18:54:27

标签: python-3.6

我是一个新的python用户,最近开始研究一个在python中创建测验的项目。我想为参加测验的每个人都做一个帐户。我将所有用户名和密码保存在文本文件中,如果用户想要登录,程序将检查文件中的用户名和密码。这是我的代码,但是当我运行它时会打印输出对于文件中文本的每一行。我只想要一个基于整个文件的输出。有人知道如何解决这个问题吗?:

 choice = input("are you registered user?")
    if choice == "1":
        age = input ("age? ")
        name = input ("name? ")
        yrgroup = input("yr group? ")
        username = name[:3] + age 
        print ("your username is ", username)
        password = input ("password? ")
        students = open("students.txt","a")
        students.write(password)
        students.write(" ")
        students.write(age)
        students.write(" ")
        students.write(yrgroup)
        students.write(" ")
        students.write(username)
        students.write(" ")
        students.write(name)
        students.write(" ")
        students.write("\n")
        students.close()
    elif choice == "2":
        user = input ("please enter your username: ")
        pas = input ("please enter password: ")
        with open("students.txt","r") as file:
            for line in file:
                word = line.split(" ")
                if pas in word:
                    print ("LOGGING IN")
                else:
                    print ("WRONG")
    else:
        print("invalid input")

我在运行它时会打印出来:

 hello everyone
    are you registered user?2
    please enter your username: ale15
    please enter password: meow
    WRONG
    WRONG
    WRONG
    LOGGING IN

我需要输出一行,说明它是错还是登录。

1 个答案:

答案 0 :(得分:1)

你可以做到

user = input ("please enter your username: ")
    pas = input ("please enter password: ")
    result = False
    with open("students.txt","r") as file:
        for line in file:
            word = line.split(" ")
            if pas in word:
                result = True
    if (result):
        print('LOGGIN IN')
    else:
        print('WRONG')