Functions. Learning Outcomes 10/1/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17

Size: px
Start display at page:

Download "Functions. Learning Outcomes 10/1/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17"

Transcription

1 Functions CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Adapted from slides by Sue Evans et al. 2 Learning Outcomes Understand why programmers divide programs up into sets of cooperating functions. Have the ability to define new functions in Python. Understand the details of function calls and parameter passing. Understand the distinction between functions, procedures and predicate functions. 3 1

2 What Are Functions? Functions define segments of code, similar to a subprogram Functions can be called at any time in a program Functions are generally useful when you need to repeatedly use a segment of code 4 What Are Functions? Functions in programming are analogous to functions in math such as f(x) = 2x We have actually used functions previously from the Python Modules such as math.sqrt(x) In this case sqrt is the name of a function defined in the math module 5 Why Use Functions? Two main purposes: Reuse: Can be called many times within a program Can be reused and called from other programs Validated once, used many times Modularity Embodies top-down design Decompose a large task into a sequential series of smaller tasks Decompose a task into a hierarchy of subtasks 6 2

3 Review of Top-Down Design Involves repeatedly decomposing a problem into smaller problems Eventually leads to a collection of small problems or tasks each of which can be easily coded The function construct in Python is used to write code for these small, simple problems. Functions A Python program is made up of one or more functions, one of which is usually main( ). Execution by convention begins with main( ) When program control encounters a function name, the function is called (invoked). Program control passes to the function. The function is executed. Control is passed back to the calling function. Sample Programmer-Defined Function import string def PrintMessage ( ): # A very simple function print A message for you:\n\n ) print Have a nice day!\n ) return 0 def main ( ): PrintMessage ( ) 3

4 Examining printmessage import string def PrintMessage (): # A very simple function print A message for you:\n\n print Have a nice day!\n return 0 function header function body function definition def main ( ): PrintMessage ( ) function call The Function Call Passes program control to the function Must match the function definition in number of arguments, and their purpose def PrintMessage () : def main ( ): same name no arguments PrintMessage ( ) The Function Definition Control is passed to the function by the function call. The statements within the function body will then be executed. def PrintMessage ( ): print A message for you:\n\n print Have a nice day!\n After the statements in the function have completed, control is passed back to the calling function, in this case main( ). (Note that the calling function does not have to be main( ).) 4

5 A Song-singing Program Let's write a program that "sings" Old MacDonald's Farm: # Filename: farm1.py # Written by: Sue Evans # Date: 7/31/09 # Section: All # bogar@cs.umbc.edu # # This program "sings" Old MacDonald's Farm def : print "" print "And on that farm he had a cow, Ee-igh, Ee-igh, Oh!" print "With a moo, moo here and a moo, moo there." print "Here a moo, there a moo, everywhere a moo, moo." print "" 13 A Song-singing Program Let's see if it works: linuxserver1.cs.umbc.edu[117] python farm1.py And on that farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there. Here a moo, there a moo, everywhere a moo, moo. linuxserver1.cs.umbc.edu[118] 14 A Song-singing Program Of course it works. There was nothing difficult about writing this code, except I got tired of typing "Ee-igh, Ee-igh, Oh!" So whenever you find yourself typing the same code over and over again, you should make a module out of that code by putting it in a function. 15 5

6 Defining a Function Functions are defined using the following form: def <function-name>(<parameters>): <block> def is a keyword that tells the system you are about to define a function. The <function-name> is a name of your choosing and must be different than any other functions you've defined. 16 Defining a Function All function names are followed with parentheses. Inside the parentheses are the names of the variable parameters, if there are any (to be discussed later). Using the same format as if statements discussed earlier, we then use the colon, : and then the tab-indented notation to specify the code block of the function. The code block is the code that will be executed when a function is called. 17 Defining a Function The first line of a function, i.e. def <function-name>(<parameters>): is known as the function header and the block of code beneath it is known as the function body. Below we've defined a function named chorus that prints the text, "Ee-igh, Ee-igh, Oh!" def chorus(): print Ee-igh, Ee-igh, Oh! 18 6

7 Calling a Function In order to call the function and execute its code, all we do is type the function name followed by the parentheses. We can call a function as many times as we want. Let's rewrite the song using our new function 19 Calling a Function # [Filename: farm2.py [rest of formal header not shown] # chorus() prints the chorus of Old MacDonald's farm # Inputs: none # Outputs: none def chorus(): print "Ee-igh, Ee-igh, Oh!" def : print "Old MacDonald had a farm,", chorus() print "And on that farm he had a cow,", chorus() print "With a moo, moo here and a moo, moo there." print "Here a moo, there a moo, everywhere a moo, moo." print "Old MacDonald had a farm,", chorus() 20 Calling a Function Does it work correctly? linuxserver1.cs.umbc.edu[120] python farm2.py And on that farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there. Here a moo, there a moo, everywhere a moo, moo. linuxserver1.cs.umbc.edu[121] 21 7

8 Functions That Call Other Functions We can also define functions that call other functions. Since our song has a repeated line at the beginning and end of the verse, let's write a function called line(). Since the end of the line is "Ee-igh, Ee-igh, Oh!", we'll be calling the function chorus() to do that. Our program now looks like this : 22 Functions That Call Other Functions # [Filename: farm3.py [rest of formal header not shown] # chorus() prints the chorus of Old MacDonald's farm # Inputs: none # Outputs: none def chorus(): print "Ee-igh, Ee-igh, Oh!" # line() prints the repeated line of Old MacDonald's farm # Inputs: none # Outputs: none def line(): print "Old MacDonald had a farm,", chorus() # (continued next page) 23 # (continued) Functions That Call Other Functions def : line() print "And on that farm he had a cow,", chorus() print "With a moo, moo here and a moo, moo there." print "Here a moo, there a moo, everywhere a moo, moo." line() 24 8

9 Functions That Call Other Functions Be careful not to define functions with the same name, or you will overwrite the previous function definition without warning! >>> def duplicatename():... print "First Definition"... >>> duplicatename() First Definition >>> def duplicatename():... print "Second Definition"... >>> duplicatename() Second Definition 25 We're not really finished with Old MacDonald yet, because if we want to sing several verses, where each verse uses a different animal name and sound, we would either have to have a huge or write a separate function for every possible animal. Neither of the functions we wrote in the previous example had parameters. By using parameters, we can define just one function that can handle all of the animals and their sounds, one at a time : 26 # verse() prints an entire verse of Old MacDonald's farm # Inputs: animal - an animal's name # sound - the sound that animal makes # Outputs: none def verse(animal, sound): print line() print "And on that farm he had a %s," % (animal), chorus() print "With a %s, %s here" % (sound, sound), print "and a %s, %s there" % (sound, sound) print "Here a %s, there a %s," % (sound, sound), print "everywhere a %s, %s." % (sound, sound) line() 27 9

10 Notice in the parentheses following verse we included animal and sound separated by a comma--these are known as the function's parameters. animal and sound serve as variables the function can use - as we see in the line : print "And on that farm he had a %s," % (animal), 28 So, any variables specified between the parentheses in a function's definition are parameters for the function. The value of a function's parameters are assigned by evaluating the arguments when the function is called def : verse("cow", "moo") 29 In, when we called the function verse(), we gave the arguments "cow" and "moo" so the variable animal was assigned "cow" and sound was assigned "moo". The values of those variables were printed out in the song. linuxserver1.cs.umbc.edu[149] python farm4.py And on that farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there Here a moo, there a moo, everywhere a moo, moo. linuxserver1.cs.umbc.edu[150] 30 10

11 Arguments are always passed to the function in the order they are entered. In our song program, the first argument passed to the function verse will always be assigned into the function's variable named animal and the second argument passed will always be assigned into the function's variable named sound. The names of the variables don't play into this process at all, only the positions in the parameter list matter. 31 To illustrate, let's make a mistake when we call the function from. def : verse( oink", pig") 32 Here s what it produced: linuxserver1.cs.umbc.edu[107] python farm7.py And on that farm he had a oink, Ee-igh, Ee-igh, Oh! With a pig, pig here and a pig, pig there Here a pig, there a pig, everywhere a pig, pig. linuxserver1.cs.umbc.edu[108] 33 11

12 Because the arguments are always evaluated before they are passed, you can also use variables as arguments. def : ananimal = "pig" asound = "oink" verse(ananimal, asound) 34 produces the following output: linuxserver1.cs.umbc.edu[153] python farm6.py And on that farm he had a pig, Ee-igh, Ee-igh, Oh! With a oink, oink here and a oink, oink there Here a oink, there a oink, everywhere a oink, oink. linuxserver1.cs.umbc.edu[154] 35 Since we've written these functions, we can easily sing as many verses as we want with very little additional code. In fact, that additional code will be in. Here's the final edit of the program: 36 12

13 # [Filename: farm5.py [rest of formal header not shown] # # This program "sings" many verses of Old MacDonald's Farm # making use of the chorus(), line() and verse() functions. # chorus() prints the chorus of Old MacDonald's farm # Inputs: none # Outputs: none def chorus(): print "Ee-igh, Ee-igh, Oh!" # line() prints the repeated line of Old MacDonald's farm # Inputs: none # Outputs: none def line(): print "Old MacDonald had a farm,", chorus() # (continued next page) 37 # (continued) # verse() prints an entire verse of Old MacDonald's farm # Inputs: animal - an animal's name # sound - the sound that animal makes # Outputs: none def verse(animal, sound): print line() print "And on that farm he had a", animal, "", chorus() print "With a %s, %s here" % (sound, sound), print "and a %s, %s there" % (sound, sound) print "Here a %s, there a %s," % (sound, sound), print "everywhere a %s, %s." % (sound, sound) line() # (continued next page) 38 # (continued) def : verse("cow", "moo") verse("pig", "oink") verse("hen", "cluck") verse("duck", "quack") verse("cat", "meow") 39 13

14 and the output looks like this : linuxserver1.cs.umbc.edu[109] python farm5.py And on that farm he had a cow Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there Here a moo, there a moo, everywhere a moo, moo. And on that farm he had a pig Ee-igh, Ee-igh, Oh! With a oink, oink here and a oink, oink there Here a oink, there a oink, everywhere a oink, oink. And on that farm he had a hen Ee-igh, Ee-igh, Oh! With a cluck, cluck here and a cluck, cluck there Here a cluck, there a cluck, everywhere a cluck, cluck. 40 And on that farm he had a duck Ee-igh, Ee-igh, Oh! With a quack, quack here and a quack, quack there Here a quack, there a quack, everywhere a quack, quack. And on that farm he had a cat Ee-igh, Ee-igh, Oh! With a meow, meow here and a meow, meow there Here a meow, there a meow, everywhere a meow, meow. linuxserver1.cs.umbc.edu[110] 41 The code we produced is certainly preferable to the naive way to accomplish the same task : # Filename: farm1.py # Written by: Sue Evans # Date: 7/31/09 # Section: All # bogar@cs.umbc.edu # # This program "sings" Old MacDonald's Farm def : print print "" print "And on that farm he had a cow, Ee-igh, Ee-igh, Oh!" print "With a moo, moo here and a moo, moo there." print "Here a moo, there a moo, everywhere a moo, moo." print "" print 42 14

15 print "" print "And on that farm he had a pig, Ee-igh, Ee-igh, Oh!" print "With a oink, oink here and a oink, oink there." print "Here a oink, there a oink, everywhere a oink, oink." print "" print print "" print "And on that farm he had a hen, Ee-igh, Ee-igh, Oh!" print "With a cluck, cluck here and a cluck, cluck there." print "Here a cluck, there a cluck, everywhere a cluck, cluck." print "" print print "" print "And on that farm he had a duck, Ee-igh, Ee-igh, Oh!" print "With a quack, quack here and a quack, quack there." print "Here a quack, there a quack, everywhere a quack, quack." print "" 43 print print "" print "And on that farm he had a cat, Ee-igh, Ee-igh, Oh!" print "With a meow, meow here and a meow, meow there." print "Here a meow, there a meow, everywhere a meow, meow." print "" 44 A great thing about using the version with functions is that we can add new animals to the song quickly and easily. Adding one more call to the function verse() produces another whole verse with the animal and sound passed. verse("sheep", "baa") 45 15

16 Kinds of Functions When refering to functions, it is sometimes useful to differentiate them into types that depend upon what they return. functions - return values predicate functions - return booleans procedures - return nothing, or None in python Let's see an example of a predicate function. Predicate functions typically use the word is as part of their name: 46 Kinds of Functions # isprime() takes a positive integer as an argument # and returns True if that integer is a prime number # and False if the number is not prime. # Input: a positive integer, num # Output: either True or False # Assumptions: num will be an integer > 1 def isprime(num): # try to evenly divide num by all # numbers between 2 and num - 1 for i in range(2, num): # if num is evenly divisible by this # number, then it isn't prime if num % i == 0: return False # if num wasn't divisible by any of # those numbers, then it's prime return True 47 We use it Kinds of Functions def : # print primes from 2 to 11, inclusive for i in range (2, 12): if isprime(i): print i, and here s the output: linuxserver1.cs.umbc.edu[118] python isprime.py linuxserver1.cs.umbc.edu[119] 48 16

17 Kinds of Functions All of the functions we wrote for singing "Old MacDonald's Farm" are procedures. Here's one of those functions : def : # print primes from 2 to 11, inclusive for i in range (2, 12): if isprime(i): print i, Notice that the outputs say none. Outputs specify what is being returned and so it should say none. The fact that this function prints "Ee-igh, Ee-igh, Oh!" is the effect of the function, not the output. 49 Kinds of Functions If we wanted to make our function header comment more precise we could add an Effect: line; this is not a requirement. Here's the change : # chorus() prints the chorus of Old MacDonald's farm # Inputs: none # Outputs: none # Effect: prints "Ee-igh, Ee-igh, Oh!" def chorus(): print "Ee-igh, Ee-igh, Oh!" All of your homeworks and projects should contain a procedure named printgreeting(), which tells the user about the program they are about to run. 50 List Exercise In groups of 3 or 4, write a program that will print the even integers in a range that the user enters. Your program must have the following: a file-header comment function header comments for each function other than a procedure named printgreeting() a predicate function named iseven(value) don't forget to call 51 17

18 List Exercise Here s the output: Enter the starting number: 11 Enter the ending number: 21 The even numbers between 11 and 21 are:

2.5 Methods. You may have heard this song from when you were a child:

2.5 Methods. You may have heard this song from when you were a child: 2.5 Methods You may have heard this song from when you were a child: And on that farm he had a cow, EE-I-EE-I-O, With a moo moo here and a moo moo there Here a moo, there a moo, everywhere a moo moo And

More information

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions User Defined Functions In previous labs, you've encountered useful functions, such as sqrt() and pow(), that were created by other

More information

MITOCW watch?v=flgjisf3l78

MITOCW watch?v=flgjisf3l78 MITOCW watch?v=flgjisf3l78 The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality educational resources for free. To

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17 CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 1 Discussion Sections 02-08, 16, 17 Adapted from slides by Sue Evans et al. 2 Learning Outcomes Become familiar with input and output (I/O) from

More information

MITOCW watch?v=kz7jjltq9r4

MITOCW watch?v=kz7jjltq9r4 MITOCW watch?v=kz7jjltq9r4 PROFESSOR: We're going to look at the most fundamental of all mathematical data types, namely sets, and let's begin with the definitions. So informally, a set is a collection

More information

UNIT 6. Functions and Structured Programming

UNIT 6. Functions and Structured Programming UNIT 6 Functions and Structured Programming DAY 1 What is a Function? What is Structured Programming? I can.. Divide a large program into small problems. Write a Python program as a function Planning a

More information

Lecture 26: Review. CS105: Great Insights in Computer Science Michael L. Littman, Fall : Introduction

Lecture 26: Review. CS105: Great Insights in Computer Science Michael L. Littman, Fall : Introduction Lecture 26: Review CS105: Great Insights in Computer Science Michael L. Littman, Fall 2006 1: Introduction Computers are everywhere creating new capabilities. Computer science is the study of "reduction":

More information

Week - 01 Lecture - 03 Euclid's Algorithm for gcd. Let us continue with our running example of gcd to explore more issues involved with program.

Week - 01 Lecture - 03 Euclid's Algorithm for gcd. Let us continue with our running example of gcd to explore more issues involved with program. Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 03 Euclid's Algorithm

More information

Hello, World! EMT1111: Logic and Problem Solving Fall 2016 Dr. Mendoza

Hello, World! EMT1111: Logic and Problem Solving Fall 2016 Dr. Mendoza Hello, World! EMT1111: Logic and Problem Solving Fall 2016 Dr. Mendoza LESSON 6 (Labs): Python Functions FUNCTION DEFINITION AND CALLS Functions Terminology Function A piece of code that can be called

More information

MITOCW watch?v=0jljzrnhwoi

MITOCW watch?v=0jljzrnhwoi MITOCW watch?v=0jljzrnhwoi The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

Functions Structure and Parameters behind the scenes with diagrams!

Functions Structure and Parameters behind the scenes with diagrams! Functions Structure and Parameters behind the scenes with diagrams! Congratulations! You're now in week 2, diving deeper into programming and its essential components. In this case, we will talk about

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park

2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park 2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park 1 Topics Review 0f C program Functions - Overview Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function Header

More information

Arrays and Other Data Types

Arrays and Other Data Types 241 Chapter 14 Arrays and Other Data Types 14.1 Array Data Types 14.2 Manipulating Lists 14.3 When to Use an Array 14.4 Initialization of Arrays 14.5 Sorting an Array 14.6 Related Lists 14.7 Subrange Data

More information

Short Answer Questions (40 points)

Short Answer Questions (40 points) CS 1112 Fall 2017 Test 2 Page 1 of 6 Short Answer Questions (40 points) 1. TRUE FALSE You have very legibly printed your name and email id below. Name = EMAILD = 2. TRUE FALSE On my honor, I pledge that

More information

Writing and Understanding C++

Writing and Understanding C++ Writing and Understanding C++ There are language independent skills in programming (C++, Java, ) However, writing programs in any language requires understanding the syntax and semantics of the programming

More information

Repetition, Looping CS101

Repetition, Looping CS101 Repetition, Looping CS101 Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

Types, Expressions, and States

Types, Expressions, and States 8/27: solved Types, Expressions, and States CS 536: Science of Programming, Fall 2018 A. Why? Expressions represent values in programming languages, relative to a state. Types describe common properties

More information

Writing and Understanding C++

Writing and Understanding C++ Writing and Understanding C++ Writing programs in any language requires understanding the syntax and semantics of the programming language as well as language-independent skills in programming. Syntax

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

Introduction to: Computers & Programming Defining Identifiers: Objects with Names

Introduction to: Computers & Programming Defining Identifiers: Objects with Names Introduction to: Computers & Programming Defining Identifiers: Objects with Names Adam Meyers New York University Outline The types of objects with names Functions, Variables, Programs, Modules, etc. Defining

More information

C Programming for Engineers Functions

C Programming for Engineers Functions C Programming for Engineers Functions ICEN 360 Spring 2017 Prof. Dola Saha 1 Introduction Real world problems are larger, more complex Top down approach Modularize divide and control Easier to track smaller

More information

CMSC 201 Fall 2018 Python Coding Standards

CMSC 201 Fall 2018 Python Coding Standards CMSC 201 Fall 2018 Python Coding Standards The purpose of these coding standards is to make programs readable and maintainable. In the real world you may need to update your own code more than 6 months

More information

The first program: Little Crab

The first program: Little Crab Chapter 2 The first program: Little Crab topics: concepts: writing code: movement, turning, reacting to the screen edges source code, method call, parameter, sequence, if-statement In the previous chapter,

More information

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

More information

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase Today s Lesson plan (4) 20 min Quiz 10 min Looking back What did we learn last week?

More information

Decisions, Decisions. Testing, testing C H A P T E R 7

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information

Introduction to: Computers & Programming Defining Identifiers: Objects with Names

Introduction to: Computers & Programming Defining Identifiers: Objects with Names Introduction to: Computers & Programming Defining Identifiers: Objects with Names Adam Meyers New York University Outline The types of objects with names Functions, Variables, Programs, Modules, etc. Defining

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 9 Exercise

More information

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

More information

Announcements. CompSci 101 Introduction to Computer Science. APT organization, Code organization. Organization matters

Announcements. CompSci 101 Introduction to Computer Science. APT organization, Code organization. Organization matters CompSci 101 Introduction to Computer Science Jan. 24, 2017 Prof. Rodger Announcements Reading and RQ 4 due next time Asgn 2 out, APT 1 is due Thursday Lab 2 this week Add class or change sections? see

More information

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials Fundamentals We build up instructions from three types of materials Constants Expressions Fundamentals Constants are just that, they are values that don t change as our macros are executing Fundamentals

More information

4.2 Function definitions the basics

4.2 Function definitions the basics 4.2. FUNCTION DEFINITIONS THE BASICS 89 4.2 Function definitions the basics There are three questions you must answer before you can write a function definition: What will the function do? What inputs

More information

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning Lecture 1 Contracts 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Lab 4 CSE 7, Spring 2018 This lab is an introduction to using logical and comparison operators in Matlab.

Lab 4 CSE 7, Spring 2018 This lab is an introduction to using logical and comparison operators in Matlab. LEARNING OBJECTIVES: Lab 4 CSE 7, Spring 2018 This lab is an introduction to using logical and comparison operators in Matlab 1 Use comparison operators (< > = == ~=) between two scalar values to create

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

More information

CSCE 121 ENGR 112 List of Topics for Exam 1

CSCE 121 ENGR 112 List of Topics for Exam 1 List of Topics for Exam 1 If statements o How is an if statement constructed? o Does every if need an else? Looping o While loop! What does a while loop look like?! How do you ensure you will not have

More information

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology. Guide to and Hi everybody! In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology. This guide focuses on two of those symbols: and. These symbols represent concepts

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

CMSC 201 Fall 2016 Homework 6 Functions

CMSC 201 Fall 2016 Homework 6 Functions CMSC 201 Fall 2016 Homework 6 Functions Assignment: Homework 6 Functions Due Date: Wednesday, October 26th, 2016 by 8:59:59 PM Value: 40 points Collaboration: For Homework 6, collaboration is not allowed

More information

CircuitPython 101: Working with Lists, Iterators and Generators

CircuitPython 101: Working with Lists, Iterators and Generators CircuitPython 101: Working with Lists, Iterators and Generators Created by Dave Astels Last updated on 2018-11-01 12:06:56 PM UTC Guide Contents Guide Contents Overview List Functions Slicing Filtering

More information

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen 1 Truth Last lecture we learned about the int, float, and string types. Another very important object type in Python is the boolean type. The two reserved keywords True and False are values with type boolean.

More information

Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python Condition Controlled Loops Introduction to Programming - Python Decision Structures Review Programming Challenge: Review Ask the user for a number from 1 to 7. Tell the user which day of the week was selected!

More information

Intro. Speed V Growth

Intro. Speed V Growth Intro Good code is two things. It's elegant, and it's fast. In other words, we got a need for speed. We want to find out what's fast, what's slow, and what we can optimize. First, we'll take a tour of

More information

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017 Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG 1 Notice Prepare the Weekly Quiz The weekly quiz is for the knowledge we learned in the previous week (both the

More information

Racket Style Guide Fall 2017

Racket Style Guide Fall 2017 CS17 Integrated Introduction to Computer Science Hughes Racket Style Guide Fall 2017 Contents 1 Introduction 1 2 Naming 1 3 Formatting 1 4 Equality 3 5 Conditionals 4 5.1 Prefer Cond to If......................................

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 13 Functions Prof. Jeremy Dixon Based on concepts from: http://mcsp.wartburg.edu/zelle/python/ppics2/index.html Last Class We Covered Midterm exam Comments?

More information

Python Debouncer Library for Buttons and Sensors

Python Debouncer Library for Buttons and Sensors Python Debouncer Library for Buttons and Sensors Created by Dave Astels Last updated on 2019-01-09 12:28:10 AM UTC Guide Contents Guide Contents Overview Basic Debouncing Advanced Debouncing Function Factories

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

Dr. Scheme evaluates expressions so we will start by using the interactions window and asking Dr. Scheme to evaluate some expressions.

Dr. Scheme evaluates expressions so we will start by using the interactions window and asking Dr. Scheme to evaluate some expressions. 1.0 Expressions Dr. Scheme evaluates expressions so we will start by using the interactions window and asking Dr. Scheme to evaluate some expressions. Numbers are examples of primitive expressions, meaning

More information

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?

More information

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning Lecture 1 Contracts 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,

More information

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

CS 1110, LAB 3: MODULES AND TESTING   First Name: Last Name: NetID: CS 1110, LAB 3: MODULES AND TESTING http://www.cs.cornell.edu/courses/cs11102013fa/labs/lab03.pdf First Name: Last Name: NetID: The purpose of this lab is to help you better understand functions, and to

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 10 Functions Last Class We Covered The string data type Built-in functions Slicing and concatenation Escape sequences lower() and upper() strip() and whitespace

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

CSCE 110: Programming I

CSCE 110: Programming I CSCE 110: Programming I Sample Questions for Exam #1 February 17, 2013 Below are sample questions to help you prepare for Exam #1. Make sure you can solve all of these problems by hand. For most of the

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Extending Jython. with SIM, SPARQL and SQL

Extending Jython. with SIM, SPARQL and SQL Extending Jython with SIM, SPARQL and SQL 1 Outline of topics Interesting features of Python and Jython Relational and semantic data models and query languages, triple stores, RDF Extending the Jython

More information

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

Most of the class will focus on if/else statements and the logical statements (conditionals) that are used to build them. Then I'll go over a few With notes! 1 Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few useful functions (some built into standard

More information

Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork Lecture 7: Functions CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Summary Functions in Python. Terminology and execution.

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

The following content is provided under a Creative Commons license. Your support

The following content is provided under a Creative Commons license. Your support MITOCW Recitation 2 The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality educational resources for free. To make

More information

Scientific Computing: Lecture 3

Scientific Computing: Lecture 3 Scientific Computing: Lecture 3 Functions Random Numbers More I/O Practice Exercises CLASS NOTES Ò You should be finishing Chap. 2 this week. Ò HW00 due by midnight Friday into the Box folder Ò You should

More information

Writing Functions. Reading: Dawson, Chapter 6. What is a function? Function declaration and parameter passing Return values Objects as parameters

Writing Functions. Reading: Dawson, Chapter 6. What is a function? Function declaration and parameter passing Return values Objects as parameters What is a function? Function declaration and parameter passing Return values Objects as parameters Reading: Writing Functions Dawson, Chapter 6 Abstraction Data scoping Encapsulation Modules Recursion

More information

Starting. Read: Chapter 1, Appendix B from textbook.

Starting. Read: Chapter 1, Appendix B from textbook. Read: Chapter 1, Appendix B from textbook. Starting There are two ways to run your Python program using the interpreter 1 : from the command line or by using IDLE (which also comes with a text editor;

More information

Chapters 1 & 2 Programming and Programs

Chapters 1 & 2 Programming and Programs Chapters 1 & 2 Programming and Programs Instructor: Dr. Hyunyoung Lee Based on slides by Dr. Bjarne Stroustrup www.stroustrup.com/programming Abstract Today, we ll outline the aims for this course and

More information

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used) The design recipe Readings: HtDP, sections 1-5 (ordering of topics is different in lectures, different examples will be used) Survival and Style Guides CS 135 Winter 2018 02: The design recipe 1 Programs

More information

Introduction to Modules. Chapter 3. Defining and Calling a Module. Introduction to Modules. 5 Benefits of Modules. Modules CSUS, Spring 2016

Introduction to Modules. Chapter 3. Defining and Calling a Module. Introduction to Modules. 5 Benefits of Modules. Modules CSUS, Spring 2016 Chapter 3 Introduction to Modules Modules CSUS, Spring 2016 Chapter 3.1 Introduction to Modules Introduction to Modules A module is a group of statements that exists within a program for the purpose of

More information

Lecture 4 8/24/18. Expressing Procedural Knowledge. Procedural Knowledge. What are we going to cover today? Computational Constructs

Lecture 4 8/24/18. Expressing Procedural Knowledge. Procedural Knowledge. What are we going to cover today? Computational Constructs What are we going to cover today? Lecture 4 Conditionals and Boolean Expressions What is procedural knowledge? Boolean expressions The if-else and if-elif-else statements s Procedural Knowledge We differentiate

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

MITOCW watch?v=rvrkt-jxvko

MITOCW watch?v=rvrkt-jxvko MITOCW watch?v=rvrkt-jxvko The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

cs1114 REVIEW of details test closed laptop period

cs1114 REVIEW of details test closed laptop period python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any

More information

Unit E Step-by-Step: Programming with Python

Unit E Step-by-Step: Programming with Python Unit E Step-by-Step: Programming with Python Computer Concepts 2016 ENHANCED EDITION 1 Unit Contents Section A: Hello World! Python Style Section B: The Wacky Word Game Section C: Build Your Own Calculator

More information

CS 115 Lecture 4. More Python; testing software. Neil Moore

CS 115 Lecture 4. More Python; testing software. Neil Moore CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement

More information

Lecture 02 Making Decisions: Conditional Execution

Lecture 02 Making Decisions: Conditional Execution Lecture 02 Making Decisions: Conditional Execution 1 Flow of Control Flow of control = order in which statements are executed By default, a program's statements are executed sequentially, from top to bottom.

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

CSC236 Week 5. Larry Zhang

CSC236 Week 5. Larry Zhang CSC236 Week 5 Larry Zhang 1 Logistics Test 1 after lecture Location : IB110 (Last names A-S), IB 150 (Last names T-Z) Length of test: 50 minutes If you do really well... 2 Recap We learned two types of

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Functions. Using Bloodshed Dev-C++ Heejin Park. Hanyang University

Functions. Using Bloodshed Dev-C++ Heejin Park. Hanyang University Functions Using Bloodshed Dev-C++ Heejin Park Hanyang University 2 Introduction Reviewing Functions ANSI C Function Prototyping Recursion Compiling Programs with Two or More Source Code Files Finding Addresses:

More information

MITOCW watch?v=hverxup4cfg

MITOCW watch?v=hverxup4cfg MITOCW watch?v=hverxup4cfg PROFESSOR: We've briefly looked at graph isomorphism in the context of digraphs. And it comes up in even more fundamental way really for simple graphs where the definition is

More information

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to

More information

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON Table of contents 2 1. Learning Outcomes 2. Introduction 3. The first program: hello world! 4. The second program: hello (your name)! 5. More data types 6.

More information

Unit 4: Client View of a Component Methods

Unit 4: Client View of a Component Methods Unit 4: Client View of a Component Methods Preview of Coming Attractions In this unit be sure to look for method/operation parameters/formal parameters arguments/actual parameters method header/method

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Review. Modules. CS 151 Review #6. Sample Program 6.1a: Review Modules A key element of structured (well organized and documented) programs is their modularity: the breaking of code into small units. These units, or modules, that do not return a value are called

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY CS 111X - Fall 2016 - Test 1 1/9 Computing ID: CS 111X - Fall 2016 - Test 1 - KEY KEY KEY KEY KEY KEY KEY Name: Computing ID: On my honor as a student, I have neither given nor received unauthorized assistance

More information

There are functions to handle strings, so we will see the notion of functions itself in little a detail later. (Refer Slide Time: 00:12)

There are functions to handle strings, so we will see the notion of functions itself in little a detail later. (Refer Slide Time: 00:12) Programming Data Structures, Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module - 13b Lecture - 19 Functions to handle strings;

More information

Chapter 9: Dealing with Errors

Chapter 9: Dealing with Errors Chapter 9: Dealing with Errors What we will learn: How to identify errors Categorising different types of error How to fix different errors Example of errors What you need to know before: Writing simple

More information

Warmup : Name that tune!

Warmup : Name that tune! Warmup : Name that tune! Write, using a loop, Java code to print the lyrics to the song 99 Bottles of Beer on the Wall 99 bottles of beer on the wall. 99 bottles of beer. Take one down, pass it around,

More information

Divisibility Rules and Their Explanations

Divisibility Rules and Their Explanations Divisibility Rules and Their Explanations Increase Your Number Sense These divisibility rules apply to determining the divisibility of a positive integer (1, 2, 3, ) by another positive integer or 0 (although

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information