5

I enter a username - "User1" - however the result always prints that "User1" is an incorrect username even though it is in the external text file.

import random

print ("Welcome to the Music Quiz!")

username = input("please enter your Username...")

f = open("F:/GCSE/Computer Science/Programming/username.txt","r");
lines = f.readlines()


if username == "lines":
    print = input("Please enter your password")

else:
    print("That is an incorrect username")

If the usernames - User1 User2 User3 User4 User5 are entered as a username then the output should be "please enter your password"

SuperStew
  • 2,857
  • 2
  • 15
  • 27
  • you check if username is equals to "lines" as string. What you want is to check if the username is 'in' lines. So look here please: https://stackoverflow.com/questions/5143769/how-do-i-check-if-a-given-python-string-is-a-substring-of-another-one – hasan Apr 15 '19 at 16:09
  • 1) It should be `lines` instead of `"lines"`. 2) Its not clear how the data is structured inside `username.txt`. 3) What happens when you run the script? – amanb Apr 15 '19 at 16:10

1 Answers1

3

lines = f.readlines() will create a list of each line in the text file. Provided that each username is on a separate line. Otherwise, you don't want to read it line by line, but rather some other delimiter.

What you want to do is to check if the username input is in that list. So you'd want:

if username in lines: 

The problem with that though is it needs to be an exact match. If there is an extra whitespace, it will fail. So what you could do is use the .strip() to clear any whitespace.

There is also another huge issue with:

print = input("Please enter your password")

You are using the print function to store your input string. When you use input it will print it. And then what you really want is to store that input as something...I called it password

import random

print ("Welcome to the Music Quiz!")

username = input("please enter your Username... ")

f = open("C:/username.txt","r")

# Creates a list. Each item in the list is a string of each line in your text files. It is stored in the variable lines
lines = f.readlines()

# the strings in your list (called lines), also contains escape charachters and whitespace. So this will create a new list, and for each string in the lines list will strip off white space before and after the string
users = [user.strip() for user in lines ]

# checks to see if the username input is also in the users list
if username in users:
    password = input("Please enter your password: ")
else:
    print("That is an incorrect username")
chitown88
  • 27,527
  • 4
  • 30
  • 59