Reputation: 26
This Is Quite Simple but I cant get the hang of it. I'm writing a short program where you enter the name, it will compare to each item in the array, then if it is found print what number it is in the array. if it isnt found, then enter a new name
Names = ['alice', 'bob', 'carol', 'david']
name = input("Enter Name ").lower()
c = 0
while name != Names[c]:
c = c + 1
if c == (len(Names)):
name = input("Name Not Found \n \nEnter Name ").lower()
c = 0
if name == Names[c]:
print ("name found, in position ", c)
It Always Comes Up With Name Not Found
Upvotes: 0
Views: 192
Reputation: 2660
Alternatively, you could use Name.index(name)
and create a recursive function to search for names, like so:
Names = ['alice', 'bob', 'carol', 'david']
def findName():
name = input("Enter Name: ").lower()
if name in Names:
print(f'Name at position {Names.index(name)}')
else:
print('Name not found; try again')
findName()
findName()
Or the same code but in a loop:
while True:
name = input("Enter Name: ").lower()
if name in Names:
print(f'Name at position {Names.index(name)}')
break
else:
print('Name not found; try again')
Upvotes: 1
Reputation: 11
Use name = input("Enter Name ").lower()
instead of name = input("Enter Name ").lower
.
name = input("Enter Name ").lower
would assign name to the function lower, while name = input("Enter Name ").lower()
runs the function lower and assigns name its return value
Upvotes: 1
Reputation: 89
name.lower without the () at the end will return the whole lower function and it will mess with the variable
So just replace that with name.lower() and it should work
Upvotes: 2