INTRO2CS Tirgul 3 1. What we will cover today?  Boolean and logical expressions  Truth values  Conditional statements  while loop  for loop  range.

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

Introduction to Computing Science and Programming I
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
Conditional Statements Introduction to Computing Science and Programming I.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
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.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Loops – While, Do, For Repetition Statements Introduction to Arrays
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
Fundamentals of Python: From First Programs Through Data Structures
The University of Texas – Pan American
4. Python - Basic Operators
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
An Introduction to Textual Programming
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
CATHERINE AND ANNIE Python: Part 4. Strings  Strings are interesting creatures. Although words are strings, anything contained within a set of quotes.
Chapter 2 - Algorithms and Design
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
If statements while loop for loop
Flow of Control Part 1: Selection
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Chapter 4: Control Structures II
Chapter 3: Branching and Program Flow CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Decision Structures, String Comparison, Nested Structures
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.
Variables, Types, Expressions Intro2CS – week 1b 1.
September 7, 2004ICP: Chapter 3: Control Structures1 Introduction to Computer Programming Chapter 3: Control Structures Michael Scherger Department of.
COMP Loop Statements Yi Hong May 21, 2015.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
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.
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.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
G. Pullaiah College of Engineering and Technology
Intro2cs Tirgul 3.
Python: Control Structures
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.
Python - Loops and Iteration
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Arithmetic operations, decisions and looping
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Conditional and iterative statements
CHAPTER 6: Control Flow Tools (for and while loops)
Another Example Problem
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

INTRO2CS Tirgul 3 1

What we will cover today?  Boolean and logical expressions  Truth values  Conditional statements  while loop  for loop  range  random 2

Remarks from ex1  Divide your code into separated sections; for example one block for circle drawing, and another one for a square.  Separation is done by empty lines (and later with functions) and comments.  Truncate long lines: code lines, comment lines and README too. Make sure that lines in the submission.pdf are well displayed 3

Syntax – reminder  Each indentation is considered a new “scope”. All statements considered to be in the same group should be indented the same.  In general you should try to code as you speak, it might just work! 4

Boolean Variables  Boolean variables are either True or False.  Note that Python's True and False are capitalized, while in most other programming languages they are not. a = True b = False 5

Boolean expressions  The standard Boolean (or logical) operators can be applied to Boolean expressions and generate more complex Boolean expressions from “atomic” ones.  Example of such operators are:  and  or  not >>> a and b >>> a or b >>> not a 6

Boolean and logical expressions  You can get a value of some boolean query using comparison and logical operations:  Is a variable grater than 5?  Is a variable is equal to another variable?  Comparison operators:  >, =, <=, is, is not  Logical operators:  and, or, not 7

Combine Boolean expressions  You can combine multiple Boolean expression  The result will always be one Boolean value: True or False  For example:  a=True  b=False  c=True 8 a and b and c ( a and (not b)) or ((not a) and b) a and b or (num > 3)

Combine Boolean expressions  You can combine multiple Boolean expression  The result will always be one Boolean value: True or False  For example:  a=True  b=False  c=True  num=17 9 a and b and c ( a and (not b)) or ((not a) and b) a and b or (num > 3) False True

Truth values - Reminder  An object is considered to be False if-and-only-if it holds one of the following values:  None  False  Zero (of any numeric type, e.g., 0, 0.0)  An empty sequance (later on), e.g., ‘’, [], ()  An empty mapping (later on), e.g., {}  Which means everything else is True! (well, almost, but for us it is everything ) 10

Strings comparison  Python support string comparison  It compare lexicographically (like a dictionary) >>> "Aa" == 'Aa' True >>> 'a' == 'A' False >>> 'Ben' > 'Avi' True >>> 'Avi' > 'Ben' False >>> 'avi' > 'Avi ' True 11

Strings comparison  Python support string comparison  It compare lexicographically (like a dictionary) >>> "Aa" == 'Aa' # Same string True >>> 'a' == 'A' # Case matter False >>> 'Ben' > 'Avi' True >>> 'Avi' > 'Ben' False >>> 'avi' > ‘Avi ' # lower cases are ‘bigger’ True 12

Strings comparison  Lexicographically order >>> '12' > '1' True >>> '12' > '2' False >>> '0' > 0 TypeError: unorderable types: str() > int() 13

Strings comparison  Lexicographically order >>> '12' > '1' True >>> '12' > '2' # Not number order! False >>> '0' > 0 # Different types TypeError: unorderable types: str() > int() 14

Boolean quiz!  What will happen here? 1. if True or int(input("insert positive number:"))>0: print("We are good to go!”) 2. if True and int(input("insert positive number:"))>0: print("We are good to go!”) 3. if 5 and True and 0: print("We are good to go!”) 4. if 5 and True and (0 or int(input("insert number"))): print("We are good to go!") 15

Conditioning – If Statement  The main reason for using Boolean expressions is to write conditions for the execution of commands  One way to do it is using the structure: if boolean-expression: statements  The statements are executed if the boolean expression is evaluated to True 16

The “if” statements family  Used to create conditional flow in the code.  Each type is used to address a certain scenario:  If “condition” holds, what needs to be performed?  If it does not, is there something else we should do?  Are there several optional conditions which can hold? 17

If Example  Assuming we, have an initialized variable time_now if time_now > 4 and time_now < 11: print('Good Morning') elif time_now > 21 or time_now < 4: print('Good Night') 18 Equivalent to: 4 < time_now < 11

If-else statement  If the condition of our if holds, we would like the program to perform some statements. If it dose not hold – would like it to do nothing!  If the condition does not hold, we might want to try something else: if :... if : else: 19

 Could there be multiple conditions which should be checked sequentially?  Used for cases where there needs to be a different behavior for each condition: This part is optional, only used when no condition is met If-elif-else statement if : elif :... else: 20

“If” examples (1)  Scenario 1:  Scenario 2: if input("enter a char") == 'a': print("You have entered 'a'!!") if input("enter a char") == 'a': print("You have entered 'a'!!") else: print("You did not enter 'a'...") 21

“If” examples (2)  Scenario 3: selected = input("enter a char") if selected == 'a': print("You have entered 'a'!!") elif selected == 'b': print("You have entered 'b'!!") elif selected == 'c': print("You have entered 'c'!!")... elif selected == 'z': print("You have entered 'z'!!") else: print("You did not enter any lowercase alphabet letter...") 22

“If” examples (2)  Although you could have just used: if selected.isalpha() and selected.islower(): print( ) else: print( ) 23

Exercise: Are the following two equivalent? if boolean_exp_1: statement_1 else: if boolean_exp_2: statment_2 else: statment_3 if boolean_exp_1: statement_1 elif boolean_exp_2: statment_2 else: statment_3 Convince yourself with a truth table 24

Loops - Motivation  Often, we want to execute a statement multiple times repetitively  Write a program that receives 2 numbers from the user and sums them up.  Write a program that receives 3 numbers from the user and sums them up.  What if we wanted a program that sums 100 numbers?  current syntax requires a single line for every print. But note that there is actually just a single action here which we need to repeat many times. 25

What is a loop?  A loop is a programming structure that contains an executable block of code that can be repeated several times.  There are two types of loops:  while loop  for loop 26

Repetition Statements  Repetition statements allow us to execute a statement multiple times repetitively; they are often simply referred to as loops  Like conditional statements, they are controlled by Boolean expressions  Python has two kinds of repetition statements: the while loop, and the for loop; the programmer must choose the right kind of loop for the situation 27

While loops  While loops should be used when we want the same operation to be performed as long as some condition is met.  Will continue to run forever if the condition is never evaluated to False  potential problems ahead! while : statement true condition evaluated false 28

While loop example  What does the following code do? n = 100 m = n while m > 0: if n % m == 0: print(m) m = m - 1 Output: The code finds and prints all divisors of n =

 There could be an additional else clause after the while (like in the “if” statement)  When the “while” condition is evaluated to false, this section is called.  It will not be called if some exception was thrown (e.g., reading a non existing file) or the loop was “broken” using the break directive. While else 30

While else What will be printed here? 31

while val < maxVal: if is_bad_value(val): #something bad happened, no money for you break val = get_new_value(val) result = gimme_da_money(val) While break What could go wrong here? 32

Breaking loops  So how can we escape from an infinite loop? One way is to invalidate the loop condition. And if that can’t be done?  Use the “ break ” directive, which tells the program to exit from its current loop and continue the regular flow of the program. 33

Continuing an iteration - 1  What happens if we do not want to continue executing the current iteration of the loop?  We could break, but what if we want to keep on running the loop, and just skip the current iteration?  For that (again - type as you would have said it) you could use: continue  Example: while : if : continue 34

Continuing an iteration - 2  So what’s the difference?  Well in this case there isn’t, its just another way to code.  Can you think about a case where there will be a difference?  If you have plenty of conditions before applying your real code – it could help making your code more clear! x=0 while x < 5: if x%2 == 1: print(x) x += 1 x=0 while x < 5: if x%2 == 0: x += 1 continue print(x) 35

Example 1  What does this code do?  What will be the final value of “val”?  What happens if we initialize val to 1? To 0? To 20? val = 3 while True: if val > 10: break val = (val-1)*2 36

Iterating average  We want to get10 numbers from the user, and after each one print the current average NUMBER_OF_ITERATIONS = 10 avg = 0 counter = 1 while counter <= NUMBER_OF_ITERATIONS: i = float(input('Enter a number: ')) avg += (i - avg) / counter print('The current average is:', avg) counter += 1 37

Iterating average NUMBER_OF_ITERATIONS = 10 avg = 0 counter = 0 while counter < NUMBER_OF_ITERATIONS: i = float(input(’Enter a number: ')) avg += (i - avg)/ (counter + 1) print('The current average is:', avg) counter += 1 Example of execution: Please enter a number: 10 The current average is: 10.0 Please enter a number: 0 The current average is: 5.0 Please enter a number: 9 The current average is: Please enter a number: 1 The current average is: 5.0 Please enter a number: 8 The current average is: 5.6 Please enter a number: 2 The current average is: 5.0 Please enter a number: 7 The current average is: Please enter a number: 3 The current average is: 5.0 Please enter a number: 6 The current average is: Please enter a number: 4 The current average is:

Nesting while/if  Everything we have learned can be nested! Meaning: if within an if, for within a for, if within a for within a while…!  This could get pretty confusing!  You should always remember the python Zen: “Simple is better”.  Try to simplify your code, and check which conditions / loops could be removed or reordered. 39

 Ask the user for a positive number until we get one. not_positive = True while not_positive: n = int(input("Please enter a ” \ "positive number: ")) if n >= 0: not_positive = False print('You entered the number:', n) Example 1 Please enter a positive number: -9 Please enter a positive number: 9 You entered the number: 9 40

 A nicer way: n = -1 while n < 0: n = int(input("Please enter a ” \ "positive number: ")) print('You entered the number:', n) Example 2 Please enter a positive number: -9 Please enter a positive number: 9 You entered the number: 9 41

Python’s Range  Python has a built in construct, range which creates an ordered collection of all integers in a given range.  For two integers a, b, range(a, b) contains all integers k satisfying a ≤ k < b.  range(b) is a shorthand for range(0,b).  range returns a list (not exactly) with the numbers in the range on demand  range(a, b, d) returns a list (not exactly) contains all integers of the form a+id, i≥0 satisfying a ≤ a+id < b. 42

The range function  Used to generate a sequence of numbers following a simple “rule”. And is used like this:  If start is omitted, it will begin at 0.  If step is specified, the numbers we will run over are: start, start+step, start+2*step, … such that the last element is the largest number (in the form of start+n*step) which is smaller than end. range([start],end[,step]) 43

The for loop  Basic Syntax: for i in range(3): print('Hello World') Hello World 44

Iterating over a string with for loop line = 'The quick brown fox jumps ' \ ‘over the lazy dog’ num_of_spaces = 0 for char in line: if char == ' ': num_of_spaces += 1 if num_of_spaces: print('There are ', num_of_spaces, ‘ spaces in the sentence’) There are 8 spaces in the sentence 45

How many iterations?  How many iterations the following loops will run?  How can you check it if you’re not sure? a. for i in range (5): b. for i in range (0,5): c. for i in range (0,5,2): d. for i in range (0,50,20): e. for i in range (0,5,8): 46

7 Boom  Go over the numbers from 1 to N, if the number is a multiplication of 7, or it contains the digit 7 print ‘Boom’ instead of the number for i in range(50): if i % 7 == 0 or '7' in str(i): print('Boom') else: print(i) 47

Create a random number import random for i in range(10): print(random.randint(1, 50), end=’, ’) 3, 40, 43, 41, 33, 43, 31, 36, 6, 31, More about random function 48

Is a random sequence contains a specific value  How many times will it be printed?  What should we do if we want it to be printed once at most? import random for i in range(10): if random.randint(1, 50) == 41: print( ’41 was randomized’ ) 49

break  The break statement terminates the current loop and resumes execution at the next statement  For example: import random for i in range(10): if random.randint(1, 50) == 41: print(’41 was randomized’) break 41 was randomized 50

continue  With “ continue ” it is possible to skip the rest of the commands in the current iteration and start from the top of the loop again. >>> for i in range(5):... x = random.randint(-5, 5)... if(x == 0):... continue... print('The inverse of, ', x, 'is:', 1/x) The inverse of, 3 is: The inverse of, 5 is: 0.2 The inverse of, -5 is: -0.2 The inverse of, -1 is:

else clause (of ‘for’ statement)  Loop statements may have an else clause; it is executed when the for loop terminates through exhaustion, but not when the loop is terminated by a break statement.  Similar to what you have seen with while loop 52

Example of ‘else’ statement has_even_number = False for i in range(10): val = random.randint(1, 50) if val % 2 == 0: has_even_number = True break if has_even_number: print(’An even number was found’) else: print(’No even number found') for i in range(10): val = random.randint(1, 50) if val % 2 == 0: print('An even number was found’) break else: print(’No even number found') 53

Game: Guess the number num_to_guess = 10 guess = None while(guess != num_to_guess): guess = int(input('Guess a number: ')) if guess < num_to_guess: print('Your guess is too low') elif guess > num_to_guess: print('Your guess is too high') else: print('You got it!') Guess a number: 1 Your guess is too low Guess a number: 10 Your guess is too low Guess a number: 50 Your guess is too high Guess a number: 13 Your guess is too high Guess a number: 11 Your guess is too low Guess a number: 12 You got it! 54

So which loop is “better”? It depends on what we want to do:  Write a program that gets numbers from the user and calculate their average, continue input until receiving -1.  Write a program that receives 20 numbers from the user and counts how many consecutive numbers were identical.  Write a program that gets positive numbers from the user until reaching exactly 100. announce the user if he successes. What happens if we passed 100? 55

Range with negative step?  Well why shouldn’t we use a negative step? Can be useful for iterating in a reversed order…  Using range(start, end, negVal) will produce the values: start, start-negVal, start-2*negVal, … such that the last element is the smallest number (in the form of start-n*negVal) greater than end. 56

Example  What will these code snippets print? (Hint: when writing list(range(0,3)) - [0,1,2] will be printed):  list(range(5,0,-1))  list(range(5,0,-3))  list(range(5,6,-1)) A nswers : [5,4,3,2,1], [5,2], [] 57

Example  Supposed you are asked to print a square with only the char ‘#’ and of some length, how would you do that?  A solution is to use a while loop (with range): print('#'*size) i = 0 while i in range(0,size-2): print('#'+' '*(size-2)+'#') i += 1 print('#'*size) ############ # ########## 58