Monday, July 20, 2020

My First Python Program

The first experiments with python was tp write a simple bit mipulation function which should show the binary presentation if a decimal number like 12 which is 0011000. Below you see the working version.


is_set = lambda argbit : bool( arg & (1<<bit) > 0)


def my_bits(args):
  result=""
  for i in range(32):
    if is_set(args,i):
      result = result + "1"
    else:
      result = result + "0"
  return result

print(my_bits(12))

it was a bit of a journey to get the code working to proeduce the expected result

PS C:\Users\49172\Projects\py> & C:/Python38/python.exe c:/Users/49172/Projects/py/src/main.py
00110000000000000000000000000000
PS C:\Users\49172\Projects\py>

The first version is looking not very dfferent but it returns a 0 and it seems that the for i loop is not completely executed  which is a bit stramge. I think the reason simply that the return ist eexecuted in the wrong scope (i a guess) terminating the for i loop premature.
is_set = lambda argbit : bool( arg & (1<<bit) > 0)


def my_bits(args):
  result=""
  for i in range(32):
    if is_set(args,i):
      result = result + "1"
    else:
      result = result + "0"
    return result

print(my_bits(12))

PS C:\Users\49172\Projects\py> & C:/Python38/python.exe c:/Users/49172/Projects/py/src/main.py
0
PS C:\Users\49172\Projects\py>
Frankly speaking i don't understand the hype about Python.