binary = "1010" flip = "" for i in binary: if i == "0": flip+ = "1" else: flip+="0" print(flip) #output:0101 # please exp | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

binary = "1010" flip = "" for i in binary: if i == "0": flip+ = "1" else: flip+="0" print(flip) #output:0101 # please exp

Please explain

30th Oct 2021, 6:44 AM
Khalif Baby👶
Khalif Baby👶 - avatar
6 Answers
+ 6
Hi! “1010” is a string. The for loop traverse the string, element by element, from left to right. If the element is a “0”, it’s changed to a “1” and vice versa. Then the result is printed. flip += “0” means flip = flip + “0” The two strings concatenates to one string and the result is put in the variable flip, whose value is being upgraded, like: “1” + “1” becomes “11”. In every loop the lenght of the variable flip is growing, to the size is equal to the original string ”1010”. The process becomes like this: flip = ”” loop 1 -> flip = ”0” loop 2 -> flip = ”01” loop 3 -> flip = ”010” loop 4 -> flip = ”0101” So ”1010” becomes ”0101”.
30th Oct 2021, 7:06 AM
Per Bratthammar
Per Bratthammar - avatar
+ 6
That's the place where you save your other code bits Go to code section -> click "New Code" -> select language -> write code, save code And then link the saved code here.
30th Oct 2021, 11:08 AM
Lisa
Lisa - avatar
+ 5
From the top: • Initializes the output to the empty string • Looks at every character in the input string (binary), and • if the character is 0 it appends a 1 to the output string (flip) • else it appends a 0 • Then it prints the output string Does this explain, or is there something else you're looking for?
30th Oct 2021, 7:09 AM
Steve
Steve - avatar
+ 3
Hi, can you please put your code on playground instead of the heading next time?
30th Oct 2021, 9:25 AM
Lisa
Lisa - avatar
+ 1
you strictly want to use for loop to understand the background work ? or want to reverse the string simply?
30th Oct 2021, 11:13 AM
Krishnam Raju M
Krishnam Raju M - avatar
0
Lisa don't know how to do that
30th Oct 2021, 10:17 AM
Khalif Baby👶
Khalif Baby👶 - avatar