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

renee
renee
4,382 Points

Hello, I'd like to know why these two codes produces a different output.

hellos = [ "hello", "bonjour", "hola"]
for hi in hellos:
... print(hi + " World!")
...
hello World!
bonjour World!
hola World!

hellos = [ "hello", "bonjour", "hola"]
for hi in hellos:
... print("hi" + " World!")
...
hi World!
hi World!
hi World!

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

4 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! It's because when you make a for loop, the first item is a local variable name for each individual item in that list you're iterating through. In your first example, the first iteration has the variable hi set to equal the first item in the list which is the string literal "hello". You print out the value stored in the hi variable plus the string literal " World!".

In your second example, the variable hi is still set to be the value of each individual item you're looking at. But you're not printing out the value of hi, you're printing out the string literal "hi".

Hope this clarifies things! :sparkles:

Chris Jones
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Chris Jones
Java Web Development Techdegree Graduate 23,933 Points

Hi Renee,

You aren't passing the names variable into the print function like you did in the first script you referenced. Instead you passed a string literal, "hellos". You want to pass the variable names into the print function instead.

Let me know if that solves it!

Bill Fox
Bill Fox
392 Points

In the first example, you are iterating through the hellos list and printing each item in the list followed by the string " World!" In the second example your use of quotes (python doesn't care whether you use single or double quotes) means you are printing the string "hi" followed by the string " World!"

renee
renee
4,382 Points

Thank you so much everyone!