0
ELI5 how this code is executing the desired output
You are given a list of contacts, where each contact is represented by a tuple, with the name and age of the contact. Complete the program to get a string as input, search for the name in the list of contacts and output the age of the contact in the format presented below: Sample Input John Sample Output John is 31 the code is: contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] name = input() loop = 0 for x in contacts: if name in x: print(name + " is " + str(x[1])) break else: loop += 1 if loop == len(contacts): print("Not Found") I'm having a brain freeze understanding it. what's going on here??
3 Respuestas
+ 5
Nour Mohamed ,
Here you take name as a user input ...
And initialising loop=0
Using for loop we are checking whether the name in the contacts and what you provided as a user input is equal or not through if condition...
If it is equal it will print the statement and and the loop breaks...
If it is not equal loop value incremented by 1...
And finally the loop value is equal to total length of the contacts...then it indicates that there is no match...and print "not found"
Hope you understand 👍
+ 5
Nour Mohamed ,
the last line with print() statement needs to be indented to the previous line.
> to understand how the code is working, it can be written differently, also using *found* instead of variable name *loop*:
contacts = [
('James', 42),
('Amy', 24),
('John', 31),
('Amanda', 63),
('Bob', 18)
]
name = input()
found = False
for x in contacts:
if name in x:
print(name + " is " + str(x[1]))
found = True
break
if found == False:
print("Not Found")
0
أوضحه لك بالعربي
اتخيلي عندك سلسلة من الصناديق اسمها contacts
كل صندوق فيه اسم الشخص وعمره ، مثلاً في الصندوق الأول James وعمره 42 والثاني Amy وعمرها أربعة وعشرين ....
الحين يريدون من البرنامج إن المستخدم يدخل اسم الشخص وهذا المستخدم يمكن مايعرف شو أسماء
الأشخاص فإذا دخل اسم صح
for x in contacts عشان نوصل للاسم لازم نوصل للصندوق أول
if name in x إذا الاسم تواجد في صندوق
اظهر النتيجة
print(name+"is"+str(x[1]))
الاسم نوعه string مانقدر نسوي ربط مع الرقم اللي هو age
فلازم نقلبه ل string
str(x[1])
وليش 1 لأن index في السلاسل يبدأ ب 0
أما إذا كان اسم الشخص مو موجود فاكتب مو موجود
أتمنى يكون شرحي واضح