+ 1

double tuple trouble (in Python)

Oh, these pesky yet incredibly useful little tuple.s My problem is a list of tuples where I need to access each one with my input. Then I need my input to match (or not) with its' pair in a tuple for my output. But when I use this 'for' statement to unpack the tuple, it reassigns my input. I've tried other methods (like, 'if') but they require me to define one tuple variable type int. But I'm not sure how to do that w/o referencing my input. The OUTPUT below is the result regardless what string is input. Any assistance would be of great help w/this days- old head-scratcher... bowling_team1 = [ ('Rue', 87), ('Tara', 95), ('Joey', 102), ('Amanda', 73), ('Bobby', 88) ] name = input() for (name,score) in bowling_team1: print(name, 'has', score, 'points') OUTPUT Rue has 87 points Tara has 95 points Joey has 102 points Amanda has 73 points Bobby has 88 points

16th Jan 2024, 1:23 AM
Average American
Average American - avatar
5 odpowiedzi
+ 4
Average American , I believe you have two different name variables, one in the global namespace and one inside the for loop. Try renaming the global one name_in or something. Then you can access it inside the for loop in case you want to compare name_in to name. bowling_team1 = [ ('Rue', 87), ('Tara', 95), ('Joey', 102), ('Amanda', 73), ('Bobby', 88) ] name_in = input() for (name, score) in bowling_team1: if name == name_in: print(name, 'has', score, 'points')
16th Jan 2024, 1:49 AM
Rain
Rain - avatar
+ 2
I suggest you to use dictionary in Python.. it's more appropriate for that bowling_team1 = { 'Rue': 87, 'Tara': 95, 'Joey': 102, 'Amanda': 73, 'Bobby': 88 }
17th Jan 2024, 7:36 PM
Harimamy Ravalohery
Harimamy Ravalohery - avatar
+ 1
bowling_team1 = [ ('Rue', 87), ('Tara', 95), ('Joey', 102), ('Amanda', 73), ('Bobby', 88) ] #optional. Display list of players. print('players:') for player in bowling_team1: print(player[0], end=' ') print() name = input() result = 'name not in bowling_team1' for player in bowling_team1: if name == player[0]: score = player[1] result = f'{name} has {score} points' print(result)
16th Jan 2024, 2:05 AM
Bob_Li
Bob_Li - avatar
+ 1
or use dictionary to simplify the search. bowling_team1 = { 'Rue': 87, 'Tara': 95, 'Joey': 102, 'Amanda': 73, 'Bobby': 88 } #optional. Display list of players. print('players:\n', *(name for name in bowling_team1)) name = input() if name in bowling_team1: print(f'{name} has {bowling_team1[name]}') else: print(f'{name} not in bowling_team1' )
16th Jan 2024, 2:18 AM
Bob_Li
Bob_Li - avatar