problem in loop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: problem in loop (/thread-20697.html) |
problem in loop - roseojha - Aug-26-2019 Hey guys.. I wanted to have a loop from list of tuples where i can extract name of husband by giving name of wife.. I got that ... but when I am trying to put one more statement so that if name is not available, it can give precautionary statement, I am having problems.. Please see the code below and suggest what I can do.. PS I do not want to convert it into dictionary. husbands=[('ginny','harry'),('eve','adam'),('lizzy','darcy'),('rose','jack')] wife=input('write wife name here = ') for x in husbands: if wife == x[0]: loved = x[1] print('her husband is ',loved) elif wife != x[:]: print('name is not available') RE: problem in loop - Malt - Aug-26-2019 You can try this husbands=[('ginny','harry'),('eve','adam'),('lizzy','darcy'),('rose','jack')] wife=input('write wife name here = ') for x in husbands: if wife == x[0]: loved = x[1] print('her husband is ',loved) break elif wife != x[:]: continue else: print("Name is not available") RE: problem in loop - ThomasL - Aug-26-2019 I would do it this way: husbands = [('ginny', 'harry'), ('eve', 'adam'), ('lizzy', 'darcy'), ('rose', 'jack')] name = input('write wife name here = ') found = False for wife, husband in husbands: if name == wife: print(f'{wife}´s husband is {husband}') found = True if not found: print(f'{name} might be single as she is not in the list') RE: problem in loop - perfringo - Aug-26-2019 ThomasL refactored code to take advantage of else: clause in for-loop (no need for sentinel): >>> name = 'lizzy' >>> for wife, husband in husbands: ... if wife == name: ... print(f"{wife.title()}'s husband is {husband.title()}") ... break ... else: # no-break ... print(f"{name.title()} might be single as she is not in the list") ... Lizzy's husband is DarcyThere is of course question of uniqueness. This code returns first match but if there are several wives with same name what is expected result? For built-in help on for-loop (including else clause): >>> help('for') EDIT: One can approach this problem with another angle: get all matching pairs in list and use conditional to print appropriate information: >>> matches = [f"{wife.title()}'s husband is {husband.title()}" for wife, husband in husbands if wife == name] >>> if matches: ... print(*matches, sep='\n') ... else: ... print(f"{name.title()} might be single as she is not in the list") ... Lizzy's husband is Darcy |