Python Programming 8

So, you've been coding a lot haven't you. You've been making your code pretty complex. A long the way you may have committed a coding sin with out realizing it. DRY KISS. That's right. You could have DRY KISS'd and that would be bad. Don't Repeat Yourself and Keep It Simple Stupid.

Basically, if you ever find yourself writing the same block of code over and over again to complete similar tasks, you should use functions. Take a look at this code here:

def sum_it_up(a,b):

____return a+b

x = sum_it_up(99,22)

print(x)

This will print 121. So theres a lot of new stuff going on here. Obviously 99+22 is 121 and that's easy. When we declare 'def' we are saying the variable that follows is now a function. A function is basically a block of code that we stow away for later and can call out when we need it. We can pass it parameters that will act with the code inside the function to make what we are doing relevant to that section of our program.

Let's break this down. By declaring def, we said 'sum_it_up' will be our new function. We must wrap our new function with parenthesis which we have the option to place parameters in. Parameters are variables that we can use inside the function that we are gathering from outside the code. So we created two variables, a and b. Then we return a+b back to the code outside the function so that when its done we can use the values computed.

Let's try another example (code will only get longer):

names = ["tom", "joe", "luke", "michael", "james", "malcolm"]

def check_name(name, set):

____if name.lower() in set:

||||||||printed = "This name is in the list of names"

____else:

||||||||printed = "This name is not in the list of names"

____return printed

print check_name("James", names)

This is an example of a function which takes a name and a list and determines whether or not that name is in the list. Then it also returns a comment on whether or not the list has the name. This is a good chunk of code which may be often repeated. It would be a shame to have to copy and paste this repeatedly and that's why it works well as a function. Whenever we need to use the function again, we simple write 'check_name()' with a new set of parameters to pass in.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Video tutorials Video 1 Video 2


Develop the most useful function you can. Make it long, helpful, maybe crazy and show your classmates.

results matching ""

    No results matching ""