Conditional and iterative statements

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

Lecture 12 – Loops – while loops COMPSCI 1 1 Principles of Programming.
Introduction to Computing Science and Programming I
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Computer Science 1620 Loops.
The If/Else Statement, Boolean Flags, and Menus Page 180
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Chapter 2 - Algorithms and Design
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
While Loops CMSC 201. Overview Today we will learn about: Looping Structures While loops.
Lists Computers and Programming. Agenda What is a list? How to access elements in the list? The for statement Operations on lists Looping with.
30/10/ Iteration Loops Do While (condition is true) … Loop.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 5: Structured Programming
Decision Making CMSC 201. Overview Today we will learn about: Boolean expressions Decision making.
Chapter 3: Branching and Program Flow CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
© The McGraw-Hill Companies, 2006 Chapter 3 Iteration.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
Decision Making CMSC 201 Chang (rev ).
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
Control Flow (Python) Dr. José M. Reyes Álamo.
Control structure: Selections
Lesson Objectives Aims To be able to write an algorithm in Pseudo Code
Chapter 5: Structured Programming
Selection (also known as Branching) Jumail Bin Taliba by
Making Choices with if Statements
Lecture 6 Repetition Richard Gesick.
Repetition (While-Loop) version]
Selection and Python Syntax
Python: Control Structures
Programming 101 Programming for non-programmers.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Repetition-Counter control Loop
( Iteration / Repetition / Looping )
Iterations Programming Condition Controlled Loops (WHILE Loop)
Bools & Ifs.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Logical Operators and While Loops
Writing Functions( ) (Part 5)
Selection CIS 40 – Introduction to Programming in Python
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Algorithm Discovery and Design
Do While (condition is true) … Loop
Coding Concepts (Basics)
If selection construct
3. Decision Structures Rocky K. C. Chang 19 September 2018
Selection Statements.
Comparing Strings Strings can be compared using the == and != operators String comparisons are case sensitive Strings can be compared using >, =, and.
Chapter 5: Control Structure
15-110: Principles of Computing
Flowcharts and Pseudo Code
Logical Operators and While Loops
For loops Taken from notes by Dr. Neil Moore
CHAPTER 5: Control Flow Tools (if statement)
Another Example Problem
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
CSE 231 Lab 2.
CMPT 120 Lecture 13 – Unit 2 – Cryptography and Encryption –
REPETITION Why Repetition?
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Control Structures.
Flow Control I Branching and Looping.
Presentation transcript:

Conditional and iterative statements 01204111 – Computer and Programming

Agenda Boolean expressions Conditional statements Iterative statements

Boolean Expressions A Boolean expression is an expression whose value is either True or False. Examples: Do you want the coffee? (yes/no) Is x greater than 10? (yes/no) Have you found the answer? (yes/no) Does 5 divide 153? (yes/no)

Boolean values Yes True No False

Watch out! Python is case sensitive. I.e., For Boolean constants, use: False and false are not equal. For Boolean constants, use: True, or False

How to get Boolean results Comparison operators: To get Boolean result, we compare two things Equal == Not equal != Greater than > Greater than or equal >= Less than < Less than or equal <=

How to get Boolean results Boolean operators To get Boolean results, we combine one or two Boolean results Boolean operators operators And and Or or Not not

Quick review True and True True True and False False False and True False and False not True False not False True True or True True True or False False or True False or False False

Examples of Boolean expressions Suppose that variable x is 4. Expression Value x < 5 x > 5 x <= 5 5 == x x != 5 (3!=4) and (7<5) (4>4) or (5<=10) True False True False True False True

More examples x*x + 9*x + 10 == 0 (y%2 == 0) (y%2 != 1) To check if x is a root of equation X2 + 9X + 10 = 0 x*x + 9*x + 10 == 0 To check if y is an even number (y%2 == 0) or (y%2 != 1)

Source: http://www.ryt9.com/s/prg/774090 If-statement MRT Children whose height is no larger than 140cm can enjoy a free ride. Source: http://www.ryt9.com/s/prg/774090

If-statement if statement evaluates a condition, and controls if the following statements shall be executed. The statements inside the block will be executed when the condition is True.

Example price = 40 False height<=140 True print('Hello kids') True price = 0 False print('price =',price) price = 40 price = 40 if height <= 140: print('Hello kids!') price = 0 print('price =',price)

Syntax and meaning false bool-expr true statement 1 statement 2 : statement n false Statement syntax if bool-expr: statement 1 statement 2 : statement n

Program flow control Normal sequential program x = int(input()) y = int(input()) print(x+y) print("Hello",x) z = x * y + 10 print(z)

Program flow control A program with if-statement price = 40 height <= 140 True False price = 40 if height <= 140: print('Hello kids!') price = 0 print('price =',price) When height = 160 When height = 120

Block The aligned indented statements are grouped into a block. price = 40 if height <= 140: print('Hello kids!') price = 0 print('price =',price) The aligned indented statements are grouped into a block. A condition in the if-statement decides whether the statements inside the block will be executed.

Good Bad Be careful Python uses the concept of blocks extensively. Thus, you must be very careful about indentation. Fdskfjsdlkfslkdjfdsff fdskfsdflksdlkfdsf: fddslfldskf fdsfkdsfdsfd fdkfddfdfd fdkfdlf fdslkdskslkdjsld Fdskfjsdlkfslkdjfdsff fdskfsdflksdlkfdsf: fddslfldskf fdsfkdsfdsfd fdkfddfdfd fdkfdlf fdslkdskslkdjsld Good Bad

pass-statement for empty blocks In Python, we cannot have an empty block. if height <= 140: print("I'm here") X If you want a block that does nothing, put the pass statement inside it. if height <= 140: pass print("I'm here")

Block can be nested Guess the output for various values of x. 3 5 7 9 10 x = int(input()) if x > 5: print("hello") if x < 10: print("foofoo") print("barbar") print("well") print("cheers")

Final words Indented block is a distinctive feature of Python. It is one of the reason people like Python. Be careful about indentation and blocks.

Thinking Corner 0 x = y Y = x y = x x = y t = x x = y y = t Given two variables x and y, can you swap their values? E.g., if x = 10 and y = 25, after executing your program, x = 25 and y = 10. x = y Y = x y = x x = y t = x x = y y = t This again won't work. Why? This won't work. Why?

Thinking Corner 1 A candy store sales a certain kind of candy. However, it has a condition that the number of candies must be at least some limit s. Given that variable x equals the actual number of candies you want to buy, write a program that modifies x so that it is the number of candies you end up buying. E.g., For s = 5 and x = 7, at the end x = 7. For s = 10 and x = 5, at the end x = 10.

Thinking Corner 1 (solution) if x < s: x = s

Thinking Corner 1 (function) def num_candies(want, limit): if want < limit: return limit return want limit = 20 x = int(input("How many?")) print("You should buy", num_candies(x,limit), "candies.")

Source: http://splinedoctors.com/2009/02/hurry-up-and-choose/ if – else statements Source: http://splinedoctors.com/2009/02/hurry-up-and-choose/

If-else-statement If-statement If-else-statement

if - else statement When condition is True, statements in group T will be executed. When condition is False, statements in group F will be executed. Syntax if condition: statement T1 statement T2 : statement Tn else : statement F1 statement F2 : statement Fn

Meaning Syntax condition statement T1 true statement T2 : statement Tn false statement F1 statement F2 statement Fn Syntax if condition: statement T1 statement T2 : statement Tn else : statement F1 statement F2 : statement Fn

Example for the if – else statement Check if n is an even number or an odd number. Value in N Output Even Number It is an even number. Odd Number It is an odd number. if n%2 == 0: print('It is an even number') else: print('It is an odd number')

Program Flow Control n % 2 == 0 print('It is an even number') True False print('It is an odd number')

Thinking Corner 2 Based on the following table, write a program that determines if your score will pass the exam. score Output Less than 50 You failed. Other You passed. if score<50: print('You failed.') else: print('You passed.')

Thinking Corner 3 Write a program that reads an integer and then tells if it is a positive integer, a negative integer, or a zero.

Thinking Corner 3 x > 0 x == 0 x < 0

Thinking Corner 3 x > 0 x < 0 x == 0 x > 0 x < 0 True False x == 0 False

Thinking Corner 3 x = int(input("Enter an integer:")) if x > 0: print("A positive integer") else: if x < 0: print("A negative integer") print("A zero") Note that we are using if-statement inside a block in another if-statement.

Nested if-statement An if-statements is just a kind of statements, so we can write it in a block inside another if-statement

Example: evaluation (if) You a given an exam: If you score > 8, then you are good If you score > 4 but <= 8, you pass If you score <= 4, you fail. if score > 8: print("Good") if score > 4 and score <= 8: print("Passed") If score <= 4: print("Failed")

Example: evaluation (nested-if) You a given an exam: If you score > 8, then you are good If you score > 4 but <= 8, you pass If you score <= 4, you fail. if score > 8: print("Good") else: if score > 4: print("Passed") print("Failed")

Example: evaluation (nested-if) When do you get to this line? if score > 8: print("Good") else: if score > 4: print("Passed") print("Failed") score > 8 score <= 8 and score > 4 score <= 8 and score <= 4 score <= 4

Example: evaluation (elif) if score > 8: print("Good") else: if score > 4: print("Passed") print("Failed") if score > 8: print("Good") elif score > 4: print("Passed") else: print("Failed") This flow structure can be made more clear, using elif

if – elif – else statements Source http://www.flickr.com/photos/29104098@N00/285609610/

if – elif – else statements Syntax if – elif – else – statement can be used when there are more than two choices. if condition1: statement 1 elif condition2: statement 2 elif condition3: statement 3 : : : else: statement n

if – elif – else statements condition1 . statement 1 true false condition2 statement 2 statement 3 Syntax if condition1: statement 1 elif condition2: statement 2 else: statement 3

Thinking Corner 4 Write a function fun that computes the following function def fun(x): if x <= 5: return 2*x + 10 elif x <= 20: return x*x + 10 elif x < 30: return x*x*x + 10 else: return 3*x f(x) = 2x+10, x ≤ 5 x2+10, 5 < x ≤ 20 x-10, 20 < x < 30 3x, x ≥ 30

Iterations Source: http://gamedesignconcepts.wordpress.com/2009/07/02/level-2-game-design-iteration-and-rapid-prototyping/

Repetitive work Computers are very good at doing repetitive work. But how can we "program" them to do so?

print('I like Bossanova') Repetitive Work What is the output of the following program What should we do if we want a program that prints that sentence for 2553 times? print('I like Bossanova')

Repetitive work You can do it pretty easily with while-statement. What should we do if we want a program that prints that sentence for 2553 times? count = 1 while count <= 8: print('I like Bossanova') count = count + 1

How does it work? count <= 8 print('I like Bossanova') False count <= 8 True print('I like Bossanova') count = count + 1

while-statement Syntax While the condition is True, the statements in the block inside the while statement are executed. The condition is checked before every round. Syntax while condition: statement 1 statement 2 : statement n

While-statement Syntax condition statement 1 True statement 2 : statement n False while condition: statement 1 statement 2 : statement n Syntax

Example A program that prints integers from 1 to 100 n = 1 while : print(n) n = 1 n <= 100 n += 1

Thinking Corner 5 Write a program that prints all even number from 100 down to 2 n = 100 while : while : print(n) n = 100 n >= 2 n >= 1 or if n%2 == 0: print(n) n = n - 2 n = n - 1

Thinking Corner 6 Write a function sum_to(n) that computes 1 + 2 + … + n. Please don't use the formula n*(n+1)/2. You can start by writing a program that computes that and then turning it into a function.

Thinking Corner 6: hints You want to add 1, 2, up to n In each round: What do you want to keep? What do you want to change? condition False True

Thinking Corner 6: more hints First, think about the values 1, 2, …, n. We will use variable i to keep tracks of these number. Write a loop that do just this: ________ while ________: _________ i = 1 i <= n i += 1

Thinking Corner 6: more and more hints What do you want to do with i. Keep the summation You will need a variable for it.

Thinking Corner 6: program n = int(input()) total = 0 i = 1 while i <= n: total = total + i i = i + 1 print(total)

Thinking Corner 6: solution def sum_to(n): total = 0 i = 1 while i <= n: total = total + i i = i + 1 return total

Thinking Corner 7: Password Write a program that asks for a password until the user enters the correct one. Let the password be 'happy204111'. Enter password: sad111 Sorry. Enter password: happy111 Enter password: happy204111 Correct.

Thinking Corner 7: hints Answer the following questions: What condition do keep your loop going? What do you want to do in each iteration? What do you have to do before checking the first condition?

Thinking Corner 7: more hints pwd = input("Enter password: ") while ______________________: ____________________ print("Correct.") print("Sorry.")

Thinking Corner 7: solutions pwd = input("Enter password: ") while ______________________: _______________ ________________________________ print("Correct.") pwd != 'happy204111' print("Sorry.") pwd = input("Enter password: ")

Loop control Usually how we control the loops falls into two broad categories: Counter-controlled repetition Sentinel-controlled repetition Note: This clearly is not exhaustive. There are other ways of controlling loop.

Counter-controlled repetition Look closely on the structure of this loop. def sum_to(n): total = 0 i = 1 while i <= n: total = total+i i = i + 1 return total Initialization Condition Updates

Thinking Corner 8 Consider the following program What happen if we change the operator from >= to <= ? n = 100 while n >= 2: print(n) n = n - 2 What happen if we change this line from n = n-2 to n = n + 2

Sentinel-controlled repetition pwd = input("Enter password: ") while pwd != 'happy204111': print("Sorry.") print("Correct.") Look closely on the structure of this loop. What is the loop waiting for? It won't stop until pwd == 'happy204111'

Thinking Corner 9 total = 0 n = 0 while n >= 0: n = input('Input n : ') if n >= 0: total = total + n print('total =", total) What is this loop waiting for? It won't stop until n < 0

Thinking Corner 10 A factorial of n (denoted by n!) is defined as 1 x 2 x … x n, or 1 when n = 0. Write a function fact(n) that computes the value of n!. For the first version, you can ignore the case when n=0.