Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "INTRO2CS Tirgul 3 1. What we will cover today?  Boolean and logical expressions  Truth values  Conditional statements  while loop  for loop  range."— Presentation transcript:

1 INTRO2CS Tirgul 3 1

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

3 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

4 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

5 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

6 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

7 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

8 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)

9 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

10 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

11 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

12 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

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

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

15 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

16 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

17 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

18 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

19 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

20  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

21 “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

22 “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

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

24 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

25 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

26 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

27 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

28 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

29 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: 100 50 25 20 10 5 4 2 1 The code finds and prints all divisors of n = 100 29

30  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

31 While else What will be printed here? 31

32 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

33 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

34 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

35 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

36 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

37 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

38 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: 6.333 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: 5.285 Please enter a number: 3 The current average is: 5.0 Please enter a number: 6 The current average is: 5.111 Please enter a number: 4 The current average is: 5.0 38

39 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

40  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

41  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

42 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

43 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

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

45 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

46 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

47 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

48 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

49 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

50 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

51 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: 0.3333333333333333 The inverse of, 5 is: 0.2 The inverse of, -5 is: -0.2 The inverse of, -1 is: -1.0 51

52 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

53 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

54 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

55 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

56 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

57 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

58 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


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

Similar presentations


Ads by Google