Names Variable Code Function in Python

Names Variable Code Function in Python

Big title, right? I am about to introduce you to the function! Dum dum dah! Every programmer will go on and on about functions and all the different ideas about how they work and what they do, but I will give you the simplest explanation you can use right now. Functions do three things:

  1. They name pieces of code the way variables name strings and numbers.
  2. They take arguments the way your scripts take argv.
  3. Using #1 and #2, they let you make your own “mini- scripts” or “tiny commands.”
1 # this one is like your scripts with argv
2 def print_two(*args):
3 arg1, arg2 = args
4 print "arg1: %r, arg2: %r" % (arg1, arg2)
5
6 # ok, that *args is actually pointless, we can just do this
7 def print_two_again(arg1, arg2):
8 print "arg1: %r, arg2: %r" % (arg1, arg2)
9
10 # this just takes one argument
11 def print_one(arg1):
12 print "arg1: %r" % arg1
13
14 # this one takes no arguments
15 def print_none():
16 print "I got nothin'."
17
18
19 print_two("Zed","Shaw")
20 print_two_again("Zed","Shaw")
21 print_one("First!")
22 print_none()

Output

 arg1: 'Zed', arg2: 'Shaw'
 arg1: 'Zed', arg2: 'Shaw'
 arg1: 'First!'
 I got nothin'.

Right away you can see how a function works. This means you can make your own commands and use them in your scripts too.

Study Drills

  1. Did you start your function definition with def?
  2. Does your function name have only characters and _ (underscore) characters?
  3. Did you indent all lines of code you want in the function four spaces? No more, no less.

What’s allowed for a function name?

Just like variable names, anything that doesn’t start with a number and is letters, numbers, and underscores will work.

This feels really boring and monotonous.

That’s good. It means you’re starting to get better at typing in the code and understanding what it does. on purpose.