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 trialFerenc Vámos
5,047 PointsCommas or plus signs in print
Both of the for ... in loops return the same output, but the test only accepts the plus sign version.
Why is that the case? What is the difference between using a comma or a plus sign other than the fact that the comma has a "builit-in" empty character in it?
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
# Your code here
for continent in continents:
print("* " + continent)
for continent in continents:
print("*", continent)
2 Answers
Steven Parker
231,275 PointsThere is no difference in regards to the final output. Either of your loops will pass the challenge by itself.
But you can only have one of them, pick one and remove the other.
Sean T. Unwin
28,690 PointsThe Challenge is verifying that there is a newline('\n
') at the end of each print()
statement.
Using the +
for String concatenation, automatically adds a newline to each output of print()
, which is to say when there is only a single argument for print()
.
print()
using commas, which is to say to pass multiple arguments, does not do this for us. Luckily there are two (2) special parameters with names that we can pass here: 1. sep
for separator, such as a hyphen between strings, 2. end
for a suffix to append to the end of the output.
Another point of interest is that with the comma usage, every comma-separated string has a default to add a space between the comma-separated strings, unless specified otherwise with the sep
parameter.
To get the comma usage to work correctly, we need to use the end
parameter and set it to a newline.
e.g.
print("*", continent, end='\n')
Steven Parker
231,275 PointsBy default, the "print" statement adds a newline at the end whether you give it one argument or several., so:
print("*", continent, end='\n') # these lines both do exactly the same thing
print("*", continent)
Sean T. Unwin
28,690 Points@stevenparker Huh, when I initially tried the Challenge failed, but I just tried again and it passed.
My mistake then regarding the newline.