Use of def function

Asked

Viewed 1,647 times

2

I would like to create a function def to the first input and then return it in the third line.

Example:

def se():
    sex = input('Digite seu sexo:')

while sex != 'M' and sex != 'F':
    #não sei como se retorna esta parte: sex = input('Digite seu sexo:')

2 answers

4


def is a key word of language construction, it is not a function, it serves precisely to declare and define a function.

Your code, by posting indentation, does not do what you want, Python is indentation sensitive. So

def se():
    sex = input('Digite seu sexo:')

is the function and

while sex != 'M' and sex != 'F':

is a loose code.

What you probably want is this:

def getSex():
    while True:
        sex = input('Digite seu sexo:')
        if sex == 'M' or sex == 'F':
            return sex

print(getSex())

See working on ideone. And in the repl it.. Also put on the Github for future reference.

The return closes a function and it can optionally deliver a result to the called, as every mathematical function does (programming does not invent anything, it is all math, almost everything that is taught in school).

Of course there is much to improve on this, but the focus of the question is this.

0

The reserved word def starts the definition of a function. It must be followed by the name of the function and the list of formal parameters in parentheses. The commands that form the body of the function start at the next line and must be indented.

For example:

def fib2(n):  
    result = []
    a, b = 0, 1
    while a < n:
       result.append(a)    
       a, b = b, a+b
 return result

The Return statement terminates the execution and returns a function value. Return without any expression as argument returns None. Reaching the end of the function also returns None.

There is a very good documentation on functions on the official Python language website I’ll leave the link below:

https://docs.python.org/pt-br/3/tutorial/controlflow.html#Defining-functions

Browser other questions tagged

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