+ 1

Tuples in python exercise

What is wrong with this 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") Names and ages are given as a tuple. The code should take user input, search the tuples and print e.g. John is 31

24th Jan 2024, 8:31 PM
Dragan
6 odpowiedzi
+ 6
Suppose we enter "Amy". What happens? The first contact x does not contain "Amy", we get "Not Found" and the loop continues. https://www.sololearn.com/Discuss/3259490/?ref=app
24th Jan 2024, 8:58 PM
Lisa
Lisa - avatar
+ 3
Dragan, all you need to do is assign the conditional "else" operator to the "for" loop, and there is also no need to use the str() function for x[0] since this element is already a string. for x in contacts: if name in x: print(x[0]+" is "+str(x[1])) break else: print("Not Found")
24th Jan 2024, 10:38 PM
Solo
Solo - avatar
+ 1
Dragan , Others already helped you solve it. I want to de-program your mind from a bad habit Sololearn teaches of using str() and +, and explicitly padding your strings with spaces all the time when printing. You don't need to, because the print function automatically converts your arguments to strings and separates them with spaces before printing. Instead of this, print(str(x[0]) + " is " + str(x[1])) just do this. print(x[0], "is", x[1])
24th Jan 2024, 10:50 PM
Rain
Rain - avatar
0
I've solved it in the meantime. The problem was that the alignment of else statement mattered a lot. However, I had problems running the code with the proper positioning of the else statement. The thing started working once I rewrote the code
24th Jan 2024, 10:41 PM
Dragan
0
I checked with chatgpt but this code is correct
26th Jan 2024, 12:10 PM
Python Vietnam
Python Vietnam - avatar
0
How bro
26th Jan 2024, 7:29 PM
Abhishek Reddy
Abhishek Reddy - avatar