+ 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")
9 Answers
+ 7
Taher Ahmed Taher
break should be inside if condition
+ 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
+ 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.
+ 3
Hi. Steve. Okay. Thank you.
+ 2
If name in contacts:
print(f" {name} is {contacts[name]}")
else:print("not found")
+ 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đ
+ 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
+ 1
for key,value in contacts.items():
If name == key:
print(f"{key} is {value}"