I try to run a python function and it returns me None

Asked

Viewed 284 times

2

Sorry if my question seems silly I’m still novice but it’s the following, I created a python function that should return me a list with this character in "~". Here is the function:

def escreva(texto):
   lista = []
   cont = 0
   while cont < len(texto)
     lista = ['~']
     cont += 1


a = str(input('Entre com o texto'))
print(a)
print(escreva(a))

I want this list to be the size of the text that was typed only when I run the program it shows me the typed string and the word None :

String (O texto qualquer que eu digitei e mandei printar)
None

I wonder why it returns me the word None and how could I make this list look the size of the text.

1 answer

4

There are some problems in your code.

First, you’re not using the keyword return to specify the variable and the value to be returned by the function, simply add to your code:

return lista

Second, even adding the return your program will return a list with only one element which is the ~, because you use the = to reassign the vector to its list variable:

['~']

To correct use the method append, see here. Look at the code:

def escreva(texto):
    lista = []
    cont = 0

    while cont < len(texto):
        lista.append('~')
        cont += 1
    return lista

a = str(input('Entre com o texto:'))
print(a)
print(escreva(a))

Entree:

text

Exit:

['~', '~', '~', '~', '~']

Also no need to convert the value returned by the function input because it already returns a string, do:

a = input('Entre com o texto:')

Read about the function input.

  • Could also use list comprehension return ["~" for _ in texto] or even (if you don’t need to check any value) simply return ["~"] * len(text)

  • Yeah, but I followed his logic :)

Browser other questions tagged

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