Code doesn't work | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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')

8th Oct 2021, 6:10 AM
Gemuh Hans
7 Answers
+ 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;
8th Oct 2021, 6:36 AM
Jibraeel Abdelwahhab
Jibraeel Abdelwahhab - avatar
+ 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
8th Oct 2021, 6:53 AM
Gemuh Hans
+ 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.
8th Oct 2021, 6:56 AM
Jibraeel Abdelwahhab
Jibraeel Abdelwahhab - avatar
+ 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.
8th Oct 2021, 6:58 AM
Jibraeel Abdelwahhab
Jibraeel Abdelwahhab - avatar
0
Okay thanks so much sir
8th Oct 2021, 7:58 AM
Gemuh Hans
0
Jibraeel Abdelwahhab Great explanation
8th Oct 2021, 10:45 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
using dictionary can be much better for this idea
9th Oct 2021, 5:43 PM
RDOriginall
RDOriginall - avatar