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.

Slides:



Advertisements
Similar presentations
Introduction to Computing Science and Programming I
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
Lecture 2 Introduction to C Programming
Introduction to C Programming
Μαθαίνοντας Python [Κ4] ‘Guess the Number’
Computer Science 1620 Loops.
Jay Summet CS 1 with Robots IPRE Python Review 1.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Program Design and Development
Loops – While, Do, For Repetition Statements Introduction to Arrays
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Python November 14, Unit 7. Python Hello world, in class.
Intro to Python Paul Martin. History Designed by Guido van Rossum Goal: “Combine remarkable power with very clear syntax” Very popular in science labs.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Python Control of Flow.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
An Introduction to Textual Programming
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #002 (January 17, 2015)
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.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Module 3 Fraser High School. Module 3 – Loops and Booleans import statements - random use the random.randint() function use while loop write conditional.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #005 (April somthin, 2015)
CPS120: Introduction to Computer Science Decision Making in Programs.
Functions Chapter 4 Python for Informatics: Exploring Information
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Count Controlled Loops Look at the little children … Why is the sun’s face features orange …
Loops and Simple Functions CS303E: Elements of Computers and Programming.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Loops and Simple Functions COSC Review: While Loops Typically used when the number of times the loop will execute is indefinite Typically used when.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
Python Review 1.
REPETITION CONTROL STRUCTURE
Introduction to Python
Introduction To Repetition The for loop
ECS10 10/10
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Variables, Expressions, and IO
Formatting Output.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Arrays, For loop While loop Do while loop
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
An Introduction to Python
Count Controlled Loops
CISC101 Reminders Assn 3 due tomorrow, 7pm.
CISC101 Reminders All assignments are now posted.
COMPUTER PROGRAMMING SKILLS
CISC101 Reminders Assignment 3 due today.
Lecture 7 – Unit 1 – Chatbots Python – For loops + Robustness
CMPT 120 Lecture 13 – Unit 2 – Cryptography and Encryption –
Presentation transcript:

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 use conditionals We can import new modules with specific functions we need

What’s Next?- Iteration 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

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 Python) –While counter is greater than 0, execute some code –While userguess does not equal my number, keep asking for a new number

While Loop While loops are like if, elif, and else statements in that only the indented code is part of the loop –Be careful with indentation Like if and elif statements, while loops must check to see if some condition is true –While it’s true, execute some code –When it’s not true, exit the loop

Simple While Loop Example Let’s write a while loop that prints the numbers from 1 to 10 i = 1#initialize i 1 while i<=10:#execute the code in the loop print iuntil i >10 i = i +1#increment i print “all done!”

Another While Loop Example count =1 num =3 while count<5: print num*count count = count+1 *this prints 3, 6, 9, 12

Variation on Last While Loop num =3 while num<=12: print num num = num+3 *this loop also prints 3, 6, 9, 12

In-Class Example Adding a while loop to our random program

While loops, cont. 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 In-Class Example

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 Ex. count = 1 while count<10 print “I love cmpt165” count = count+1 In this simple example, count is referred to as the counter

Counters, cont. 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–i –j–j –k–k –a–a –b–b –Etc.

Counters, cont. We don’t always need counters count =1 num =3 while count<5: print num*count count = count+1 num =3 while num<=12: print num num = num+3

Functions We’ve been using many functions so far –raw_input –type –int, float, str –random.randint So what is a function? –Sequence of code which performs a specific task

Functions, cont. Functions often take arguments –This is what you have to put inside the parentheses –For example, raw input “takes in” a string raw_input (“enter your name”) –“Takes in” is another way of saying it takes an argument, in this case a string Functions often return a value –This is what you get back when you “call” the function –For example, raw_input returns a string –int() returns an integer –float() returns a float

Creating New Functions We don’t have to rely on only the functions in the Python library We can have functions that do almost anything –Can be as simple as adding 2 to a number Why use functions? –Makes our code easier to read –Lets us repeat code more efficiently

Creating a New Function 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

Simple Function Let’s create a function that does one thing, prints “CMPT 165” def printWord(): print “CMPT165!!!” To call this function we simply use its name: printWord() This function takes in no arguments and returns no values –All it does when we call it is print the string “CMPT165”

In-Class Trying the last function in class Adding a while loop to it

Changing our printWord() printWord is a pretty boring function Again it has no arguments and returns nothing So, let’s change it so that we can give it any string to print def printWord(wordToPrint): print wordToPrint Now when we call this function we have to provide something for it to print printWord(“CMPT165 Rules!”)

In-Class Changing printWord to take in a string

Passing Values into Functions The function printWord takes in the argument wordToPrint –wordToPrint is a variable When we call the function printWord, whatever value we put inside the () is the value that the function uses printWord(“butterfly”) printWord(“peanut”) printWord(2+4) #prints 6 The value in parenthesis in the function call is assigned to the argument variable

Functions with Multiple Arguments We can have functions with many arguments –As many as we want Let’s do a math example where we want to do some fancy math def fancyMath(a,b) c = a*b+b/ (a+b) +b**a print c

fancyMath(a,b), cont. fancyMath takes in two arguments –Need to be numbers (either ints or floats) When we call the function fancyMath we have to put in two values for a and b fancyMath(2,3) fancyMath(5.0,1) fancyMath(num1, 3) fancyMath(num1, num2) We can use integers, floats, or variables –And any combination thereof Remember that the value we pass into the function gets stored in the variables a and b

In-Class Using fancyMath

Return Values Functions can take in any number of arguments –From 0 ->whatever you want But functions can only return one value To return a value we use the return keyword We an return numbers, strings, and any values stored in variables

Adding Return to fancyMath Right now fancyMath prints the value of c –Has the result of our fancy math calculation Instead, let’s have it return the value so we can do something else with it in the main part of the program def fancyMath(a,b) c = a*b+b/ (a+b) +b**a return c

Returning Values, cont. def fancyMath(a,b) c = a*b+b/ (a+b) +b**a return c Now fancyMath will have a value when we call it We can assign the value of that function to a variable fancyNumber = fancyMath(3,2.4)

Return Values, cont. The str() function takes in a number and returns a string But so far when using it, we’ve not assigned the value of that function to a variable before printing We can do the same thing with fancyMath print fancyMath(2, 3.5) The value that fancyMath returns is then printed

Functions, cont. If a function returns a value, we can use it as the argument for another function fancyMath returns a number But if we want to print the result along with other strings, we can convert it to a string so we can concatenate it We are using the result of fancyMath(3, 2.3) as the argument for str() print “Your result is: “ +str(fancyMath(3, 2.3))

In-Class Example Just putting it all together

Questions From this lecture you should be able to: –Use a simple while loop –Understand using counters to terminate loops –How to 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