Python for Beginners (Lesson 4)

From EventScripts Community Encyclopedia


Tutorial: Python for Beginners (Lesson 4)

Requires: ES (Not needed)
Difficulty: Easy
Author: Saul Rennison
Contributors: ~
Length: ~

Tutorial Overview

Table of Contents

Contents

Description

Previous Lesson: Lesson 3
Next Lesson: Lesson 5

Last lesson I said that we would delve into purposeful programming. Also we will be using user inputs, and user inputs require a thing called functions if you wish to use them complexy (is that a word?)

What are functions? Well, in effect, functions are little self-contained programs that perform a specific task, which you can incorporate into your own, larger programs. After you have created a function, you can use it at any time, in any place. This saves you the time and effort of having to retell the computer what to do every time it does a common task, for example getting the user to type something in.

Tutorial Content

Using a function

Python has lots of pre-made functions, that you can use right now, simply by calling them. Calling a function involves you giving a function input if the function requires parameters, and it will return a value (like a variable would) as output (if it returns a value). Don't understand? Here is the general form that calling a function takes:

function_name(parameters)

See? Easy.

  • Function_name identifies which function it is you want to use (You'd figure...). For example, the function raw_input, which will be the first function that we will use.
  • Parameters are the values you pass to the function to tell it what is should do, and how to do it. For example, if a function multiplied any given number by five, the stuff in parameters tells the function which number it should multiply by five. Put the number 70 into parameters, and the function will do 70 x 5, then return the answer.

Parameters, Returning Values and Communicating with Functions

Well, that's all well and good that the program can multiply a number by five, but what does it have to show for it? A warm fuzzy feeling? Your program needs to see the results of what happened, to see what 70 x 5 is, or to see if there is a problem somewhere (like you gave it a letter instead of a number). So how does a function show what is does?

Well, in effect, when a computer runs a function, it doesn't actually see the function name, but the result of what the function did. Variables do the exact same thing - the computer doesn't see the variable name, it sees the value that the variable holds. Lets call this program that multiplied any number by five, multiply(). You put the number you want multiplied in the brackets. So if you typed this:

a = multiply(70)

The computer would actually see this:

a = 350

Note: Don't bother typing in this code -- multiply() isn't a real function, unless you create it.

The function ran itself, then returned a number to the main program, based on what parameters it was given.

Now let's try this with a real function, and see what it does. The function is called raw_input, and asks the user to type in something. It then turns it into a string of text. Try the code below:

# this line makes 'a' equal to whatever you type in
a = raw_input("Type in something, and it will be repeated on screen:")
# this line prints what 'a' is now worth
print a

Say in the above program, you typed in 'hello' when it asked you to type something in. To the computer, this program would look like this:

a = "hello"
print "hello"

Remember, a variable is just a stored value. To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running.

A Calculator program

Lets write another program, that will act as a calculator. This time it will do something more adventerous than what we have done before. There will be a menu, that will ask you whether you want to multiply two numbers together, add two numbers together, divide one number by another, or subtract one number from another. Only problem - the raw_input function returns what you type in as a string - we want the number 1, not the letter 1 (and yes, in python, there is a difference.).

Luckily, somebody wrote the function input, which returns what you typed in, to the main program - but this time, it puts it in as a number. If you type an integer (a whole number), what comes out of input is an integer. And if you put that integer into a variable, the variable will be an integer-type variable, which means you can add and subtract, etc.

Now, lets design this calculator properly. We want a menu that is returned to every time you finish adding, subtracting, etc. In other words, to loop (HINT!!!) while (BIG HINT!!!) you tell it the program should still run.

We want it to do an option in the menu if you type in that number. That involves you typing in a number (a.k.a input) and an if loop.

Lets write it out in understandable English first:

START PROGRAM
print opening message

while we let the program run, do this:
    #Print what options you have
    print Option 1 - add
    print Option 2 - subtract
    print Option 3 - multiply
    print Option 4 - divide
    print Option 5 - quit program
    
    ask for which option is is you want
    if it is option 1:
        ask for first number
        ask for second number
        add them together
        print the result onscreen
    if it is option 2:
        ask for first number
        ask for second number
        subtract one from the other
        print the result onscreen
    if it is option 3:
        ask for first number
        ask for second number
        multiply!
        print the result onscreen
    if it is option 4:
        ask for first number
        ask for second number
        divide one by the other
        print the result onscreen
    if it is option 5:
        tell the loop to stop looping
Print onscreen a goodbye message
END PROGRAM

Lets put this in something that Python can understand:

"""Calculator program"""
 
loop = 1 # 1 means loop; anything else means don't loop.
choice = 0 # This variable holds the user's choice in the menu
 
while loop == 1:
    # Print what options you have
    print "Welcome to calculator.py"
 
    print "your options are:"
    print " "
    print "1) Addition"
    print "2) Subtraction"
 
    print "3) Multiplication"
 
    print "4) Division"
    print "5) Quit calculator.py"
    print " "
 
    choice = int(raw_input("Choose your option: ").strip())
    if choice == 1:
        add1 = input("Add this: ")
        add2 = input("to this: ")
        print add1, "+", add2, "=", add1 + add2
    elif choice == 2:
        sub2 = input("Subtract this: ")
        sub1 = input("from this: ")
        print sub1, "-", sub2, "=", sub1 - sub2
    elif choice == 3:
        mul1 = input("Multiply this: ")
        mul2 = input("with this: ")
        print mul1, "*", mul2, "=", mul1 * mul2
    elif choice == 4:
        div1 = input("Divide this: ")
        div2 = input("by this: ")
        print div1, "/", div2, "=", div1 / div2
    elif choice == 5:
        loop = 0
	
print "Thank-you for using calculator.py!"

Wow! That is an impressive program! Paste it into python IDLE, save it as 'calculator.py' and run it. Play around with it -- try all options, entering in integers (numbers without decimal points), and floats (stuff after the decimal point). Try typing in text, and see how the program chucks a minor fit, and stops running (that can be dealt with, using error handling, which we can address in Lesson 10.)

Define your own functions

Well, it is all well and good that you can use other people's functions, but what if you want to write your own functions, to save time, and code. Maybe use them in other programs? This is where the def operator comes in. If you don't know, an operator is just something that tells python what to do. For example, the + operator tells Python to add things, the if operator tells Python to do something if conditions are met, etc.

The basics of a function:

# Remember to put a colon ":" at the end of any line that starts with an operator,
# in this case, use the : as we are using the "def" operator.
def function_name(<parameters go here>):
    <code of the function goes here>
 
    return <value to return from the function (optional)>

function_name is the name of the function. You write the code that is in the function below that line, and have it indented. The code indented is the code that is ran when you do function_name(). This function also returns a value. This is what your program gets from the function, if you wish to do something like:

hello = function_name()

The hello variable will be what function_name returned.

A function is like a miniture program that some parameters are given to, it then runs itself, and then returns a value (OPTIONAL). Your main program sees the value it returned. Here is a function that prints the words "hello" onscreen, and then returns the number 1234 to the main program:

# Below is the function
def hello():
    print "hello"
    return 1234
 
# And here is the function being used
print hello()

Think about the last line of code above. What did it do? Type in the program (you can skip the comments), and see what it does. The output looks like this:

The output: hello 1234

So what happened? 1. When def hello() was ran, a function called 'hello' was created 2. When the line 'print hello()' was ran, the function 'hello' was executed (The code inside it was run) 3. The function hello printed "hello" onscreen, then returned the number '1234' back to the main program 4. The main program now sees the line as 'print 1234' and as a result, printed '1234'.

Passing parameters to functions

There is one more thing we will cover in this lesson is passing parameters to functions. Think back to how we defined functions:

def function_name(<parameters go here>):
    <code of the function goes here>
 
    return <value to return from the function '''(optional)'''>

Where <parameters go here> is (inbetween the parentheses), you put the names of variables that you want to put the parameters into. For example:

# Define the function
def function_name(parameter1, parameter2):
	print parameter1
	print parameter2
 
# Now call the function
function_name("hello", "world")

The output would be: hello world

There is no limit to how many parameters you can have in a function, or the name of them, you can put as many as you need, just have them seperated by commas.

Here is a basic adding function:

# Define the function
def add(value1, value2):
	return value1 + value2
 
# Call it
print add(1, 2)

The output would be: 3

The basics of the above function is, parameter 1 (value1) is being added to parameter 2 (value2) and then being returned to the program. The print function then prints the return value of the add function we made.

Conclusion

That covers functions and parameters and other crap, next lesson we will be doing "Lists, Tuples and Dictionaries", three of the main multiple value data storage datatypes in Python.

(That last sentence did not make sense)

Thanks for reading

blog comments powered by Disqus