Kreidol
Kreidol

Reputation: 396

How do I call a defined procedure within another def procedure? - Python

I don't understand the basic mechanics of calling a procedure for use in defining a second one. I'm struggling to conceptualize a simple procedure calling another in trying to figure it out on my own and I've gotten to a point in my self-paced lessons where it would be useful.

Information on this is hard to find (perhaps I'm not using the right keywords) and the only examples I've seen were way too complicated for me to break down. If you have any internet literature I can read, I'll accept that.

How can I def a procedure second and call procedure first within it? I know that {} are for dictionaries, [] for lists (more or less), and () for strings (more or less) at this point.

Is there a rule I can follow? Can I call the first procedure anywhere, like in a for loop (for e in first:) or an if statement (if first:)? Having trouble conceptualizing this one. I've spent hours on this playing with the code, trying to figure it out with no luck. Please help break it down for me!

Upvotes: 0

Views: 8606

Answers (1)

petabyte
petabyte

Reputation: 1567

You can call a function nested in an if statement and you can call a function inside a loop. Nobody thinks about "rules" like these when they program. After you play around with code, it'll become second nature.

def print_hello_world(): # first function
    print "hello world"

def in_an_if_statement(): # a function that uses first func in if statement
    if 1 == 1:
        print_hello_world()

def in_a_loop(): # a function that uses first func in a loop
    for i in range(3):
        print_hello_world()

if __name__ == '__main__':
    in_an_if_statement()
    print '----'
    in_a_loop()

Upvotes: 3

Related Questions