Chapter 5 Functions. Dr. Zhang COSC 1436 Summer, 2018 June 19, 2018

Size: px
Start display at page:

Download "Chapter 5 Functions. Dr. Zhang COSC 1436 Summer, 2018 June 19, 2018"

Transcription

1 Chapter 5 Functions Dr. Zhang COSC 1436 Summer, 2018 June 19, 2018

2 while Loop Repetition Review A Condition-Controlled Loop Causes a statement or set of statements to repeat as long as a condition is true. It tests its condition before performing an iteration, which is also known as a protest loop. Example: n = 10 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # print the sum # update counter print("the sum is", sum)

3 For Loop Repetition Review A count-controlled loop iterates a specific number of times. Example: # Prints out the numbers 0,1,2,3,4 for x in range(5): print(x) # Prints out 3,4,5 for x in range(3, 6): print(x) # Prints out 3,5,7 for x in range(3, 8, 2): print(x)

4 Repetition Review Augmented assignment operators

5 Nested Loop Repetition Review Python programming language allows to use one loop inside another loop you can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa. i = 0 kebab = ["chicken","garlic","cheese","tomato","lettuce","chilli"] print "Kebabs are so good, this is what mine has:" excitement_over_kebab = 1 for ingredients in kebab: while excitement_over_kebab == 1: print kebab[i] i+=1 if i == 6: print "Enough talk, my lunch break is over." excitement_over_kebab = 0

6 Chapter 5: Functions Concept: A function is group of statements that that exist within a program for the purpose of performing a specific task. Example: An overall task of calculating an travel cost would consist of several subtasks, Such as : Getting the air fare Getting the cost of ground transportation Calculating the lodge cost Calculating the meals cost Calculating the other costs Printing the total cost The program performs the task can be broken down into several subtasks. For this reason, we usually break down the programs into small manageable pieces known as functions. This approach is also called divide and conquer

7 Designing a Program to Use Functions Top-Down Design The overall task that the program is to perform is broken down into a series of subtasks. Each of the subtasks is examined to determine whether it can be further broken down into more subtasks. This step is repeated until no more subtasks can be identified. Once all of the subtasks have been identified, they are written in code.

8 Designing a Program to Use Functions Using IPO Charts IPO stands for input, processing, and output. An IPO chart is a simple but effective tool for programmer to use for designing and documenting functions.

9 Benefits of Modularizing a program Simpler Code with functions easy read and manage Code reuse reduce the duplication of code Better testing can test each function individually Faster Development same function can be used by different programs Easier Facilitation of Teamwork

10

11 Defining and Calling a Void Function Function Name Roles: python requires that you follow the same rules that you follow when naming variables: Can not use one of Python s key words as a variable name. A function name can not contains space. The first character must be one of the letters a through z, A through Z or under-score character(_) After the first character you may use one of the letters a through z, A through Z, the digit 0 through 9 or under-score character(_) name is case sensitive.

12 Defining and Calling a Void Function Concept: The code for a function is known as a function definition. To execute the function, you write a statement that calls it. ##Defining a function: def function_name(): Statement Statement ##Calling a function: function_name()

13 Defining and Calling a Void Function Code example: # This program demonstrates a function. # First, we define a function named main. def main(): print('i am Arthur') print('king of the Britons') # Call the message function. main()

14 # This program has two functions. First we # define the main function. def main(): print('i have a message for you.') message() print('goodbye!') # Next we define the message function. def message(): print('i am Arthur') print('king of the Britons.') # Call the main function. main() Program Output I have a message for you. I am Arthur King of the Britons Goodbye! Code example

15 Local Variables Concept: A local variable is created inside a function and cannot be accessed by statements that are outside the function. Different functions can have local variables with the same names because the functions cannot see each other s local variables. Scope: A variable s scope is that part of a program in which the variable may be accessed. A variable is visible only to statements in the variable s scope. A local variable s scope is the function in which the variable is created.

16 Local Variables Code example: # This program demonstrates two functions that have local variables with the same name. def main(): texas() # Call the texas function. california() # Call the california function. # Definition of the texas function. def texas(): birds = 5000 # a local variable named birds. print('texas has', birds, 'birds.') # Definition of the california function. def california(): birds = 8000 # a local variable named birds. print('california has', birds, 'birds.') # Call the main function. main()

17 Passing Arguments to Functions Concept: An argument is any piece of data that is passed into a function when the function is called. A parameter is a variable that receives an argument that is passed into a function.

18 Passing Arguments to Functions Code example # This program demonstrates an argument being # passed to a function. def main(): value = 5 show_double(value) ## value is argument # The show_double function accepts an argument # and displays double its value. def show_double(number): ## number is parameter result = number * 2 print(result) # Call the main function. main()

19 Passing Arguments to Functions- Cont Parameter Variable Scope: A parameter variable s scope is the function in which the parameter is used. Passing Multiple Arguments: In Python, functions can accept multiple arguments. # This program demonstrates a function that accepts # two arguments. def main(): print('the sum of 12 and 45 is') show_sum(12, 45) # The show_sum function accepts two arguments and displays their sum. def show_sum(num1, num2): result = num1 + num2 print(result) main() ## Call the main function

20 Passing Arguments to Functions- Cont Code example (passing strings) # This program demonstrates passing two string # arguments to a function. def main(): first_name = input('enter your first name: ') last_name = input('enter your last name: ') print('your name reversed is') reverse_name(first_name, last_name) def reverse_name(first, last): print(last, first) # Call the main function. main()

21 Passing Arguments to Functions- Cont Making Changes to Parameters. You can change the value of the parameters. # This program demonstrates what happens when you change the value of a parameter. def main(): value = 99 print('the value is', value) change_me(value) print('back in main the value is', value) def change_me(arg): print('i am changing the value.') arg = 0 print('now the value is', arg) main() # Call the main function.

22 Passing Arguments to Functions- Cont Keyword Arguments The Python language allows you to write an argument in the following format to specify which parameter variable the argument should be passed to: Parameter_name=value (syntax) Example: def main(): show_interest(rate=0.01, periods=10, principal=1000.0) def show_interest(principle, rate, periods): interest = principal * rate * periods print( The simple interest will be $, format(interest,,.2f ), sep= ) # call the main function main()

23 Global Variables and Global Constants global variable : A global variable is accessible to all the functions in a program file. The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution. 1. # Create a global variable. my_value = 10 # The show_value function prints # the value of the global variable. def show_value(): print(my_value) # Call the show_value function. show_value()

24 Global Variables and Global Constants global variable : A variable can't be both local and global inside of a function. So Python decides that we want a local variable due to the assignment to s inside of f(), so the first print statement before the definition of s throws the error message above. Any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we want to use the global variable, we have to explicitly state this by using the keyword "global", as can be seen in the following example: def f(): global s ## keyword global print(s) s = "Only in spring, but London is great as well!" print(s) s = "I am looking for a course in Paris!" # a f() print(s)

25 Global Variables and Global Constants Concept: A global constant is a global name that references a value that can not be changed. # The following is used as a global constant to represent the contribution rate. CONTRIBUTION_RATE = 0.05 def main(): gross_pay = float(input('enter the gross pay: ')) bonus = float(input('enter the amount of bonuses: ')) show_pay_contrib(gross_pay) show_bonus_contrib(bonus). def show_pay_contrib(gross): #Calculate the retirement contribution contrib = gross * CONTRIBUTION_RATE print('contribution for gross pay: $', format(contrib, ',.2f'), sep='') def show_bonus_contrib(bonus): #calculate the contrib = bonus * CONTRIBUTION_RATE print('contribution for bonuses: $', format(contrib, ',.2f'), sep='') main() # Call the main function.

26 Concept: Introduction to Value-Returning Functions: A value-returning function is a function that returns a value back to the part of the program that called it. Python, as well as most other programming languages, provides a library of prewritten functions that perform commonly needed tasks. These libraries typically contain a function that generates random numbers. A value-returning function is a special type of function. It is like a void function in the following ways. It is a group of statements that perform a specific task When you want to execute the function, you call it

27 Introduction to Value-Returning Functions: Standard Library Functions and the import statement import math This statement causes the interpreter to load the contents of the math module into memory and makes all the functions in the math module available to the program Import random This statement causes the interpreter to load the contents of the random module into memory and makes all the functions in the random module available to the program

28 Introduction to Value-Returning Functions: Generating Random Numbers Import random Functions: random.randint(1,10) #generate random integer random.randrange(0,101,10) There is one slight difference when used with just two parameters. randint(x,y) will return a value >= x and <= y, while randrange(x,y) will return a value >=x and < y (n.b. not less than or equal to y) There is a bigger difference if you use the additional parameter that randrange can take... randrange(start, stop, step)

29 Introduction to Value-Returning Functions: Generating Random Numbers Import random Functions: random.random random.uniform(1.0,10.0) random.random() gives you a random floating point number in the range [0.0, 1.0) (so including 0.0, but not including 1.0). random.uniform(a, b) gives you a random floating point number in the range [a, b], (where rounding may end up giving you b).

30 Introduction to Value-Returning Functions: # This program displays a random number in the range of 1 through 10. import random def main(): number = random.randint(1, 10) # Get a random number. print('the number is', number) # Display the number. # Call the main function. main()

31 Introduction to Value-Returning Functions: # This program displays five random # numbers in the range of 1 through 100. import random def main(): for count in range(5): # Get a random number. number = random.randint(1, 100) # Display the number. print(number) # Call the main function. main()

32 Introduction to Value-Returning Functions: # This program simulates 10 tosses of a coin import random # GLOBAL Constants HEADS = 1 TAILS = 2 TOSSES = 10 def main(): for toss in range(tosses): # Simulate the coin toss. if random.randint(heads, TAILS) == HEADS: print('heads') else: print('tails') main() # Call the main function.

33 Introduction to Value-Returning Functions: randrange, random, seed, and uniform Functions number = random.randrange(10) number=random.randrange(5,10) number=random.randrange(0,101,10) number=random.uniform(1.0,10.0) Random.seed(10) import random random.seed( 3 ) Print( "Random number with seed 3 : ", random.random() ) #will generate a random number #if you want to use the same #random number once again in your #program random.seed( 3 ) random.random() # same random number as before

34 Introduction to Value-Returning Functions: Concept: The Python standard library s math module contains numerous functions that can be used in mathematical calculations Example: result = math.sqrt(16), mypi=math.pi, mye=math.e

35 Writing Your Own Value-Returning Function Concept: A value-returning function has a return statement that returns a value back to the part of the program that called it. Sytanx: def function_name(): Statement Statement Etc. Return expression

36 Writing Your Own Value-Returning Function Example: # This program uses the return value of a function. def main(): first_age = int(input('enter your age: ')) # Get the user's age. second_age = int(input("enter your best friend's age: ")) total = sum(first_age, second_age) # Display the total age. print('together you are', total, 'years old.') # The sum function accepts two numeric arguments and returns the sum of those arguments. def sum(num1, num2): result = num1 + num2 return result main() # Call the main function.

37 Writing Your Own Value-Returning Function Return string, Boolean values, multiple values Code example: def get_name(): name=input( Enter your name: ) return name def is_even(number): if number = 1 status = True else status = false return status

38 Writing Your Own Value-Returning Function Return string, Boolean values, multiple values Code example: def get_fullname(): firstname = input( Enter your first name ) lastname = input( Enter your last name ) #return both name return firstname, lastname # call get_fullname function first_name, last_name = get_fullname()

39 Writing Your Own Value-Returning Function EXAMPLE: Text book: page 211

40 Lab exercise and Assignment Lab : Chapter 5: Programming Exercises: 1,3,5,8,13 Due 6/21/2018 ( show your code to me in class) Review questions. Assignments: Chapter 5: Programming Exercises : 14, 19,20,21 Due 6/26/2018 ( show your code to me in class)

Chapter 5 Functions (Part 2) Hong Sun COSC 1436 Fall, 2017 Oct 18, 2017

Chapter 5 Functions (Part 2) Hong Sun COSC 1436 Fall, 2017 Oct 18, 2017 Chapter 5 Functions (Part 2) Hong Sun COSC 1436 Fall, 2017 Oct 18, 2017 Defining and Calling a Void Function Function Name Roles: python requires that you follow the same rules that you follow when naming

More information

Functions. Introduction to Functions Introduction to Functions TOPICS C H A P T E R

Functions. Introduction to Functions Introduction to Functions TOPICS C H A P T E R C H A P T E R www.thestudycampus.com Functions Introduction to Functions TOPICS 5.1 Introduction to Functions 5.2 Defining and Calling a Void Function 5.3 Designing a Program to Use Functions 5.4 Local

More information

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017 Chapter 6: Files and Exceptions COSC 1436, Spring 2017 Hong Sun 3/6/2017 Function Review: A major purpose of functions is to group code that gets executed multiple times. Without a function defined, you

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

Chapter 4 Repetition Structures. Dr. Zhang COSC 1436 Spring 2017 June 15, 2017

Chapter 4 Repetition Structures. Dr. Zhang COSC 1436 Spring 2017 June 15, 2017 Chapter 4 Repetition Structures Dr. Zhang COSC 1436 Spring 2017 June 15, 2017 Review Python: about Indentation The indentation level of your statements is significant (i.e. the whitespace at the very left

More information

Chapter 3: Modules. Starting Out with Programming Logic & Design. Second Edition. by Tony Gaddis

Chapter 3: Modules. Starting Out with Programming Logic & Design. Second Edition. by Tony Gaddis Chapter 3: Modules Starting Out with Programming Logic & Design Second Edition by Tony Gaddis Copyright 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Topics 3.1 Introduction

More information

More Functions. CS 1111 Introduction to Programming. Spring 2019

More Functions. CS 1111 Introduction to Programming. Spring 2019 More Functions CS 1111 Introduction to Programming Spring 2019 [The Coder s Apprentice,, 8-8.3] Based in part on Agnostic Programming: Learning to Design and Test Basic Programming Algorithms by Kinga

More information

Random Walks and Defining Functions FEB 9 AND 11, 2015

Random Walks and Defining Functions FEB 9 AND 11, 2015 Random Walks and Defining Functions FEB 9 AND 11, 2015 If we take a random walk, will we go places? Problem: Simulate a random walk in which a person starts of at point 0 and at each step randomly picks

More information

How to Think...- Chapter 3

How to Think...- Chapter 3 1 Professor: Sana Odeh odeh@courant.nyu.edu Functions Math Functions (generating random functions) Reading: How to Think...- Chapter 3 2 Functions Two types of Functions: Built-in functions: (efficient

More information

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today. Lecture 6 Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today. Previously Decision structures with flowcharts Boolean logic UML

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3 Programming in C main Level 2 Level 2 Level 2 Level 3 Level 3 1 Programmer-Defined Functions Modularize with building blocks of programs Divide and Conquer Construct a program from smaller pieces or components

More information

Introduction to programming using Python

Introduction to programming using Python Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 5 1 Objectives To come back on the definition of functions To invoke value-returning

More information

Python Unit

Python Unit Python Unit 1 1.1 1.3 1.1: OPERATORS, EXPRESSIONS, AND VARIABLES 1.2: STRINGS, FUNCTIONS, CASE SENSITIVITY, ETC. 1.3: OUR FIRST TEXT- BASED GAME Python Section 1 Text Book for Python Module Invent Your

More information

CMSC 201 Computer Science I for Majors

CMSC 201 Computer Science I for Majors CMSC 201 Computer Science I for Majors Lecture 02 Intro to Python Syllabus Last Class We Covered Grading scheme Academic Integrity Policy (Collaboration Policy) Getting Help Office hours Programming Mindset

More information

(Python) Chapter 3: Repetition

(Python) Chapter 3: Repetition (Python) Chapter 3: Repetition 3.1 while loop Motivation Using our current set of tools, repeating a simple statement many times is tedious. The only item we can currently repeat easily is printing the

More information

Basics of Programming with Python

Basics of Programming with Python Basics of Programming with Python A gentle guide to writing simple programs Robert Montante 1 Topics Part 3 Obtaining Python Interactive use Variables Programs in files Data types Decision-making Functions

More information

Test #2 October 8, 2015

Test #2 October 8, 2015 CPSC 1040 Name: Test #2 October 8, 2015 Closed notes, closed laptop, calculators OK. Please use a pencil. 100 points, 5 point bonus. Maximum score 105. Weight of each section in parentheses. If you need

More information

Quiz 1: Functions and Procedures

Quiz 1: Functions and Procedures Quiz 1: Functions and Procedures Outline Basics Control Flow While Loops Expressions and Statements Functions Primitive Data Types 3 simple data types: number, string, boolean Numbers store numerical data

More information

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017 Chapter 2 Input, Processing and Output Hong Sun COSC 1436 Spring 2017 Jan 30, 2017 Designing a Program Designing a Program o Programs must be carefully designed before they are written. Before beginning

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

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals Midterm 1 Review Important control structures Functions Loops Conditionals Important things to review Binary numbers Boolean operators (and, or, not) String operations: len, ord, +, *, slice, index List

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

Expressions and Variables

Expressions and Variables Expressions and Variables Expressions print(expression) An expression is evaluated to give a value. For example: 2 + 9-6 Evaluates to: 5 Data Types Integers 1, 2, 3, 42, 100, -5 Floating points 2.5, 7.0,

More information

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik SAMS Programming A/B Lecture #1 Introductions July 3, 2017 Mark Stehlik Outline for Today Overview of Course A Python intro to be continued in lab on Wednesday (group A) and Thursday (group B) 7/3/2017

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

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python CONDITION CONTROLLED LOOPS Introduction to Programming - Python Generating Random Numbers Generating a random integer Sometimes you need your program to generate information that isn t available when you

More information

Conditionals and Recursion. Python Part 4

Conditionals and Recursion. Python Part 4 Conditionals and Recursion Python Part 4 Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print (remainder) 1 Boolean expressions An expression that

More information

Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python + Condition Controlled Loops Introduction to Programming - Python + Repetition Structures n Programmers commonly find that they need to write code that performs the same task over and over again + Example:

More information

Python Activity 7: Looping Structures WHILE Loops

Python Activity 7: Looping Structures WHILE Loops Python Activity 7: Looping Structures WHILE Loops How can I get my code to repeat output or processes? Learning Objectives Students will be able to: Content: Explain the three parts of a loop Explain the

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Starting chapter 5. l First open file, and say purpose read or write inputfile = open('mydata.txt', 'r') outputfile = open('myresults.

Starting chapter 5. l First open file, and say purpose read or write inputfile = open('mydata.txt', 'r') outputfile = open('myresults. Starting chapter 5 Files l Mostly handle like any sequential data type A sequence of characters if a text file, or a sequence of bytes if a binary file l First open file, and say purpose read or write

More information

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++ Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and

More information

Variable A variable is a value that can change during the execution of a program.

Variable A variable is a value that can change during the execution of a program. Declare and use variables and constants Variable A variable is a value that can change during the execution of a program. Constant A constant is a value that is set when the program initializes and does

More information

Notes on Chapter 1 Variables and String

Notes on Chapter 1 Variables and String Notes on Chapter 1 Variables and String Note 0: There are two things in Python; variables which can hold data and the data itself. The data itself consists of different kinds of data. These include numbers,

More information

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal An Easy Intro to Python & Programming Don t just buy a new video game, make one. Don t just download the latest app, help design it. Don t just play on your phone, program it. No one is born a computer

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want

More information

CMSC 201 Spring 2018

CMSC 201 Spring 2018 CMSC 201 Spring 2018 Name Midterm Review Worksheet This worksheet is NOT guaranteed to cover every topic you might see on the exam. It is provided to you as a courtesy, as additional practice problems

More information

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

20. VB Programming Fundamentals Variables and Procedures

20. VB Programming Fundamentals Variables and Procedures 20. VB Programming Fundamentals Variables and Procedures 20.1 Variables and Constants VB, like other programming languages, uses variables for storing values. Variables have a name and a data type. Array

More information

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Introduction to: Computers & Programming: Review prior to 1 st Midterm Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in

More information

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each. CMSC 0 Fall 0 Name Final Review Worksheet This worksheet is NOT guaranteed to cover every topic you might see on the exam. It is provided to you as a courtesy, as additional practice problems to help you

More information

Name: Partner: Python Activity 9: Looping Structures: FOR Loops

Name: Partner: Python Activity 9: Looping Structures: FOR Loops Name: Partner: Python Activity 9: Looping Structures: FOR Loops Learning Objectives Students will be able to: Content: Explain the difference between while loop and a FOR loop Explain the syntax of a FOR

More information

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board) Chapter 5 : Informatics practices Class XI ( As per CBSE Board) Conditional & Looping Constructs Control Statements Control statements are used to control the flow of execution depending upon the specified

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

CSC 533: Programming Languages. Spring 2015

CSC 533: Programming Languages. Spring 2015 CSC 533: Programming Languages Spring 2015 Functional programming LISP & Scheme S-expressions: atoms, lists functional expressions, evaluation, define primitive functions: arithmetic, predicate, symbolic,

More information

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions. 6 Functions TOPICS 6.1 Focus on Software Engineering: Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5 Passing Data by Value 6.6 Focus

More information

Repetition Algorithms

Repetition Algorithms Repetition Algorithms Repetition Allows a program to execute a set of instructions over and over. The term loop is a synonym for a repetition statement. A Repetition Example Suppose that you have been

More information

Python. Department of Computer Science And Engineering. European University Cyprus

Python. Department of Computer Science And Engineering. European University Cyprus 1 Python VICKY PAPADOPOULOU LESTA, Assistant Professor, Member at AHPC group MICHALIS KYPRIANOU, member of the AHPC group(internship project) Department of Computer Science And Engineering European University

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Department of Computer Science and Information Systems Steve Maybank sjmaybank@dcs.bbk.ac.uk Spring 2018 Week 9: Functions 9 March 2018 Birkbeck College, U. London 1 Exercise

More information

Chapter 4 Introduction to Control Statements

Chapter 4 Introduction to Control Statements Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?

More information

Python Games. Session 1 By Declan Fox

Python Games. Session 1 By Declan Fox Python Games Session 1 By Declan Fox Rules General Information Wi-Fi Name: CoderDojo Password: coderdojowireless Website: http://cdathenry.wordpress.com/ Plans for this year Command line interface at first

More information

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers

More information

Lab 4 Fruitful Functions

Lab 4 Fruitful Functions Lab 4 Fruitful Functions September 19, 2018 1 ME 30 Lab 4 - Functions and Style Description and Summary: >A function in programming is a block of code that performs some task. Functions are a way to organize

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

CMSC 201 Spring 2017 Lab 12 Recursion

CMSC 201 Spring 2017 Lab 12 Recursion CMSC 201 Spring 2017 Lab 12 Recursion Assignment: Lab 12 Recursion Due Date: During discussion, May 1st through May 4th Value: 10 points (8 points during lab, 2 points for Pre Lab quiz) This week s lab

More information

COSC The if Statement. Yves Lespérance. Lecture Notes Week 5 Control Structures

COSC The if Statement. Yves Lespérance. Lecture Notes Week 5 Control Structures COSC 1020 Yves Lespérance Lecture Notes Week 5 Control Structures Recommended Readings: Horstmann: Ch. 5 and 6 Lewis & Loftus: Ch. 3 The if Statement The if statement is used to select which is to be performed

More information

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016 Chapter 6: Files and Exceptions COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016 Introduction to File Input and Output Concept: When a program needs to save data for later use, it writes the data in a

More information

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

Computer Science 217

Computer Science 217 Computer Science 17 Midterm Exam March 5, 014 Exam Number 1 First Name: Last Name: ID: Class Time (Circle One): 1:00pm :00pm Instructions: Neatly print your names and ID number in the spaces provided above.

More information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

Chapter Five: Functions

Chapter Five: Functions Chapter Five: Functions Chapter Goals To be able to implement functions To become familiar with the concept of parameter passing To develop strategies for decomposing complex tasks into simpler ones To

More information

Impera've Programming

Impera've Programming Impera've Programming Python Programs Interac)ve Input/Output One- Way and Two- Way if Statements for Loops User- Defined Func)ons Assignments Revisited and Parameter Passing Python program line1 = 'Hello

More information

CS110: PROGRAMMING LANGUAGE I

CS110: PROGRAMMING LANGUAGE I CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Intro. to Computing. Lecture 7 Page1

Intro. to Computing. Lecture 7 Page1 1. Read sections 6.1 and 6.2 of the textbook. A function is a procedural abstract, i.e., a named body of code that performs some task when it is called/invoked. Often a function will have one or more parameter

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Variables and data types

Variables and data types Survivor: CSCI 135 Variables Variables and data types Stores information your program needs Each has a unique name Each has a specific type Java built-in type what it stores example values operations String

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

CS 139 Practice Midterm Questions #2

CS 139 Practice Midterm Questions #2 CS 139 Practice Midterm Questions #2 Spring 2016 Name: 1. Write Java statements to accomplish each of the following. (a) Declares numbers to be an array of int s. (b) Initializes numbers to contain a reference

More information

Textbook. Topic 5: Repetition. Types of Loops. Repetition

Textbook. Topic 5: Repetition. Types of Loops. Repetition Textbook Topic 5: Repetition Are you saying that I am redundant? That I repeat myself? That I say the same thing over and over again? Strongly Recommended Exercises The Python Workbook: 64, 69, 74, and

More information

Semester 2. Structured Programming. Modular Programming Top-down design. Essentials covered. More complex programming topics.

Semester 2. Structured Programming. Modular Programming Top-down design. Essentials covered. More complex programming topics. Semester 2 Essentials covered Basis of problem solving More complex programming topics Modular programming Lists, tuples, strings & arrays File handling Dr. Hugh Melvin, Dept. of IT, NUI,G 1 Structured

More information

Teaching London Computing

Teaching London Computing Teaching London Computing A Level Computer Science Topic 1: GCSE Python Recap William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims What is programming?

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

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017 Java Methods Lecture 8 COP 3252 Summer 2017 May 23, 2017 Java Methods In Java, the word method refers to the same kind of thing that the word function is used for in other languages. Specifically, a method

More information

Python workshop. Week 2: Make choices and reuse code.

Python workshop. Week 2: Make choices and reuse code. Python workshop Week 2: Make choices and reuse code barbera@van-schaik.org Overview of this workshop series Week 1: Writing your first program Week 2: Make choices and reuse code Week 3: Loops and strings

More information

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

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

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Programming for Engineers Functions

Programming for Engineers Functions Programming for Engineers Functions ICEN 200 Spring 2018 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

Fundamentals of Programming (Python) Control Structures. Sina Sajadmanesh Sharif University of Technology Fall 2017

Fundamentals of Programming (Python) Control Structures. Sina Sajadmanesh Sharif University of Technology Fall 2017 Fundamentals of Programming (Python) Control Structures Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python: How to Program 1 st Edition Outline 1. Control Structures

More information

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 07 While Loops (cont) Last Class We Covered Using while loops Syntax of a while loop Interactive loops Infinite loops and other problems Practice with while

More information

CS1 Lecture 5 Jan. 25, 2019

CS1 Lecture 5 Jan. 25, 2019 CS1 Lecture 5 Jan. 25, 2019 HW1 due Monday, 9:00am. Notes: Do not write all the code at once before starting to test. Take tiny steps. Write a few lines test... add a line or two test... add another line

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 Ziad Matni Dept. of Computer Science, UCSB Administrative CHANGED T.A. OFFICE/OPEN LAB HOURS! Thursday, 10 AM 12 PM

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 7&8: Methods Lecture Contents What is a method? Static methods Declaring and using methods Parameters Scope of declaration Overloading

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

Algorithms and Conditionals

Algorithms and Conditionals Algorithms and Conditionals CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005 Lecture 8 Classes and Objects Part 2 MIT AITI June 15th, 2005 1 What is an object? A building (Strathmore university) A desk A laptop A car Data packets through the internet 2 What is an object? Objects

More information

Chapter 11: Create Your Own Objects

Chapter 11: Create Your Own Objects Chapter 11: Create Your Own Objects Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Our usual text takes a fairly non-standard departure in this chapter. Instead, please refer

More information