Problems with using Return

Asked

Viewed 70 times

1

My code:

def a():
       print(1 + 1)
       n = input()
       print(2)

I don’t know how to return only the "n" out of the function to use it with an "if". Ex.:

if n in ...

1 answer

1


I believe you want to do this:

def foobar():
    print(1 + 1)
    n = input()
    print(2)
    return n # retona aqui

bar = foobar() # Pega o valor de n e coloca na variável baz

print(baz) # exibe baz

if baz in ...: # Aqui iria a sua if

In another example, as your comment

I added 2 re-turns one for when everything is right and the s is less than 8 and one return None which is for chance occurs to return more than 8

# -*- coding: utf-8 -*-

# tudo que estiver indentado esta dentro do escopo da "função"
def begin():
    s = []

    for c in range(0,4):
        s.append( int( input() ) )

    if sum(s) < 8:
        print('Error 01: Invalid Input. Type other 4 numbers.')
        return None # <--- Aqui tem um RETURN dentro da IF, retorna None em caso de erro

    return s # <--- Aqui tem um RETURN fora da IF, termina a "função" e retorna o valor para quem a chamou

# retornou um chamada e setou para foo
foo = begin()

# retornou um chamada e setou para bar
bar = begin()

print(foo) # exibe o valor da variável foo
print(bar) # exibe o valor da variável bar
  • I made changes to the code, can you explain to me how I would return the "s", only again out of function, in this case? def Begin(): s = [] for c in range(0,4): s. append ( int(input()) ) if sum(s) < 8: print('Error 01: Invalid Input. Type other 4 Numbers.') Begin() Begin()

  • And I’m sorry, but I don’t know how to put the code correctly in the comments.

  • @Lucassouza I edited the answer, see if this is what you want

  • Is giving identation error on the part of "Return s".

  • @Lucassouza edited again and revised the spaces I took and added the utf8 because of the accents, copies the way this and glue in a new document with nothing and tries to execute.

Browser other questions tagged

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