how to return an integer in python? - Python

Asked

Viewed 227 times

2

I’m new to python and I have a question about how to return 0 or 1 instead of True and False. Even putting int the output is being "[False, True, False, True, False, False, True, False]"

a="101001"

def p_not(a):
  b=[]
  for i in range(6):
    b.append(not(int(a[i])))

return b
  • Remove the not that should give the exit you expect.

  • this way will not deny the values of "a", I would like the output to be "010110"

  • It makes sense, and important information, so just try the conversion again to int: int(not(int(a..

  • Still, I think I’d write something like: map(lambda x: 1 if x == '0' else 0, a).

1 answer

3


The problem is that you had to convert the boolean value again to integer. See this code below:

a = "101001"

def p_not(a):

    b = []

    # Talvez você não saiba disso, mas você pode iterar strings.
    # Cada elemento de uma string, lista, tupla e outros serão passados para value.

    for value in a:

        # Converte o valor de string para inteiro, depois converte para booleano
        # devido a utilização do "not". Após isso, o valor é convertido 
        # para inteiro novamente.

        value_b = int(not int(value))

        b.append(value_b)

    return b

print(p_not(a)) # Saída: [0, 1, 0, 1, 1, 0]

The conversion of bool for int is the following:

int( False ) == 0
int( True ) == 1

Using the map():

We can greatly decrease the size of the code using the function map. This function takes as a parameter a function that must contain a parameter and an iterable ( strings, lists, tuples, among other strings ).

I do not recommend for the moment that you write the code this way because it is a bit advanced since you are a beginner in the language, but it is a much more practical way to do.

a = "101001"

def p_not(a):

    result = map(lambda x: 0 if int(x) else 1, a)
    return list(result)

print(p_not(a))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.