0
binary = "1010" flip = "" for i in binary: if i == "0": flip+ = "1" else: flip+="0" print(flip) #output:0101 # please exp
Please explain
6 Respuestas
+ 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”.
+ 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.
+ 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?
+ 3
Hi, can you please put your code on playground instead of the heading next time?
+ 1
you strictly want to use for loop to understand the background work ? or want to reverse the string simply?
0
Lisa don't know how to do that