Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Python

Can anyone tell me what is wrong with my code contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] name = input() for x in contacts: if name in x: print(str(x[0]) +" is " + str(x[1])) break else: print("Not Found")

1st Oct 2022, 3:35 PM
Taher Ahmed Taher
Taher Ahmed Taher - avatar
9 Answers
+ 7
Taher Ahmed Taher break should be inside if condition
1st Oct 2022, 4:01 PM
A͢J
A͢J - avatar
+ 6
Oma Falk , both of the suggested codes are not working properly: (exercise 4.2 intermediate phython) # 1: if name in contacts: # >>> is not working properly since we have a *list of tuples*. name can never be found. print(f" {name} is {contacts[name]}") else:print("not found") # 2: for key,value in contacts.items(): # >>> this code assumes that a dictc is used, but it is a *list of tuples* if name == key: print(f"{key} is {value}" # >>> missing closing parenthesis
2nd Oct 2022, 2:17 PM
Lothar
Lothar - avatar
+ 3
Hi, try the key value pair (dictionary). Break should be inside the if condition, you must indent the break properly. Your if condition is fix or constant, that causes an error too. Thank you.
2nd Oct 2022, 1:32 PM
Cris Tradio
Cris Tradio - avatar
+ 3
Hi. Steve. Okay. Thank you.
3rd Oct 2022, 1:31 AM
Cris Tradio
Cris Tradio - avatar
+ 3
Oma Falk , what we are talking about is a *code coach exercise* from a python tutorial. and the code of *contacts* is given as default by sololearn. (intermediate python, tuples, 4.2) so my opinion is: do the exercise with data as they are given.
3rd Oct 2022, 8:32 PM
Lothar
Lothar - avatar
+ 2
If name in contacts: print(f" {name} is {contacts[name]}") else:print("not found")
1st Oct 2022, 7:08 PM
Oma Falk
Oma Falk - avatar
+ 2
Lothar I see! Well but it should be a dictionary contacts=dict(contacts) will do it. The missing parenthesis is fixed. Thanks for checking😘
2nd Oct 2022, 5:57 PM
Oma Falk
Oma Falk - avatar
+ 2
Cris Tradio I don't see any problem with the if. If he just indents the break to be under the if, his code should work as expected
2nd Oct 2022, 11:24 PM
Steve
Steve - avatar
+ 1
for key,value in contacts.items(): If name == key: print(f"{key} is {value}"
1st Oct 2022, 7:05 PM
Oma Falk
Oma Falk - avatar