+ 2

For confusement

im slow to learn programming.however i will try harder! but...again,confusement always block me. words = ["hello", "world", "spam", "eggs"] for word in words: print(word + "!") why its not print hello!,world1,spam!,eggs! instead hello! world! spam! eggs! ?

16th Jul 2017, 2:04 PM
Kevin AS
Kevin AS - avatar
4 Answers
+ 7
print *always* adds a new line after each, so each will be on a separate line. Also, each is being printed separately, so it isn't just like printing the whole list where the elements will be separated with commas. *print does not always add a new line, but for your purposes as a beginner, just know that it automatically does that if no other args are present.
16th Jul 2017, 2:06 PM
J.G.
J.G. - avatar
+ 9
It's not hard at all to learn more accuratly the behaviour and use of print() function ;) print() can handle a named parameter 'end' which default value is the new line char ('\n')... you can change thus default setting by explicitly pass another value to this named parameter: print(42,end='') print(42) ... will output: 4242 ... while: print(42,end=',') print(42) ... will output: 42,42
16th Jul 2017, 2:16 PM
visph
visph - avatar
+ 7
@OUMAS Abdellah: Better to do: print('{}!{}!{}!{}!'.format(var0,var1,var2,var3)) ... because the way you suggest handle only string type values, as Python print() function doesn't implicitly downcast in string concanetation, while .format method will ^^
16th Jul 2017, 2:33 PM
visph
visph - avatar
+ 5
one of many solutions would be to write a one line code like this : print(words[0] + "!" + words[1] + "!" + words[2] + "!" + words[3] +"!");
16th Jul 2017, 2:19 PM
OUMAS Abdellah
OUMAS Abdellah - avatar