Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Logic in Python Loop

Subramanian K
Subramanian K
3,103 Points

I got the output correct. But i don't know exactly what happened here.. How i got the output.

I need you to write a for loop that goes through each of the words in hellos and prints each word plus the word "World". So, for example, the first iteration would print "Hello World".

loop.py
hellos = [
    "Hello",
    "Tungjatjeta",
    "Grüßgott",
    "Вiтаю",
    "dobrý den",
    "hyvää päivää",
    "你好",
    "早上好"
]
hello = " World"
new_string = [x + hello for x in hellos]
print(new_string)

2 Answers

Hello,

So let's start with your 1st variable. It's in list form which means we want to iterate through each entry. It appears that you recognized this and opted to use the for loop. Great!

Next, we don't actually need to create another variable to hold the " World" string. We can accomplish our goal without it.

In order to do this, we are going to use the for loop and the .format method. The .format method allows us to use the "curly braces" {} to identify where we want to place our variable.

hellos = [
    "Hello",
    "Tungjatjeta",
    "Grüßgott",
    "Вiтаю",
    "dobrý den",
    "hyvää päivää",
    "你好",
    "早上好"
]

for word in hellos:
  print("{} World".format(word))
Subramanian K
Subramanian K
3,103 Points

Thanks @Joey Guillaume. It helped me a lot.