0

Python Contact List

Test task, given range of contacts, user should input a name, and if name exists the code should output Name and Age *** So, my code has passed the test, but I think that it is too wordy and feels like I could do it much better and shorter, Can you please state how could I do it better? contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] n = input() if n in contacts[0]: print(str(contacts[0][0]) + " is " + str(contacts[0][1])) elif n in contacts[1]: print(str(contacts[1][0]) + " is " + str(contacts[1][1])) elif n in contacts[2]: print(str(contacts[2][0]) + " is " + str(contacts[2][1])) elif n in contacts[3]: print(str(contacts[3][0]) + " is " + str(contacts[3][1])) elif n in contacts[4]: print(str(contacts[4][0]) + " is " + str(contacts[4][1])) else: print("Not found")

5th Jun 2021, 10:21 AM
Adilet Kambarov
Adilet Kambarov - avatar
3 Respuestas
+ 9
#try this contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] n = input() for i, j in contacts: if i == n: print(i , " is " ,j) break else: print("Not found")
5th Jun 2021, 10:52 AM
Simba
Simba - avatar
+ 5
Adilet Kambarov , you can check each tuple during an iteration like: contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] n = input() for contact in contacts: if n in contact: print(contact[0], "is", contact[1]) # you don't need to convert data formats when commas as a separater is used! break else: print("Not found")
5th Jun 2021, 10:49 AM
Lothar
Lothar - avatar
0
Please help! I found this answer after thinking about it all day and it accept it as correct But I can’t add the else statement because when I do it either throws an error about indentation or it also prints the else statement anyway and it’s not correct anymore contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] nam = input() i=0 for name, age in contacts: name, age = contacts[i] if nam == name: print(name + ' is ' + str(age)) i+=1 #with the else statement that throws error is like this: nam = input() i=0 for name, age in contacts: name, age = contacts[i] if nam == name: print(name + ' is ' + str(age)) i+=1 else: print('Not found')
14th Aug 2021, 7:21 PM
Xheni Lamaj
Xheni Lamaj - avatar