Hi!

I have a beginners problem I really need some help with.
First of all, here is my current program:

def texten():
    filehandle=open ( 'savetonight.txt', 'r' )
    text=filehandle.read()
    return text

def smabokstavertext():
    texten()
    print text.lower()

I basically want my function smabokstavertext() to call the first function texten() and then print the text in lower case letters but the problem is that my function smabokstaver dosen't understand what "text" is from the first function. I thought "return text" would fix it but it didn't.

It's a real rookie-problem I know but i could really use some help.

This should work:

def texten():
    filehandle=open ( 'savetonight.txt', 'r' )
    text=filehandle.read()
    return text

def smabokstavertext():
    text = texten()
    print text.lower()

Basically, where you were calling texten, you need to create a variable to store the returned value.

So inside your texten function a local variable called 'text' is created, populated with the contents of the file and then returned.
Inside the smabokstavertext function, you now have another local variable called 'text' (this is not the same object, it is a separate object), which gets assigned the value returned by the call to the texten function.

Comments
helpful

And the whole thing does just:

with open('savetonight.txt') as f:
    print f.read().lower()

You could use global variables this way, but I don't recommend it ...

def texten():
    global text
    filehandle=open ( 'savetonight.txt', 'r' )
    text=filehandle.read()
    #return text

def smabokstavertext():
    global text
    texten()
    print text.lower()

smabokstavertext()

I assume you are experimenting with functions, so JasonHippy's approach is the way to go, since you are almost there with your return statement.

Edited 4 Years Ago by vegaseat

Actually we have to declare "text" as global only once:

def f():
    global t
    t = 567

def g():
    f()
    print t * t

g()
Comments
correct!

To not use ugly "global",a more sensible solution would be to give functions arguments.

def file_read(file_in):
    with open(file_in) as f:
        return(f.read())

def lowercase_letter(text):
    return text.lower()

afile = file_read('savetonight.txt')
print lowercase_letter(afile)

jim.lindberg1 do not use norwegian name for function.

Edited 4 Years Ago by snippsat

This question has already been answered. Start a new discussion instead.