What is wrong with this code | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

What is wrong with this code

My if statement doesn't evaluate to be true hence the print statement doesn't run. The 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:07 AM
Gemuh Hans
6 Antworten
+ 2
Is that how the original code look like? is the <contacts> not a dictionary?
8th Oct 2021, 6:44 AM
Ipang
+ 1
The contact is a list which has tuples in them. So yes; that is how the original code looks like
8th Oct 2021, 6:48 AM
Gemuh Hans
+ 1
Gemuh Hans First, You need to take input in integer as your searchup is going to be with 42,24,31... which is in integer. Second, You can iterate over contacts and every iteration will give you one tuple having name and number, Now, you have to check if the number you searching is in that tuple or not. You can simply do.. eg. 42 in x (it's a tuple) If found you have to print it out and flag it as True. Outside the for loop, check if flag is true or false. If false it means no data found. contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] n = int(input()) m = False for x in contacts: if n in x: print('{} is {}'.format(n, x[0])) m = True break if m != True: print("Not found!")
8th Oct 2021, 7:17 AM
I Am a Baked Potato
I Am a Baked Potato - avatar
+ 1
Thanks so much
8th Oct 2021, 7:46 AM
Gemuh Hans
0
Here you see an `else` block underneath the `for...in` block we use to iterate the <contacts> `list`. The `else` block is placed at the same indentation level to that of the `for...in` loop, and it will only be processed IF the loop finishes completely. When the `break` statement is issued (loop exits normally, not from issuing `break` statement), the `else` block underneath the `for...in` block will not be processed. x = input() for contact in contacts: if x in contact: print( x, 'is', contact[1] ) break else: print( 'Not found' ) P.S. Also, if this was a task/coach, do pay attention on what to print, different letter case of output is one major factor that failed some people, as I have read ...
8th Oct 2021, 7:01 AM
Ipang
0
Can you please add Python in the tags above where you wrote 'contactsearch' ☝ Example: python contact-search 👍
8th Oct 2021, 7:06 AM
Ipang