Branching Python Lecture Notes PDF
Document Details
Uploaded by AffectionateCoconutTree1215
Newgiza University
2024
Tags
Related
- Python Programming PDF
- Python Base Exam Summary PDF
- Test2Review - Python Intro to IFs (2) PDF
- SDU University CSS 115: Python Programming Fundamentals Fall 2024 Lecture 4 PDF
- Introduction to Programming in Python: Conditionals I PDF
- SYSC 2006: Imperative Programming Lecture 3 - Flow of Control (Carleton University)
Summary
These lecture notes cover branching in Python, specifically if-else statements. Includes examples of logical operators, comparison operators, and how they are applied in code.
Full Transcript
Branching Week 4: Lecture 1 DATE : 19/11/2024 1 Recap 2 Recap Questions What is the output of: print(type(28)) ‘int’ print(bool(0), bool(-3.5)) False True print(10 - 4 * 2) 2 x=6 y=2 print(x**y) 36 print(x//y)...
Branching Week 4: Lecture 1 DATE : 19/11/2024 1 Recap 2 Recap Questions What is the output of: print(type(28)) ‘int’ print(bool(0), bool(-3.5)) False True print(10 - 4 * 2) 2 x=6 y=2 print(x**y) 36 print(x//y) 3 x= 13 print(x//y) 3 print(x%y) 1 3 Recap Questions- cont’d x = 75 x=x+1 print(x) 76 Whatever you enter as input, the input() function converts it a string to ___________. How many ways can we use to import a function from a library? 3 What are the types of errors that we can you get when running a program? Syntax errors Runtime errors Logical errors 4 Learning Outcomes 5 Learning Outcomes By the end of this section, you will be able to: Implement crucial programming structures of the python programming language. Correctly use the following branching functions: if, elif, else Develop algorithms using these concepts 6 Introduction 7 Outline Comparison Operators The if statement The elif statement The else statement 8 Comparison operators Comparison operators can be used to compare two values. The results is always True or False (boolean value). The following return a boolean value. Let’s revisit our operators: 9 A closer look at comparison operators x, y= 10,15 print( x == y ) >>> False print( x > y ) >>> False print( x < y) >>> True x = 15 print( x == y ) >>> True 10 Recap on logical operators Logical operators: and or not 11 A closer look at logical operators a = True b = False print( a and b ) >>> False print( a or b ) >>> True print( a and not b ) >>> True print( a and a ) >>> True 12 A closer look at logical operators >>> print( 5 > 2 and 4 < 9 ) True >>> print( 5 > 2 and 3 < 1 ) False >>> print( 2 > 5 and 3 < 1 ) False >>> print( 6 > 2 or 3 < 9 ) True >>> print( 4 > 3 or 3 < 1 ) True >>> print( 4 < 3 or 3 < 1 ) False 13 A closer look at logical operators >>> print( bool( 4 ) ) True >>> print( not 4 > 2 ) False >>> print( not 5 < 1 ) True >>> print( not ‘a’ ) False >>> print( not ’’ ) True “not” reverses the result of the operation 14 A closer look at logical operators x, y= 10,15 print( y > x and y > 20 ) >>> False print( y > x and y >> True print( y > x or y > 20 ) >>> True print( not x > 15 ) >>> True 15 The need for branching So far, the code that we have seen, is code that executes sequentially, one line after another, but what if we need the behavior of our program to be different based on certain conditions. Let’s say you need to implement a program that takes in a student’s grade and prints whether she/he has passed or failed! How do you do that? 16 The If Statement The most basic and important construct in every language is the if. We use the if statement in our daily life all the time. If the weather is nice tomorrow, I’ll go to the club. If the sea is calm in the morning, I’ll go swimming If I can get a good deal on this car, I’ll buy it. In all the above examples, an action is only taken is a condition is met. 17 Writing an if statement in Python Notice how the code is if : indented to mark all statements that will be executed if the condition is met is always a Boolean expression that will evaluate to either True or False. The : signals the start of the block of statements to be executed of the condition is True. will ONLY be executed if the evaluates to True. Whether the statements within the if statement execute or not, the program will resume executing, once there are no more indented statements. This is marked by 18 Example 1: x = int(input("Enter a number:")) if x > 6: print("the number is greater than 6 ") print("Done.") What will the output be if the input is 10? What will the output be if the input is 3? 19 Exercise Write code that asks the user to enter a number, and then lets him/her know whether the number is even. Answer: x = int(input("Enter a number:")) if (x % 2) == 0: print("This number is even!") print("Done.") 20 Example 2 Let’s go back to the example we started with, which is telling a student whether she/he passed or failed: g = int(input("Please enter your grade:")) if g >= 40: print("You have passed :)") But how do we represent failure? Answer: Use else 21 else The else keyword catches anything which isn't caught by the preceding conditions. g = int(input("Please enter your grade:")) if g >= 40: print("You have passed :)") else: print("You have failed :(") 22 Another else example x = int(input('Input a value for x: ')) y = int(input('Input a value for y: ')) if x > y: print("x is greater than y") else: print("x is not greater than y") print('Done checking') 23 elif In some cases, we need more than two possibilities or two branches. One way to achieve this is by using a chained conditional statement, using the elif keyword. elif stands for else if and means try this block only in the case where the if condition is not true. 24 elif example x = int(input('Input a value for x: ')) y = int(input('Input a value for y: ')) if x > y: print("x is greater than y") elif x < y: print("x is smaller than y") else: print("x is equal to y") print('Done checking') 25 Summary of if-elif-else 26 Multiple conditions Using logical operators, such as and, or and not, it is possible to combine several conditions into a single if statement. # using logical and x, y, z = 10, 11, 12 if z > x and z > y: print('z is greater than x and y') 27 Multiple conditions - continued # using logical or x, y, z = 10, 11, 12 if z > x or z > y: print('z is greater than x or y’) # using logical not x, y = 10, 11 if not(x > y): print('x is not greater than y') 28 Exercise Write code that asks a student to enter his grade and then displays a message to the student depending on the grade she/he got as follows: Greater than or equal to 80, ‘Well Done! Distinction’ Between 61 and 79, ‘You did good..’ Between 50 and 60, ‘You’ve passed..’ Smaller than 50, ‘You failed :(’ 29 Exercise – solution mark = int(input("Enter a grade:")) if mark >= 80: print("Well Done! Distinction") elif mark > 60: print("You did good…") elif mark >= 50: print("You’ve passed..") else: print("You failed :(") What if the user enter a mark greater than 100? 30 Short if Python allows writing an if statement in one line when you’re not using elif or else. Example: x = 10 y = 10 if x == y: print("x and y are equal") >>> x and y are equal 31 Short if else x = 11 y = 10 print("X") if x > y else print("Y") >>> X Notice how we started with the statement we want to execute if a condition is met, then followed that by the condition then by the else statement (no colon was used here… ) 32 Problem Assume we want to write a program that takes a number from the user, and depending on the number tells the user whether the number is: Divisible by both 2 and 5 Divisible by 2, but not by 5 Divisible by 5, but not by 2 Not divisible by 2, and not divisible by 5 33 Nested if else x = int(input("Enter a number: ")) if x%2 == 0: if x%5 == 0: print ("divisible by 5 and 2") else: print ("divisible by 2 not divisible by 5") else: if x%5 == 0: print ("divisible by 5 not divisible by 2") else: print ("not divisible by 2 not divisible by 5") Note that an extensive use of nested if-elif-else statements is a bad programming practice. It makes your code difficult to read and therefore difficult to maintain. 34 Consequences It is dangerous to compare the result of some computation to float with == Small inaccuracies may mean that == fails. Instead, check that the difference between the two numbers is less than a certain threshold. # inaccuracy of floating point arithmetic a = 1.2 b = 1.0 if ((a-b) == 0.2): print("do something.") print("done.") # One possible solution a = 1.2 b = 1.0 e = 0.0000001 #margin of error because of loss of precision if (0.2 - e