+ 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
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
+ 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")
+ 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])
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
0
I checked with chatgpt but this code is correct
0
How bro