Can anyone explain Why/How this code below get number from 0 to 100
[Code]
print(*range(*b'e'))
[Result]
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
CodePudding user response:
You can look at something like this 'from the inside out':
'e'
would just be the letter "e" in a string. However, when pre-fixed with a b
as in b'e'
, it defines a byte sequence, which is just a series of raw bytes, not encoded characters like in a string.
You can use the unpack operator *
on a byte sequence to obtain the integer values of the individual bytes, for example [b'e']
would evaluate to [101]
, because the letter "e" has ascii value 101, so b'e'
really just means "create a byte sequence with only the byte with decimal value 101".
If you pass the unpacked byte sequence to a range, as it only has one value, you're getting the equivalent of range(101)
from range(*b'e')
.
A sequence like a range can also be unpacked, obtaining the individual values from the range in order, and that's what happens on the outside - all values from the range are unpacked and passed as parameters to the print()
function.
So that's why print(*range(*b'e'))
prints the numbers from 0 to 100. Of course, you'd only ever write it like this to teach someone something about Python. It's terrible code.
CodePudding user response:
b'e'
is a one element bytes array (8-bit numbers) containing the binary representation of the letter 'e'. This happens to be the number 101 (ord('e') --> 101
).
So, range(*b'e')
is like range(*[101])
. The * unpacks the one-element array to a single parameter for the range function resulting in range(101)
.
The other * is simply unpacking the output of range(101) as 101 parameters to the print function. like print(*range(101))
or print(0,1,2,3,4,...,99,100)