Python Forum

Full Version: Beginner problem, replace function with for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am new to programming with python so be gentle Blush

I'm going through the Introduction to Python on If Statements and working on a general challenge:

"Alien Points
Make a list of ten aliens, each of which is one color: 'red', 'green', or 'blue'.
You can shorten this to 'r', 'g', and 'b' if you want, but if you choose this option you have to include a comment explaining what r, g, and b stand for.
Red aliens are worth 5 points, green aliens are worth 10 points, and blue aliens are worth 20 points.
Use a for loop to determine the number of points a player would earn for destroying all of the aliens in your list."

It included this hint too:
"After you define your list of aliens, set a variable called current_score or current_points equal to 0.
Inside your for loop, write a series of if tests to determine how many points to add to the current score.
To keep a running total, use the syntax current_score = current_score + points, where points is the number of points for the current alien."


Despite the hint, I'm rather lost how to continue even with the hint. Instead, the best I could do was this using a function for each color aliens and their sum (below). Can someone point me in the right direction? Using for loops and if statements to produce this kind of result is what I'm lost on. Thanks for reading.

aliens = ['gobblegorp','andremodes','palpazar','schleem','thonbar', 'arachnio','urfur', 'vertos', 'auther','holik'] red_aliens = aliens[0:4] green_aliens = aliens[4:7] blue_aliens = aliens[7:-1] red_score = (len(red_aliens) * 5) green_score = (len(green_aliens) * 10) blue_score = (len(blue_aliens) * 20) print('The red aliens worth 5 pts each:') for reddies in red_aliens: print(reddies.title()) print('\nThe green aliens worth 10 pts each: ') for greens in green_aliens: print(greens.title()) print('\nThe blue aliens worth 20 pts each:') for blues in blue_aliens: print(blues.title()) def alien_scorer(score): score = red_score + green_score + blue_score print("\nHere is the score from the reds: ") print(red_score) print("\n...from the reds and greens: ") print(red_score + green_score) print("\n...And from all red, green, and blues : ") print(score) alien_scorer(aliens)
I think you are overthinking it
aliens list should have just elements 'red', 'green' and 'blue' (i.e. different number(e.f. 2 red, 3 green, 5 blue)
then loop over it and use if-elif block to check what color is and how many points to add
from random import choice names = ['gobblegorp','andremodes','palpazar','schleem','thonbar', 'arachnio','urfur', 'vertos', 'auther','holik'] colors = 'red green blue'.split() points = {'red': 5, 'green': 10, 'blue': 15} aliens = [{'name': alien, 'color': choice(colors)} for alien in names] # now aliens is a list with dicts, where name and color are attributes # generator expression as argument of the function call sum total_points = sum(points[alien['color']] for alien in aliens) print('Total:', total_points) # written as a classical for-loop total_points = 0 for alien in aliens: color = alien['color'] alien_points = points[color] total_points += alien_points print('Total:', total_points)
If you run this program, you get always different results, because of the random.choice from colors.
A more concise style for writing the loop below:

list_of_aliens = [ {'name': 'name_1', 'color': 'red', 'points': 5}, {'name': 'name_2', 'color': 'blue', 'points': 10}, {'name': 'name_3', 'color': 'blue', 'points': 10}, {'name': 'name_4', 'color': 'green', 'points': 20}, {'name': 'name_5', 'color': 'red', 'points': 5}, {'name': 'name_6', 'color': 'green', 'points': 20}, {'name': 'name_7', 'color': 'blue', 'points': 10}, {'name': 'name_8', 'color': 'red', 'points': 5}, {'name': 'name_9', 'color': 'blue', 'points': 10}, ] sum([alien['points'] for alien in list_of_aliens])
Basically, we initialize a list of dictionary objects for each alien, with the points baked into each alien entry. The for loop iterates over the list of dictionaries and returns a list with the points for each alien ... .we pass in this list to the sum() function to sum up the total points.

If you want to get the points for just the red aliens, you would do this:
sum([alien['points'] for alien in list_of_aliens if alien['color']== 'red'])
(Sep-11-2019, 01:38 PM)buran Wrote: [ -> ]then loop over it and use if-elif block to check what color is and how many points to add
You're right, I can tell I'm overthinking things. Can you give some example code of what the for loop and if-elif block would look like? I have learned a lot through other responses, but I'm trying to understand the most basic answer that the challenge is asking for.
(Sep-12-2019, 02:14 AM)Motley_Cow Wrote: [ -> ]Can you give some example code of what the for loop and if-elif block would look like?
I would suggest that first you try create some code yourself, based on what you have learned so far in class and then we can discuss.
You have demonstrated you can create list, and loop over it. try to make next step and introduce if/elif/else block in the loop body
I'm self-study and not in a class. Thank you for the encouragement. Will do, I'll work on it.
(Sep-12-2019, 06:48 AM)buran Wrote: [ -> ]introduce if/elif/else block in the loop body
Ok I've managed to create a for loop with an if/elif block nested within (below). However, the way that I've implemented "current_score + points" gives the point value for each alien instead of a running total like the question asks for.

aliens = ['red', 'red', 'red', 'red', 'red', 'blue', 'blue', 'blue', 'green', 'green'] current_score = 0 for alien in aliens: if alien == 'red': print(current_score + 5) elif alien == 'blue': print(current_score + 10) elif alien == 'green': print(current_score + 20) 
to get total score, print just once at the end

aliens = ['red', 'red', 'red', 'red', 'red', 'blue', 'blue', 'blue', 'green', 'green'] current_score = 0 for alien in aliens: if alien == 'red': current_score = current_score + 5 elif alien == 'blue': current_score += 10 # this is alternative, same as current_score = current_score + 10 elif alien == 'green': current_score += 20 print(f'Total score: {current_score}') # this is using f-string that require python 3.6+
That said, normally one will use dict instead of huge if/elif/else block (look at @DeaD_EyE example) or read https://python-forum.io/Thread-if-struct...dictionary
Understood, thanks for the guidance and help with new notation.