Motivating example· Happy Birthday lyrics...def main():print "Happy birthday to you!"print "Happy birthday to you!"print "Happy birthday, dear Fred..print "Happy birthday to you!"·Remove duplicates:def happy() :print "Happy birthday to you!"Xiaojuan Cai6Computational Thinking
Xiaojuan Cai Computational Thinking 6 Motivating example • Happy Birthday lyrics. def main(): print "Happy birthday to you!" print "Happy birthday to you!" print "Happy birthday, dear Fred." print "Happy birthday to you!" • Remove duplicates: def happy(): print "Happy birthday to you!
Motivating exampleUsing parameters:def sing(person):happy ()happy ()print "Happy birthday, dear", person+"happy ()A paramateris a variable that is initializedwhen the function is called.Xiaojuan CaiComputational Thinking
Xiaojuan Cai Computational Thinking 7 Motivating example • Using parameters • def sing(person): happy() happy() print "Happy birthday, dear", person + ".“ happy() • A paramater is a variable that is initialized when the function is called
The function of functions: Having similar or identical code in more than oneplace has some drawbacks:.writingthe same codetwice ormore.: this same code must be maintainedintwo separate places. Functions can be used to reduce code duplicationand make programs more easily understood andmaintained.8Xiaojuan CaiComputational Thinking
Xiaojuan Cai Computational Thinking 8 The function of functions • Having similar or identical code in more than one place has some drawbacks: • writing the same code twice or more. • this same code must be maintained in two separate places. • Functions can be used to reduce code duplication and make programs more easily understood and maintained