[BEGINNER LEVEL] Simple Python Question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[BEGINNER LEVEL] Simple Python Question

Hi guys, I would like to ask why: print(3*('a'+" "+'b')) = a ba ba b Can someone please explain this to me. Thank you.

15th Jul 2019, 9:05 AM
David Brent
David Brent - avatar
6 Answers
+ 7
print(3*('a'+" "+'b')) = a ba ba b ('a'+" "+'b') gives 'a b' 3* repeates 'a b' 3 times so it gives: 'a ba ba b'
15th Jul 2019, 9:27 AM
Lothar
Lothar - avatar
+ 3
its not a bug. if you want is a as variables, declare the variable first, and call it like this 3*(a+b) not ('a' + ' ' + 'b')
15th Jul 2019, 10:50 AM
ShortCode
+ 2
'a' + " " + 'b' will results in "a b" so 3 * "a b" -> a ba ba b (unless you put additional space behind it will be a b a b a b)
15th Jul 2019, 10:39 AM
ShortCode
+ 2
Btw multiplication for strings will results like copying it 3 times
15th Jul 2019, 10:54 AM
ShortCode
0
I tried 3*(a+b) its result is ab ab ab as it first calculates a+b then multiplies to 3. I am confused how 3*(a b) became a ba ba b I am thinking what multiplication properties applied in this equation. Or thinking this is a bug? BTW. Thanks guys.
15th Jul 2019, 10:47 AM
David Brent
David Brent - avatar
0
I am aware that multiplying strings results copying it n times. 3*(' '+'a'+' '+'b')=3*(' a b')= a b a b a b 3*(' '+'a'+'b')=3*(' ab')= ab ab ab 3*('a'+'b') = 3*('ab')=ababab But I am really confused how: 3*('a' + ' ' + 'b') = 3*('a b') = a ba ba b Can you (someone) elaborate how this happen?
15th Jul 2019, 11:18 AM
David Brent
David Brent - avatar