FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Day 1 – Lesson 4 Beginning Functions 4/5/09 Python Mini-Course: Day 1 - Lesson 4 1.
Python Programming Chapter 9: Tuples Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Μαθαίνοντας Python [Κ4] ‘Guess the Number’
Structured programming
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Introduction to Python
Chapter 2 Writing Simple Programs
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Python Programming Chapter 3: Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
1 Python Chapter 2 © Samuel Marateck, After you install the compiler, an icon labeled IDLE (Python GUI) will appear on the screen. If you click.
1 Data types, operations, and expressions Continued l Overview l Assignment statement l Increment and Decrement operators l Short hand operators l The.
Functions and abstraction Michael Ernst UW CSE 190p Summer 2012.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program.
Python Programming Fundamentals
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
Python – Part 3 Functions 1. Function Calls Function – A named sequence of statements that performs a computation – Name – Sequence of statements “call”
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Functions Chapter 4 Python for Informatics: Exploring Information
Lecture 5 Methods. Sometimes we want to perform the same sequence of operations multiple times in a program. While loops allow us to do this, they are.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Variables, Expressions and Statements
Python – Part 3 Functions 1. Getting help Start the Python interpreter and type help() to start the online help utility. Or you can type help(print) to.
Python Functions : chapter 3
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
Python Let’s get started!.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
Controlling Program Flow with Decision Structures.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015.
Functions Venkatesh Ramamoorthy 21-March Examples #include double y ; … y = sin(45*3.1416/180) ; std::cout
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Chapter 2 Writing Simple Programs
Chapter 6: User-Defined Functions I
Introduction to Programming
Python: Experiencing IDLE, writing simple programs
Introduction to Python
Functions Chapter 4 Python for Everybody
Presented By S.Yamuna AP/IT
Introduction to Programming
Variables, Expressions, and IO
Python - Functions.
Functions CIS 40 – Introduction to Programming in Python
Functions.
“If you can’t write it down in English, you can’t code it.”
Introduction to Programming
Introduction to Programming
Python for Informatics: Exploring Information
Chapter 6: User-Defined Functions I
CHAPTER 3: String And Numeric Data In Python
COMPUTER PROGRAMMING SKILLS
Introduction to Programming
Introduction to Programming
Class code for pythonroom.com cchsp2cs
Presentation transcript:

FUNCTIONS

Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in functions The max and min functions give us the largest and smallest values in a list, respectively: >>> max('Hello world') w >>> min('Hello world') ' ‘  nothing >>>len('Hello world') 11

These functions are not limited to looking at strings, they can operate on any set of values You should treat the names of built-in functions as reserved words (i.e. avoid using “max” as a variable name). >>> int('32') 32 >>> int('Hello') ValueError: invalid literal for int(): Hello int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part: >>> int( ) 3 >>> int(-2.3) -2 >>> float(32) 32.0 >>> float(' ') >>> str(32) '32' >>> str( ) ' '

RANDOM NUMBERS Given the same inputs, most computer programs generate the same outputs every time, so they are said to be deterministic. Making a program truly nondeterministic turns out to be not so easy, but there are ways to make it at least seem nondeterministic. One of them is to use algorithms that generate pseudorandom numbers. The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you call random, you get the next number in a long series. To see a sample, run this loop: import random for i in range(10): x = random.random() print x This program produces the following list of 10 random numbers between 0.0 and up to but not including

The function randint takes parameters low and high and returns an integer between low and high (including both). >>> random.randint(5, 10) 5 >>> random.randint(5, 10) 9 To choose an element from a sequence at random, you can use choice: >>> t = [1, 2, 3] >>> random.choice(t) 2 >>> random.choice(t) 3

MATH FUNCTIONS Python has a math module that provides most of the familiar mathematical functions. Before we can use the module, we have to import it: >>> import math >>> ratio = signal_power / noise_power >>> decibels = 10 * math.log10(ratio) >>> radians = 0.7 >>> height = math.sin(radians) The first example computes the logarithm base 10 of the signal-to-noise ratio. The math module also provides a function called log that computes logarithms base e. The second example finds the sine of radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2p: >>> degrees = 45 >>> radians = degrees / * 2 * math.pi >>> math.sin(radians) >>> math.sqrt(2) /

ADDING NEW FUNCTIONS def print_lyrics(): print "I'm a lumberjack, and I'm okay." print 'I sleep all night and I work all day.' def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name. The empty parentheses after the name indicate that this function doesn’t take any arguments. The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; most people use single quotes except in cases like this where a single quote (which is also an apostrophe) appears in the string. >>> print type(print_lyrics)

The syntax for calling the new function is the same as for built-in functions: >>> print_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day. Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called repeat_lyrics: def repeat_lyrics(): print_lyrics() And then call repeat_lyrics: >>> repeat_lyrics() I'm a lumberjack, and I'm okay. I sleep all night and I work all day. I'm a lumberjack, and I'm okay. I sleep all night and I work all day. Pulling together the code fragments from the previous section, the whole program looks like this: def print_lyrics(): print "I'm a lumberjack, and I'm okay." print 'I sleep all night and I work all day.' def repeat_lyrics(): print_lyrics() repeat_lyrics()

Here is an example of a user-defined function that takes an argument: def print_twice(bruce): print bruce >>> print_twice(17) 17 >>> print_twice(math.pi) >>> print_twice('Spam '*4) Spam Spam You can also use a variable as an argument: >>> michael = 'Eric, the half a bee.' >>> print_twice(michael) Eric, the half a bee.

Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called None. >>> result = print_twice('Bing') Bing >>> print result None To return a result from a function, we use the return statement in our function. For example, we could make a very simple function called addtwo that adds two numbers together and return a result. def addtwo(a, b): added = a + b return added x = addtwo(3, 5) print x

EXERCISE 4.3 What is the purpose of the ”def” keyword in Python? a) It is slang that means ”the following code is really cool” b) It indicates the start of a function c) It indicates that the following indented section of code is to be stored for later d) b and c are both true e) None of the above

EXERCISE 4.4 What will the following Python program print out? def fred(): print "Zap" def jane(): print "ABC" jane() fred() jane() a) Zap ABC jane fred jane b) Zap ABC Zap c) ABC Zap jane d) ABC Zap ABC e) Zap Zap Zap

EXERCISE 4.5 Rewrite your pay computation with time-and-a-half for overtime and create a function called compute_pay which takes two parameters (hours and rate). Enter Hours: 45 Enter Rate: 10 Pay: 475.0

EXERCISE 4.5 hrz=float(raw_input("hrz")) rate= float(raw_input("rate")) def comput_pay(hrz,rate): pay=hrz*rate return pay x= comput_pay(hrz,rate) print x

EXERCISE 4.7 Rewrite the grade program from the previous chapter using a function called computer grade that takes a score as its parameter and returns a grade as a string. Score Grade > 0.9 A > 0.8 B > 0.7 C > 0.6 D <= 0.6 F Program Execution: Enter score: 0.95 A Enter score: perfect Bad score Enter score: 10.0 Bad score Enter score: 0.75 C Enter score: 0.5 F