Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (Retired) Putting the "Fun" Back in "Function" Functions

Needing help understanding functions and how to use the def command.

Needing help with how to use the def command in a if else statement as well well as under standing functions. Thank you for taking the time to help me.

1 Answer

Dylan Shine
Dylan Shine
17,565 Points

Hi Luke,

Think of functions are just a collection of statements.

If I wanted to print your first and last name, I could have two separate statements:

print("Luke")
print("Chulack")

or I could put both of them in one function that would call them both, one after the other:

def printName:
    print("Luke")
    print("Chulack")

Conditional statements, that consist of if, else if and else allow control flow through your programs.

Think of it like this:

name = "Luke"
if name == "Luke":
    print("It's Luke")
else if name == "Dylan":
    print("It's Dylan")
else:
    print("It's not Luke or Dylan")

We set a variable name equal to a string, "Luke" and run it through our conditionals. If name is equal to "Luke", print "It's Luke". If that's not true, If name is equal to "Dylan", print "It's Dylan". If both of those aren't true, print "It's not Luke or Dylan".

This is a simple yet very powerful feature of programming as it allows our programs adapt and maintain different states.

When you use define a function with def outside a class definition, it is considered a function. Functions in Python are first class objects, which means you can:

When you define a function within a class, it is know as a method. Example:

The String class has a method upper, that uppercases each character.

var name = "Dylan"
name.upper() #=> "DYLAN"

You call (or invoke) a function with parentheses, if you forget to tack on parens while trying to call a function, you will be returned the function object.

Hope that helps,

Dylan

Thank you vary much i now understand

Jen C
Jen C
8,695 Points

This is such a helpful answer! Thank you!