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 Respostas
+ 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