How to use a function within another function in python3?

Asked

Viewed 2,500 times

0

I wanted to take the result of the name function input and use inside the intro function, but the way I’m trying, I get just one error.

code:

def nome():
    name = str(input('Poderia nos dizer seu nome? '))
    return name

def intro():
    nome()
    print('Olá {}, seja bem vindo!'.format(name))


intro()

And this is the error I got as a result:

Erro ao executar o código descrito

I am beginner in the area,I thank you from now on.

2 answers

8


If in function nome() you returns the value read, you will need to store this value in a variable. The variable name that you set within nome() does not exist within intro(). Are different scopes.

def nome():
    name = input('Poderia nos dizer seu nome? ')
    return name

def intro():
    name = nome()
    print('Olá {}, seja bem vindo!'.format(name))


intro()

Notice that I removed the str() of input also, because this is redundant; the return of input will always be a string.

  • 1

    Thank you very much, it worked as I wanted. At the moment I have to wait to accept the answer, but as soon as possible I will.

1

For your code to work:

def nome():
    name = input('Poderia nos dizer seu nome? ')
    return name

def intro(name):
    print('Olá {}, seja bem vindo!'.format(name))

name = nome()
intro(name)

Note that the name variable is being passed as a parameter to the intro fução()

Also, python is allowed to create nested functions and your code could look like this:

def intro():
    name = nome()
    print('Olá {}, seja bem vindo!'.format(name))

    def nome():
        name = input('Poderia nos dizer seu nome? ')
        return name

# aqui a chamada da função intro
intro()

And be happy...

  • I was going to ask another question, because the way I put the code, whenever I wanted the name function within another function, I would ask to type the name again, the way you made the code works. Thank you very much! too bad I can only accept one of the answers.

Browser other questions tagged

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