About the challenges
The challenges below allow you to apply your knowledge of the topics up to this point.
Challenge 1: Colours in the rainbow
Write a program that asks the user to guess the colours of the rainbow. Each time the user guesses a colour that is in the rainbow it should be removed from the colours array. When they guess a colour that is not in
the rainbow the program should stop and output how many colours the user managed to guess. If they guess all colours a congratuatory message should be displayed.
colours = ["Red","Orange","Yellow","Green","Blue","Indigo","Violet"] guess = input("Enter a colour that is in the rainbow: ").title() while guess in colours: colours.remove(guess)
guess = input("Enter a colour that is in the rainbow: ").title() if len(colours) == 0: print("Well done you guessed all the colours") else:
print(f"You guessed {7 - len(colours)} colours in the rainbow.") |
Challenge 2: Choose teams
Write a program that will let the user enter player names until 'x' is entered instead of a name. After this you must create a loop where players can be selected. The first player selected is removed from the players list and
added to the team1 list and the next to team2 with this repeating until all players have been selected. Before each player is selected you should display the list of remaining choices.
names = [] team1 = [] team2 = [] player = input("Enter the name of a player; ") while player != "x": names.append(player) player = input("Enter the
name of a player; ") turn = "team 1" for i in range(len(names)): print(f"Choose a player from: {names}") choice = input("Enter chosen player: ") names.remove(choice)
if turn == "team 1": team1.append(choice) turn = "team 2" else:
team2.append(choice) turn = "team 1" print(f"Team 1: {team1}") print(f"Team 2: {team2}") |
Challenge 3: Fair teams
Ammend the code above so that when each player is added a skill score is also requested and a list with the players name followed by skill score e.g. ["Bob",5] is appended to the names list. Instead of asking for choices, sort the
list by skill score ascending and each time through the loop take the first player from the list. You should still output the teams at the end.
names = [] team1 = [] team2 = [] player = input("Enter the name of a player; ") skill = int(input(f"Enter skill level for {player}: ")) while player != "x":
names.append([player,skill]) player = input("Enter the name of a player; ") if player != "x":
skill = int(input(f"Enter skill level for {player}: ")) names.sort(key=lambda x:x[1]) turn = "team 1" for i in range(len(names)): player = names.pop(0) if turn == "team 1":
team1.append(player) turn = "team 2" else: team2.append(player) turn = "team 1" print(f"Team 1: {team1}") print(f"Team 2: {team2}") |
<< Previous: ListsNext: Procedures >>