0

i have a computer science project and i can’t find anywhere how to figure this out. I need python to ask for input and if input is equal to a text file then it moves onto next input if it’s the same. If not it repeats the question: “please enter your name” so far I've got:

Player_1 = input(“please enter your name”)

Then need what I've said above. The text file only needs to contain two names. I am relatively new to python, hope someone can help.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • Welcome to Stack Overflow. IT can be very helpful to share some code you have tried. This allows other users to provide the most relevant support. Please see [this link](https://stackoverflow.com/help/how-to-ask) for tips on asking good questions. – Chris Oct 10 '18 at 14:01
  • 1
    As a simple tip for your coding problem, try reading the lines from the file at the start and saving them in a data structure before you even check for user input. – Chris Oct 10 '18 at 14:02
  • Read [pythonforbeginners.com/loops](https://www.pythonforbeginners.com/loops/) – stovfl Oct 10 '18 at 14:12
  • Possible duplicate: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response Minus the file reading I guess but that makes this a somewhat broad question rather than asking for a specific problem. – Fynn Becker Oct 10 '18 at 15:38

1 Answers1

0

Your text file "filename.txt" should use a symbol to separate names.

Let's say a comma, so your file should look like this:

filename.txt: Name1,Name2

You could use:

txt=open("filename.txt",'r').read() 

to get your file content as string.

namesList=txt.split(',') 

to get a list of the names in the file:

["Name1","Name2"]

then a loop to check inputs of the user:

userEntry=''
while userEntry not in namesList:
    userEntry=input("please enter your name")

At the end, userEntry is equal to one of the two names in your file.

NyuB
  • 93
  • 7