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

Similar documents
Text Input and Conditionals

Math Day 2 Programming: How to make computers do math for you

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

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

Variables, expressions and statements

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

Algorithms and Programming I. Lecture#12 Spring 2015

MITOCW watch?v=0jljzrnhwoi

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

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

Programming with Python

cs1114 REVIEW of details test closed laptop period

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

Lecture 3. Input, Output and Data Types

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

Repetition Structures

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

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Python for Non-programmers

Python Unit

Functions and Decomposition

These are notes for the third lecture; if statements and loops.

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

If Statements, For Loops, Functions

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

The Very Basics of the R Interpreter

Part III Appendices 165

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

The Big Python Guide

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

(Python) Chapter 3: Repetition

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Introduction to Python (All the Basic Stuff)

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

ENGR 101 Engineering Design Workshop

Python: common syntax

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Accelerating Information Technology Innovation

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

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

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

Python Games. Session 1 By Declan Fox

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Topic 2: Introduction to Programming

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

T H E I N T E R A C T I V E S H E L L

Programming language components

Chapter 17. Fundamental Concepts Expressed in JavaScript

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

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

1/11/2010 Topic 2: Introduction to Programming 1 1

CS1 Lecture 3 Jan. 22, 2018

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

CSCE 120: Learning To Code

Downloaded from Chapter 2. Functions

printf( Please enter another number: ); scanf( %d, &num2);

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Full file at

Introduction to TURING

Jython. secondary. memory

What did we talk about last time? Examples switch statements

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Fundamentals: Expressions and Assignment

6.096 Introduction to C++

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

CS1 Lecture 3 Jan. 18, 2019

Variables and literals

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Accelerating Information Technology Innovation

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Python 1: Intro! Max Dougherty Andrew Schmitt

Object-Oriented Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

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

CMSC 201 Computer Science I for Majors

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Computer and Programming: Lab 1

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

CME 193: Introduction to Scientific Python Lecture 1: Introduction

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Introduction to Programming in Turing. Input, Output, and Variables

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Lists, loops and decisions

CPS122 Lecture: From Python to Java

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Transcription:

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 1. Libraries 2. Modules 3. Random 3. High vs. Low Level 4. Usage 6. Variables 7. User Input 8. Conversions 9. Concatenation 10. Conditional Statements 3. Loops 4. Functions 2 What is Programming? What s a Program? Set of instructions that tell a CPU what to do A recipe, where the CPU is the cook Data are the different types of food Instructions describe how to manipulate data E.g. Numbers, words, images, sounds, etc. Operating System A special program that allows you to run other programs What is Programming? Using the computer to solve a problem You need to: Understand the problem Understand the capabilities of the computer give instructions to the computer concerning what actions it should take to solve the problem Break things down into steps Give sufficient detail in each step Be clear and unambiguous 3 4 1

What is Programming? Besides being a huge industry? Programming is the process used to write computer programs Computer programs are basically a list of instructions for your computer to execute Programs are written for some task As simple as adding up a bunch of numbers As complicated as your operating system What is Programming? - Programming Languages A programming language is a specific way of telling a computer how to do what you want It is a language Has grammar (syntax) Has key words There are many different programming languages C++ Java Visual Basic 5 6 What is Programming? - Programming Languages Programming languages are often created for specific purposes or to solve specific problems There are many different types or families of programming languages In general, all programming languages in the same family share similar properties Once you know one language it s easy to learn another What is Programming? - Markup vs. Programming HTML is a markup language is a programming language So what s the difference? Markup languages describe/create documents Programming languages are used to create programs Programs provide instructions for your computer to execute 7 8 2

What is Programming? - Markup vs. Programming Programming allows us to add extra functions to our web pages that HTML simply cannot support Programming is a challenge, but: Once you know how to program a bit it can be very useful Not just for computer scientists Especially useful in the sciences Sometimes it s faster to write a program than to do the work by hand What is Programming? - Programming Languages Why? Other more well-known languages like C, C++, and Java are more for creating desktop applications Without extensions not very suitable for the Web is a high-level language (like C, C++ and Java) Because it s a high-level language it s portable runs on most types of computers 9 10 What is Programming? - High vs. Low Level So what is meant by high-level and low-level languages? Low-level languages are also known as assembly languages or machine languages Low-level languages are not portable Programs have to be re-written for each different type of computer What is Programming? - High vs. Low Level High-level languages must be converted into low-level languages in order to be executed High-level languages are more human-readable High-level languages are more widely-used Low-level languages are used for very specialized tasks like embedded computers, microcontrollers, etc. 11 12 3

What is Programming? - High vs. Low Level Two types of translations: Using a compiler Using an interpreter Compilers completely translate your program before executing it Your program is called source code and the translation the compiler produces is called object code or the executable Interpreters do it a line at a time Alternately read and execute your file What is Programming? - Usage With python, as with most languages, we can do quite a lot User input enter your name enter a number between 1 and 100 We can output information Your are over your limit The sum of 2 and 2 is 4 13 14 What is Programming? - Usage behind the scenes Between input and output (if we have input) there is a lot going on behind the scenes We can do pretty much any math Add, subtract, divide, square, etc. We can compare one item to another i.e. login IDs and passwords If you dream it, you can probably program it With enough lines of code You should download python Available from the course website under software It is available on the lab computers - Introduction You can type commands directly into the python interpreter The python interpreter is what you get when you run the python program 15 16 4

You can write python code in a text editor and save it with the extension.py Or you can use IDLE Integrated DeveLopment Environment for Comes with the installation Usually a better choice - Introduction - Introduction The Hello, world! program is often the first program anyone writes in a new language It s tradition, so we ll start with it too Writing a program that displays Hello, world! is typically the simplest program to write in any language Basically, what we want is for the program to display the output Hello, world! 17 18 When you run the interpreter you ll get something like: IDLE 1.2.2 >>> This >>> is referred to as the prompt The print statement looks like the following: For example: - Print Statement print expression print Hello, World We can also put our program into a file and run it this way This is what you will typically be doing Easiest to do in IDLE In IDLE you ll get an interpreter window and a window where you can: Write, Edit, and Save your python program - Print Statement - IDE 19 20 5

1. In the editing window you can type your python commands print Hello, World! print Cmpt 165 2. Save the file 3. Run the file by pressing F5 - Print Statement - IDE 4. In the interpreter window you should see Hello, world! - Strings A string is a bunch of characters In >>>print Hello, world! the string is: Hello, world! We can have numbers inside strings >>>print Today is my 35 th birthday! >>>print 4+4 Strings are one type of value that python can manipulate 21 22 Values are some of the basic items that your program can manipulate Hello, world! is a value of the type string >>>print 1+1 2 So what is a type? - Types and Values Values are categorized according to their type In the example above the type is integer It s easy to see that Hello, world! and the value of 4+4 are of different types Hello, world! : 4+4: is a String is an Integer 4+4 : is a String Hello + 4: is an error (type mismatch) If it s in quotes, it is a string - Types 23 24 6

- Types The values 1.2 and 4 also have different types 4 is an integer A whole number which can be positive or negative 1.2 is called a float (or a floating-point number) Can also be positive or negative We call these real numbers in math If it has a decimal point it s usually a float The type of value dictates what you can do with it >>>print 8 4 (has value 4) >>>print Hello - H - Types why? (error) We may think this means take away the H in Hello, world! But the interpreter has no idea what we mean We can t subtract a letter from a string in this way 25 26 The main reason for using types is that different types of information are stored differently Characters are not stored the same way as integers i.e. ASCII and/or UNICODE - Types why? Integers and floating point numbers aren t stored the same way Should all be familiar with a mathematical expressions 4+4 ( 8 ) 8 * 2 ( 16 ) - Math 24 / 2 + 6 * 3 ( 30 ) An expression is any kind of calculation that returns a result 27 28 7

We can have things other than mathematical expressions A value by itself is considered an expression >>> 4 >>> Hello, world! Expressions are any combination of values, variables, and operators We ll get more into this later - Math - expressions - Math - expressions Mathematical expressions have two parts: operators and operands Mathematical Operators are the symbols we use for math + addition - subtraction / division * multiplication ** power (exponent) () brackets or parentheses 29 30 Mathematical Operands are the values we use these operators on i.e. 4 + 8 / 6 * 3 Operands are: 4, 8, 6, 3 Operators are: +, /, * - Math - expressions Operands can also be variables (coming up) In python (like in all programming languages), mathematical expressions are evaluated like we learned in grammar school BEDMAS: Brackets, Exponents, Division, Multiplication, Addition, Subtraction Multiplication and Division have the same precedence, as do Subtraction and Addition Evaluated left to right i.e. 26 / 2 + 3 * 3 = 22 - Math - evaluating expressions 31 32 8

- Math - evaluating expressions Integer division: When you divide one integer by another, you get another integer Always rounds down i.e. 2/3 = 0 4/3 = 1 Floating point division: If we want the decimal information at least one of the two operands must be a float i.e. 2.0/3 = 2/3.0 = 2.0/3.0 = 0.6666666 33 - Variables Variables are a way to store data so that we can use it over and over >>> x = 4 + 8 >>> print x 12 * x is the variable We can store data of any type in a variable >>> fname= Michael >>> lname= Angelo >>> print fname, lname Michael Angelo 34 - Variables Let s say we have the expression 8 *2 +4 and we want to store it in a variable called x >>> x = 8 *2 + 4 The value of 8 *2 + 4 is calculated, resulting in 20 This is then assigned to the variable x using the = operator This is called an assignment statement - Variables We can assign the value of one variable to another variable >>> y = x We can assign an expression using a variable to another variable >>> y = x*2 + 7 Variables do not store the expression They store the value of the expression If x = 4 in the above, y has the value: 15 y does not have the value x*2 + 7 35 36 9

- User Input Now that we have a way to store data, we can get input from users and manipulate it To prompt the user for information we are going to use a function called raw_input( ) and assign it s result to a variable The input that we receive from the user is always in String form Example: >>>name = raw_input( What is your name ) >>>print name, is a great name! 37 Another example: - User Input raw_input >>>age = raw_input( How old are you? ) >>>print you are, age, years old! So when printing out the above statement we want to put the value for age in between two strings One way to do this is to use a, Items in python separated by a comma are considered items in a list Just prints them in order 38 - User Input raw_input One of the issues with using raw_input is that all input from the user is considered to be a string Take the following: >>>base = raw_input( Enter something ) >>>print 2 times the base is:, base*2 if the user enters 4, the output would be 2 times the base is 44 if the user enters pizza, the output would be 2 times the base is pizzapizza 39 - Type Conversions Problem: If we want to find 2 times the number, we need to convert the value in base from a string to a number Solution:: We can use different functions to convert from one type to another int( ) converts whatever is inside the brackets to an integer float( ) converts the contents of the () to a floating point number str( ) converts contents of () to a string We can use these functions to convert the input from the user to the type that we need 40 10

>>>base = int(raw_input( enter something )) >>>print 2 times the base is:, base*2 Now, if the user enters 4, 8 will be output - Type Conversions - Type Conversions - example Getting input from the user Storing input in a variable Using multiple variables Converting from one type to another 41 In unit 7 examples: current_age.py 42 We can store values in variables using an assignment statement >>>x = 4 + 8 - Type Conversions - recap We can get input from the user using raw_input() >>>name = raw_input( Enter your name ) We can change the data from one type to another >>>num = int(raw_input( Enter a number )) So far when we want to print multiple things we ve been using a comma to separate the items Another way is to concatenate the items Concatenation is like string addition >>>print Hello, + world! Outputs: Hello, world! We can only concatenate strings >>>x = 4 + 8 >>>print 4 + 8 = + x - Causes an error - Concatenation 43 44 11

Just like we can change the type of input from the user from a string to a number, we can go back in the other direction >>> x = 4 + 8 >>> print 4 + 8 = + str(x) Would output: 4 + 8 = 12 - Concatenation - str( ) - Conditional So far the programs we ve written are pretty boring Whenever we need to make a decision, we must use a Conditional Statement Basically conditional statements check to see if something is true If it is true, some code is executed Perhaps if its not true, different code is executed Simplest conditional statement is the if statement 45 46 A python if statement if (T/F statement) then (do something) i.e. If the number is less than 5, print that number is less than 5 num = int(raw_input( number: )) if num < 5: - Conditional - if print( that number is less than 5 ) The syntax for the if statement is as follows: if (T/F statement) : code - Conditional - if The code you want executed if the expression is true must be indented This is the body of the if statement body expression Notice the indent!! 47 48 12

Spacing is important in python You should indent consistently - Conditional - if Convention is to indent 4 spaces (use the tab) When you stop indenting, the body of the if statement is considered to be done The code after the indention will execute no matter what num = int(raw_input( Enter a number less than 10: )) if num > 10: print That number is bigger than 10. print You can t follow directions. print Thanks for playing! Indented - Conditional - if example Not indented 49 50 - Conditional - boolean When we use an if statement, the result of the expression is either true or false If 4<3: (this is false, the body doesn t get executed) If 3<4: (this is true, the body gets executed) The result of the expression must be true or false These are called boolean expressions The two boolean values are true and false - Conditional - boolean Boolean values in python (like most languages) are stored as integers 0 represents false 4<3 as an expression has the value 0 Any other integer (usually 1) represents true 3<4 has the value of 1 You can actually write code like: if 0:... if 5:... 51 52 13

We re pretty used to seeing <, <=, >, >= in conditional statements They make sense and read just like regular English What if we want to check if something is equal to something else? We could try, if num = 1: - Conditional - boolean Recall: this is an assignment statement (not the correct syntax) We need to use the == operator if num == 1: If we want to check if two items are not equal use the!= operator if num!= 2: - Conditional - boolean 53 54 - Conditional - boolean Boolean Operators == : equal, can be used with numbers and text!= : not equal, used with both numbers and text <, > : strictly less than, greater than <=, >= : less than or equal to, greater than or equal to or : i.e. x == 9.50 or x == 9.60 and : i.e. num1 == 9 and num2 == 10 - Conditional - else We can use the else clause in to provide a sort of otherwise if 3<4: print 3 is less than 4. else: print 3 is not less than 4. Code inside the else clause will be executed only if the expression in the if statement evaluates to false 55 56 14

- Conditional - else example guess = int(raw_input( Pick a number less than or equal 10 )) if guess <= 10: print Good job! else: print Can t you follow directions!? There is one more component to the if/else structure: the else if block Basically we can now write code that reads something like: if, else if, else if,..,else - Conditional - else if To use an else if structure we need the word elif elif requires an expression (just like if) 57 58 number = 3 guess = int(raw_input( Enter a number: )) if guess == number: print you guessed it! elif guess < number: print that s too low else: print that s too big! - Conditional - else if example We can nest if statements inside other if statements Or inside elif statements Or inside else statements Basically anywhere Remember that nested ifs are only executed if the outer ifs are evaluated as true Example: range.py - Conditional - nesting if In unit 7 examples: guess.py 59 In unit 7 examples: range.py 60 15

Externals - Libraries It s useful to have some common functions available to us without us having to write the code ourselves E.g. it would be tedious if every time we needed a random number we had to write the code ourselves With most programming languages some functions are included with the language These are usually grouped into libraries We only have to import the libraries or modules we need In python, all of the prepackaged functions are considered to be part of the python library The individual parts we will import will be modules Externals - Modules When we need a random number we have to import the random module The random module contains a function called randint() which is what actually gives us a random number The syntax for importing a module is: import modulename We only import the modules we need 61 62 Externals - Modules To use a function found in a module we have to use the following syntax: modulename.functionname(...) There are a lot of modules There is a link to the reference on the course page Some of the common ones are random, math, and cmath We ll be covering many more modules So far we have had to pre-select a number for the user to guess E.g. we set number = 3 Externals - Random Number It s the same every time Pretty boring once you guess the number It would be better if every time we ran the program it chose a random number for us to guess In unit 7 examples: uppercase.py 63 64 16

Externals - Random Number In order to use random numbers it requires two parts: 1.Importing the random module 2.Using a function from the random module to generate our random number This is done by writing the following at the top of our program: import random num = random.randint(0,10) Import tells python to include the random module There are lots of modules, more on this later random.randint(1,10) In the random module, use the randint function to select a random number between 1 and 10 This is assigned to the variable num random.randint(5, 50) Externals - Random Number Select a random integer between 5 and 50 65 In unit 7 examples: random_guess.py 66 Take a Breath What you should get from this lecture: If statements else clause elif clause Nesting if statements How to produce a random integer How to access functions in modules Used to tell other people what you are doing Used to remind yourself of what you did Suggestion: always start a file with a comment containing your name, date, and a description of what the program does Anything on a line following a # is treated as a comment print Hello, World! Externals - Comments # outputs Hello, World! 67 68 17

With our random number program we re only able to let the user guess once before having to restart the program But in a real guessing game hopefully the user would be able to keep guessing until they found the answer How can we do this? Use iteration Externals - Loops Externals - Loops - iteration Iteration allows us to write programs that repeat some code over and over again The easiest form of iteration is using a while loop While loops read a lot like English (like almost everything in ) While counter is greater than 0, execute some code While userguess does not equal my number, keep asking for a new number 69 70 Externals - Loops while loop While loops are like if, elif, and else statements in that only the indented code is part of the loop Like if and elif statements, while loops must check to see if some condition is true While it s true, execute some code Once the condition has become false, exit the loop General Form: while (T/F Statement): code 71 Externals - Loops while loop Let s write a while loop that prints the numbers from 1 to 10 i = 1 #initialize i to value 1 while i<=10: #execute the code in the loop print i #until i >10 i = i +1 #increment i print all done! 72 18

Externals - Loops while loop i = 1 sum = 0 while i<=10: sum = sum + i i = i + 1 Print sum Externals - Loops while loop Adding a while loop to our random guessing program Output: 1+2+3+ +9+10 73 In unit 7 examples: random_guess_loop.py 74 Externals - Loops while loop Now our user can keep guessing until they get the right answer But they can still only play once We can add another while loop to allow the user to continue playing (i.e. restarts upon request) Externals - Loops - counters Often when creating and using while loops we need to keep count of how many times the loop has executed Usually used as the test condition for the while loop E.g. count = 1 while count < 10 print I love cmpt165 count = count + 1 In this simple example, count is referred to as the counter In unit 7 examples: random_guess_loop_restart.py 75 76 19

Counters can be used as part of the body of the while loop The counter can be used for more than counting Counters are often given a variable name of a single character i j k a Etc. Externals - Loops - counters We ve been using many functions so far raw_input int, float, str random.randint Externals - Functions So what is a function? A sequence of code which performs a specific task 77 78 Externals - Functions Functions usually take arguments This is what you have to put inside the parentheses (input) For example, raw input takes a string as an argument raw_input ( enter your name ) Functions often return a value This is what you get back when you call the function E.g. raw_input() returns a string int() returns an integer float() returns a float We don t have to rely on only the functions in the library We can write our own functions to do almost anything Why use functions? Externals - Functions - creating Makes our code easier to read Lets us repeat code more efficiently 79 80 20

Externals - Functions - creating The syntax for creating a new function is: def functionname(arguments): Let s define a function called printname that takes in a string: def printname(username): Like with if, elif, else, and while blocks, indentation is important The function is the code indented immediately following the function definition Externals - Functions - creating Let s create a function that prints Hi to the user: def printname(username): print Hi, username To call this function we simply use its name: printname( Steve ) This function takes in one argument and returns no values All it does when we call it is print Hi Steve 81 82 Externals - Functions - creating The function printname takes in the argument username username is a variable When we call the function printname, whatever value we put inside the () is the value that the function uses printname( butterfly ) printname( peanut ) The value in parenthesis in the function call is assigned to the argument variable Adding a while loop to it def printname(username): print Hi, username count = 1 Externals - Functions - creating while count <= 5: printname( Steve ) count = count + 1 83 84 21

We can have functions with many arguments As many as we want Let s do a math example where we want to do some math calculations import math Externals - Functions - creating def roots(a,b,c): root = (float(-b) + math.sqrt(b**2 - (4*a*c)) )/float(2*a) print "first root is", root root2 = (float(-b) - math.sqrt(b**2 - (4*a*c)) )/float(2*a) print "second root is", root2 Externals - Functions - creating roots takes in three arguments Need to be numbers (either ints or floats) When we call the function roots we have to put in values for a,b and c >>> roots(1,4,1) first root is -0.26794919243112281 second root is -3.73205080757 >>> roots(1,1,1) (prints error) We can use integers, floats, or variables Remember that the value we pass into the function gets stored in the variables a,b and c In unit 7 examples: roots.py 85 86 Externals - Functions - return values Functions can take in any number of arguments It s sometimes useful to have your function return a value However, functions can only return one value To return a value we use the return keyword We can return numbers, strings, and any values stored in variables Externals - Functions - return values Now oneroot will have a value when we call it >>> print oneroot(1,4,4) (prints -2.0) >>> var = oneroot(1,4,4) >>> print one root is + str(var) (prints one root is -2.0) In unit 7 examples: one_root.py 87 88 22

Summary At this point you should be able to: Use a simple while loop Understand using counters to terminate loops Define your own function Know what arguments and return values are How to call a function you write How to assign the return value to a variable Understand that functions with return values can be used as arguments of other functions 89 23