Improving programs by using FUNCTIONS
Q: Why?
A:
To be able to reuse the code multiple times.
To make the program easier to read.
To organize the many lines of code.
Q: How?
A:
By keeping together related instructions in groups or blocks.
By writing a “driver“ of instructions.
Parts of a good-style program:
1. Header
2. Imports
3. Functions
4. Driver: main
5. Input/output as comment
Let’s look at a general outline:
##################################### # Imports ##################################### ##################################### # Author's name # Assignment description # Python version # Date ##################################### ##################################### # Functions ##################################### def one(): # something def two(): # something else ####################################### # Driver: control the flow of execution ####################################### # main one() two()
Here is a working example:
##################################### # G. Elia # YI_GreetingFunct.py # Greeting program with functions # Python version 3.4 # Date 10/22/15 ##################################### ##################################### # Functions ##################################### def welcome(): # something name = input("What is your name? ") print ("Hi ", name, "! Nice to meet you ") def howRU(): # something else feeling = input(" How are you? ") print ("Did you say you are are feeling ", feeling, "? ") ####################################### # Driver: control the flow of execution ####################################### # main welcome() howRU()
Another way to use a function
##################################### # G. Elia # YI_WeeklySchedule.py # My weekly activities # Python version 3.4 # Date 10/22/15 ##################################### ##################################### # Functions ##################################### def morning(day): if day.startswith("M") or day.startswith("W"): print ("Come to school early morning for extra help ") elif day.startswith("Tu") or day.startswith("Th"): print ("Go to the weight room early morning to exercise ") def afternoon(day): if day.startswith("M") or day.startswith("W"): print ("Swimming right after school ") elif day.startswith("Tu") or day.startswith("Th"): print ("Club meeting in room 242 right after school ") ####################################### # Driver: control the flow of execution ####################################### # main morning("Monday") afternoon("Monday") morning("Tuesday") afternoon("Tuesday") ##>>> ##Come to school early morning for extra help ##Swimming right after school ##Go to the weight early morning room to exercise ##Club meeting in room 242 right after school ##>>>