+ 1
Code doesn't work
The if statement doesn't evaluate to be true hence the print statement won't run. Here goes the code contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] #print(contacts.get(input(,'not found')) x = input() if x in contacts: print (x+'is' + contacts[x][1]) else: print( 'not found')
7 odpowiedzi
+ 1
Hello, yes I have solved your problem! You need to iterate over the list and look at the individual tuples. When you call x in contacts, you are looking at the tuples themselves which won't help you. You need to use a for loop and see what each tuple contains. If it has what you want, print out your statement. If we have reached the end of the list and no match, then we want to call Not Found.
contacts = [
('James', 42),
('Amy', 24),
('John', 31),
('Amanda', 63),
('Bob', 18)
]
#print(contacts.get(input(,'not found'))
x = input()
for i in range(len(contacts)):
if x in contacts[i]:
print (x + ' is ' + str(contacts[i]))
break
if i == len(contacts) - 1:
print('Not Found')
i += 1;
+ 1
Please can you help explain the loop. For example the loop say for i in range (len (contacts). I thought we would use for X in that range
+ 1
Hi, i is the index of the list. Since we are iterating over the list, we want to get each item at that position. Its like a table of contents, start from the 0 - length of our list. As we look at each index, we check if our value is in that spot.
+ 1
Similar to a book, if you found the pages for a chapter from the table of contents, that still wouldn't tell you whats in the chapter itself. Thats why we I used i.
0
Okay thanks so much sir
0
Jibraeel Abdelwahhab
Great explanation
0
using dictionary can be much better for this idea