PYTHON CONDITIONALS AND RECURSION : CHAPTER 5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.

Slides:



Advertisements
Similar presentations
RAPTOR Syntax and Semantics By Lt Col Schorsch
Advertisements

Introduction to Computing Science and Programming I
PYTHON TURTLE WORLD : CHAPTER 4 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
Conditional Statements Introduction to Computing Science and Programming I.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Chapter 4: Conditionals and Recursion
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
The If/Else Statement, Boolean Flags, and Menus Page 180
Chapter 4 Making Decisions
Administrative MUST GO TO CORRECT LAB SECTION! Homework due 11:59pm on Tuesday. 25 points off if late (up to 24 hours) Cannot submit after 11:59pm on Wednesday.
Intro to Robots Conditionals and Recursion. Intro to Robots Modulus Two integer division operators - / and %. When dividing an integer by an integer we.
Recitation 1 Programming for Engineers in Python.
Chapter 9 IF Statement Bernard Chen. If Statement The main statement used for selecting from alternative actions based on test results It’s the primary.
The University of Texas – Pan American
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Introduction to Python
General Programming Introduction to Computing Science and Programming I.
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.
Chapter 2 - Algorithms and Design
Computing with Numbers Zelle - Chapter 3 Charles Severance - Textbook: Python Programming: An Introduction to Computer Science, John.
Programming Training kiddo Main Points: - Python Statements - Problems with selections.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Input, Output, and Processing
PAGES:51-59 SECTION: CONTROL1 : DECISIONS Decisions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Agenda Exam #1 Review Modulus Conditionals Boolean Algebra Reading: Chapter Homework #5.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
CS102 Introduction to Computer Programming Chapter 4 Making Decisions.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Python Conditionals chapter 5
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
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.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
3 Basics © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.
Controlling Program Flow with Decision Structures.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Python Basics.
Chapter 4 Selections © Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Topics Designing a Program Input, Processing, and Output
Catapult Python Programming Wednesday Morning session
Introduction to Python
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Introduction to Programming
Presented By S.Yamuna AP/IT
Chapter 4: Making Decisions.
Selection CIS 40 – Introduction to Programming in Python
Arithmetic operations, decisions and looping
Pages:51-59 Section: Control1 : decisions
15-110: Principles of Computing
Lecture 6: Conditionals AP Computer Science Principles
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Pages:51-59 Section: Control1 : decisions
Just Enough Java 17-May-19.
Hardware is… Software is…
COMPUTING.
Presentation transcript:

PYTHON CONDITIONALS AND RECURSION : CHAPTER 5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST

BOOLEAN EXPRESSION A Boolean expression is an expression that results in either a True or False. We can test these in easily. For example >>> 5 == 2 #note the double == is used to test for equality False >>> 5 == 5 # Note that 5=5(or x=5) is really bad!! True # Other relational operators include x != yx yx>=y All of these return a True or False Note that True and False are NOT strings

LOGICAL OPERATORS There are three logical operators, and, or and not These are used as we do in English >>> True and True True >>> True and False if both true return true else false # False >>> True or False # if either is true return true True >>> not True True >>> True and not False True

FURTHER EXAMPLES >>> x=10 >>> y = 0 >>> x>5 and y == 0 True >>> x != 10 or not y == 3 True >>> x>5 and x<=20 # returns True if x is between 5 and 20 True >>> x%2==0 or x%3==0 # divisible by 2 or by 3 return True True

CONDITIONAL EXECUTION The first instruction that we will look at that uses conditions is the if statement. Here is the syntax if : statement more_statements # an example if x!=0: y = 20.0/x #makes sure the we are not dividing by 0 print y Execute these instruction only if Is True. Four space Indention is required!

ALTERNATIVE EXAMPLE if : Instruction to execute if is True else: Instructions to execute if is False # Example if (x>0): print ‘x is positive’ else: print ‘x is less than or equal to zero’

CHAINED CONDITIONALS If x<y: print ‘x is less than y’ elif x>y: print ‘x is greater than y’ else: print ‘x is equal to y’ #You can chain as many of these elif’s as you want # Lets do an example with grades

DETERMINE A LETTER GRADE FROM A NUMBER grade= ? #Assign some value here if grade>=90: print ‘I made an A’ #Note: As soon as a true is found elif grade>=80: # the remainder is skipped!! print ‘I made a B’ elif grade>=70: print ‘I made a C’ else: print ‘I better get to studying’

WE CAN ALSO PUT AN IF WITHIN AN IF Suppose we want to see if a is greater than b and c if a>b : if b>c: print a, ‘is the largest’ else: if a>c: print a, ‘is the largest’ else: print a, ‘is not the largest’ else: print a, ‘ is not the largest’ Note: This is a contrived example. There is a much easier way to do this! Think about using the and operator!!

KEYBOARD INPUT Before we look at more if-else examples we need to see how to get input (keyboard) from the person running the python program. raw_input([prompt]) If the prompt argument is present, it is written to screen without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.EOFError Example: x = raw_input(‘Enter a number:’) Prompt A string

OK, LOOK AT THIS >>> x = raw_input('Enter a number:') Enter a number:23 >>> x+3 #What will be printed? Traceback (most recent call last): File " ", line 1, in x+3 TypeError: cannot concatenate 'str' and 'int' objects WHY? So what can we do to fix it?

CONVERT IT TO AN INTEGER OR FLOAT #method 1 >>> x = raw_input('Enter a number:') Enter a number:12 >>> x=int(x) #convert x to an integer >>> x+4 16 #method 2 >>> x = int(raw_input('Enter a number:'))+4 Enter a number:23 27 What if I typed in 3.45 instead of 12

HERE IS WHAT HAPPENS >>> x = raw_input('Enter a number:') Enter a number:3.45 >>> int(x) Traceback (most recent call last): File " ", line 1, in int(x) ValueError: invalid literal for int() with base 10: '3.45' Note: float(x) will work!

SOME PROBLEMS TO CONTEMPLATE a=float(raw_input(‘Enter a:’)) b=float(raw_input(‘Enter b:’)) c=float(raw_input(‘Enter c:’)) x=float(raw_input(‘Enter x:’)) y = a*x**2+b*x+c print ‘The answer is’,y Enter a:2 Enter b:3 Enter c:4 Enter x:5 The answer is 69.0 >>>

BACK TO TURTLE_WORLD One of the problems we noticed with a random walking turtle was that it often off the screen. Let solve this problem and create a fence that the turtle is kept within. We will start by creating a simple move function from swampy.TurtleWorld import * from random import * #Moves turtle to new location #without modifing its heading def MoveTo(t,x,y): “”” t is the turtle, and x,y is the location we want to move to””” t.x=x t.y=y

DRAW THE FENCE #Draws the electric fence #with a different turtle and then removes it def DrawFence(s): “”” s is the width of the square fence “”” t=Turtle() # Create a turtle to draw the fence t.delay=.001 #Draw it real fast set_pen_color(t, 'blue') MoveTo(t,-s/2,s/2) # Go to upper left hand corner of the fence for i in range(4): fd(t,s) rt(t,90) die(t) s (0,0)

REMEMBER HEADINGS

BOUNCE OFF FENCE #Changes the heading if the turtle tries to #move outside the fence. w is the width of the fence def Bounce_off_fence(t,w): b=w/2-3 if t.x>b: #going off  t.x =b t.heading=180 if t.x <-b: #going off  t.x=-b t.heading=0 if t.y>b: #going off top t.y=b t.heading=270 if t.y<-b: #going off bottom t.y=-b t.heading=90 (0,0) headings b

THE MAIN PROGRAM RUN TURTLE AROUND IN FENCE world = TurtleWorld() fenceSize=200 DrawFence(fenceSize) bob = Turtle() set_color(bob, 'red') bob.delay=.01 pu(bob) #Turn off the drawing of the path for i in range(1000): # Take 1000 random steps Bounce_off_fence(bob,fenceSize) #remember, this changes its heading fd( bob,3) # the following creates a random number from -45 to +45 # It is used to create the directional wandering movement we see angle = random()*90-45 rt(bob,angle) wait_for_user()

HOMEWORK Rewrite the turtle-fence program so that the fence is now a circle that the turtle must stay inside of. 1.You first need to modify the DrawFence(s) to draw a circle of radius r 2.When is above is working modify Bounce_off_fence(t,r) to work with the circle. HINT: remember the distance formula you learned in algebra? Might need 3. The remainder of the code aught to work as is.