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 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β.
+ 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