Jump to content
  • Revista PROGRAMAR: Já está disponível a edição #60 da revista programar. Faz já o download aqui!

Sign in to follow this  
lanah_

return ou print

Recommended Posts

lanah_

Eu tou tentando definir uma funcao.. qdo coloco 'print' me da um resultado (o resultado correto) e 'return' um outro resultado (errado).. Pq??

A funcao:

def file_to_dictionary(file, str):  
    ''' Given an open file that contains a unique string followed by a given
    string delimiter and more text on each line, return a dictionary that
    contains an entry for each line in the file: the unique string as the key
    and the rest of the text as the value (excluding the delimiter, and
    leading and trailing whitespace). '''
    
    input = open(file, "r")
    file_dict = {}
    for lines in input:
        if lines.startswith(str):
            file_dict[str] = lines
            print file_dict

Share this post


Link to post
Share on other sites
fnds

Porque estás a usar um ciclo, e a cada "volta" é imprimido um valor, se fizeres return a função é terminada nessa volta e devolve só esse valor. Estás a perceber?

Share this post


Link to post
Share on other sites
Tharis

Para isso existe o yield.

def funcao():
    for i in range(10):
        yield i

for i in funcao(): print i

Agora, para o teu código, em vez de print, nao metes nada e depois indentado com o código da função, metes return file_dict (mesma indent que o for).

Cumps

Share this post


Link to post
Share on other sites
Tharis
def file_to_dictionary(file, str):  
    ''' Given an open file that contains a unique string followed by a given
    string delimiter and more text on each line, return a dictionary that
    contains an entry for each line in the file: the unique string as the key
    and the rest of the text as the value (excluding the delimiter, and
    leading and trailing whitespace). '''
    
    input = open(file, "r")
    file_dict = {}
    for lines in input:
        if lines.startswith(str):
            file_dict[str] = lines
    return file_dict

print file_to_dictionary(ficheiro,string)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.