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.

commented: helpful +7

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.

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

def f():
    global t
    t = 567

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

g()
commented: correct! +12

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.

Bump on snippsat's reply...

That is almost certainly the way to do it if you ask me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.