Oliver
Oliver

Reputation: 9

Find if an input is in a list

Trying to get an input from the user (which the computer accepts) and then checks if it is in a list. Afterwards, it starts to play the game. Any advice?

if answer == "2":
    f = open("users.txt", "r")    
    x = str(input("Please enter a valid username: "))
    for line in f:
         usernab = print(line.strip())
         if (x) in (usernab):
                for x in range(0,5):
                       #Do something.

Here is the output:

Traceback (most recent call last):
File "E:/NEA/Project/backup.py", line 20, in <module>
if (x) in (usernab):
TypeError: argument of type 'NoneType' is not iterable

Upvotes: 0

Views: 70

Answers (2)

Ganesh Jadhav
Ganesh Jadhav

Reputation: 802

There are a few points apart from just the answer:

a) Python's input() by default returns a string, you don't need to convert by using a string conversion.
b)There's a better way to read a file in python using the keyword- 'with'.
c) You are iterating a loop after checking condition with same variable - 'x'. Seems wrong!
d) TO answer the question: the function strip returns None, and you are trying to iterate over it,so the error. Instead you can directly replace your code as:

answer = "2"
if answer == "2":
    f = open("users.txt", "r")    
    x = input("Please enter a valid username: ")
    for line in f:

         if (x) in (line.strip()):
                for i in range(0,5):
                    print('Hi',x)

Upvotes: 0

Grizzlly
Grizzlly

Reputation: 596

First of all take a look at this answer on reading a file line by line. How to read a large file, line by line, in Python

The correct, fully Pythonic way to read a file is the following:

with open(...) as f:
    for line in f:
        # Do something with 'line'

From my understanding, what you are trying to do is to check if the username entered by the user is in the list and than #Do something.

The first problem is that usernab does not get any value from usernab = print(line.strip()), as print() does not return anything. Instead you should assign usernab the line and than print it:

usernab = line.strip()
print(usernab)

The second problem is that you are trying to use x witch is a string to iterate in a range of ints. You are basically saying: "For each string in the range 0 to 5, #Do something". You should use another variable.

Furthermore, if (x) in (usernab) will check if usernab CONTAINS x. Depending on what you want to do, you might want to change this.

This code compiles under Python 3.7. It will add 1 to i five times, each time x is found in a line.

f = open("users.txt", "r")

x = str(input("Please enter a valid username: "))

i=0

for line in f:

     usernab = line.strip()
     print(usernab)

     if (x) in (usernab):
            for j in range(0,5):
                i+=1

print(i)

Upvotes: 1

Related Questions