0% found this document useful (0 votes)
47 views10 pages

CP1 Module2 ConditionalsLoopsIterations

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
47 views10 pages

CP1 Module2 ConditionalsLoopsIterations

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 10
MODULE 2: Conditionals, Loops & Iterations CONDITIONALS Objectives After this experiment, the students will be able to: 1, Understand the concept of Boolean expressions and how to use them as a control structure in Python 2. Apply different conditional execution such as chained conditionals and nested conditionals 3. Create a simple program in Python involving conditional execution Discussion To understand conditional execution, let us first discuss the concept of Boolean expressions. A Boolean expression is an expression that is either true or false. From the discussion of the previous experiment, Boolean expressions can be demonstrated using relational and logical operators. From the examples, we can see that the result writing an expression using relational operator is either True or False. From the examples, we can see the use of the logical operators and how they interact with Boolean expressions. Please review the behavior of basic logic gates, AND, OR and NOT and their corresponding truth tables to understand why the results are like that in the examples. For us to create useful programs, we almost always need the capability to evaluate conditions and modify the behavior of the program accordingly. Conditional statements give us this ability. The most basic form of conditional execution is the if statement. statements = ne The condition after the if statement must be a Boolean expression. We end the if statement with a colon character (:) and the line(s) that follow are indented, If the logical condition is True, then the indented statement gets executed. If the logical condition is False, the indented statement is skipped ‘The next form of the conditional execution is the alternate execution. The syntax and flowchart look like this: execute statement2 execute statement! statement2 If the logical condition is True, then the indented statement! gets executed and if the logical condition is False, the second indented statement is executed as shown in the flowchart. Sometimes there are more than two possibilities that can be considered ae when making conditional execution. stotementt One way to thatiis a via chained conditional. No No stotement2 J Take note that in chained conditionals, each condition is checked in order. If the first is False, the next is checked, and so on. If one of them is True, the corresponding statement is executed and the block ends. Even if more than one condition is true, only the first true branch executes. One conditional can also be nested within another. We could have written the three- branch example like this: stotements statement2| statementd statement2 Y The first conditional statement contains two branches. The first branch is simple statement and the second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well. Take note that although the indentation of the statements makes the structure apparent, nested conditionals tend to become difficult to read. Hence, it is advised to avoid them when you can. Last, there is a conditional execution structure built into Python to handle expected and unexpected errors called “try / except” Python starts by executing the sequence of statements in the try block. If there is no error encountered, it skips the except block and proceeds. If an exception occurs in the try block, Python jumps out of the try block and executes the sequence of statements in the except block. Programming Demonstrations Programming Demo 1: Students’ Status Checker Write a program that will ask a user to input grades in Integral Calculus, Computer Programming and Physics. A grade of greater than or equal to 70 means PASSED and a grade of below 70 means FAILED. If the user has a rating of PASSED from all three subjects, the program must return a status of REGULAR. If the user has only one FAILED rating, the program must return a status of PROBATIONARY and if the user has two or more FAILED rating, the program must return a status of DISMISSED. Assume that the user will only input numerical values for their grades. 1. Type the following code on your Python script. 1 integral_calc = float(input('Input your grade ) 2. phys = float(input('Input your grade in Physics: ') 3 comp_prog = float(input('Input your grade in Come ming: ')) 4 if (integral_calc >= 70 and phys >= 70 a p_prog 5 print('Congratulations, you are REGULAR!) 6 elif({integral_cale < 70 and phys < 70) or (integral_calc < 70 and comp_prog < 70) or (comp_prog < 70 and phys < 70)). 7 print('Sorry, you are DISMISSED’) 8 else print('You are PROBATIONARY!) 2. Run the program and test different input grades for the three subjects. Make sure to use only acceptable inputs since we didn’t put a try/except block to our program. 3. Explain how logical operators are used in lines 4 and 6 to avoid using chained and nested conditionals. 4. Why does the instance of three FAILED marks (Integral Calculus, Computer Programming and Physics all less than 70) not included in writing the code for the program? Loops & Iterations Objectives After this experiment, the students will be able to: 1. Understand the different types of loops and iterations used in Python programming & programming in general. 2. Identify the situations when and where control structures for loops can be applied. 3. Write simple programs and functions using loops and iterations. Discussion Before discussing the different control structures for loops and iterations, let us review how we can update contents of a variable in Python. A common pattern in assignment statements is an assignment statement that updates a variable, where the new value of the variable depends on the old. X=X+1 In mathematics, the above statement doesn’t make any sense. However, in the context of computer programming, the statement means that we get the value of x, add 1 to it and then update x with the new value. Take note however that in Python, we cannot update a variable that doesn’t exist. Hence, we should initialize a variable before we can update it. X=0 X+1 Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement. We studied updating variables because this is the main [ossieer J foundation of loops and iterations. There are two control structures for loops and iterations in Python, programming. These are the while loop and the for loop. No The basic syntax together with the flowchart on the right and es the while loop is shown below ‘execute while biock end fe The while loop is very intuitive and very easy to understand. The syntax of the loop basically means that while the condition holds True, execute the statements inside the while block and terminate it until the condition becomes False. Take note that care must be taken when using the while loop because it may enter an infinite loop if your counter variable (ctr) is not properly updated. In some cases, one can write an infinite while loop and exit it using while True: the break statement. The idea here is the loop executes and once it encounters the break statement, it will exit the loop. Usually, break is used in conjunction with a conditional execution. break ‘Again, there are some instances that we are in an iteration of a loop and we wish to terminate the current iteration and immediately move on to the next iteration, In that case we can use the continue statement to skip to the next iteration without finishing the execution of the body of the loop for the current iteration. Continue statement is oftentimes used in conjunction with a conditional execution Here, when the condition set by the if statement is met, the while loop skips the execution of the body for that iteration and will move to the next iteration. continue Moving to the next control structure for loops and iterations, we have the for loop. The main difference [ery of this control structure is that for loops are definite loops unlike while loops which are indefinite in Yes Nature. This loop is definite in a sense that we define for how many iterations this loop will run. Oftentimes Ne for loops are useful when there is a set of known values through which our loop will run. The syntax for pecite oe, the for loop together with its flowchart is shown below. end fe otements Here, we don’t need to update our variable unlike in while loop. The for loop automatically runs for each item in the seq and terminates once it reaches the last item in the seq. for loops are not as intuitive as the while loops but it is easier to code if we have a set in which the for loop will run through. ‘As a general tip, loops and iterations are constructed by initializing one or more variables before the loop starts, performing some computation on each item in the loop body, possibly changing the variables in the body of the loop and looking at the resulting variables when the loop completes. Programming Demonstrations Programming Demo 2: Count, Sum and Mean Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the count, sum and average of the numbers entered. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number. 1. Type the following code on your Python script. 1 count=0 2 total while True: ) total = total + num mean = total/coun' print(\ninv 12 except contin = {0}, Sul (count,total,zmean)) print(‘Cou af}, Average = {2:.2ff form 2. Run the script on the Python console and use the program. Try different inputs and check the result. Also try to enter some non-numerical inputs to test the try/except block of the code. 3. Explain lines 6 and 7. What happens to the program when this if block is executed? 4. Explain what happens to lines 9, 10 and 11 every time the while block is executed? 5. When an error occurs within the try block, the program will proceed to execute the except block as discussed in the previous experiments. Explain the statements within the except block and briefly discuss what it does in the execution of the program, Write your notes here: Name: Score: Section: Date: Problem 1 Write a program that will check whether an input whole number is a multiple of S or 7. Display the result together with the number. Use try/except to handle non-whole number inputs. An example of console output is shown below: In [1]: runfile(‘C:/Users/Tim/Expt2Prob2.py', wdir="C:/Users/Tim") Enter a whole number: 13 The number 13 is NOT divisible by $ nor 7! In [2]: runfile(*C:/Users/Tim/Expt2Prob2. py", wdir='C:/Users/Tim') Enter a whole number: 35 The number 35 is divisible by 5 or 7! In [3]: runfile(*C:/Users/Tim/Expt2Prob2.py", wdir='C:/Users/Tin') Enter a whole number: Hououin Kyouma Please enter a whole nunber! Instructor's Signature: Name: Score: Section: Date: Problem 2 Write a program that guesses a mystery number! The program works as follows: you (the user) thinks of an integer between 0 to 100. The program then makes guesses, and you give it input if its guess is too high or too low. Shown below is an example of the expected console output when running the program. In [1]: runfile(*C:/Users/Tim/Expt4Prob2.py Please think of a number between @ and 100 wdire'C:/Users/Tim’) Is your number 58? (H/L/Yes): H Is your number 25? (H/L/Yes): H Is your number 12? (H/L/Yes): L Is your number 18? (H/L/Yes): H Is your number 15? (H/L/Yes): H Is your number 13? (H/L/Yes): L Is your number 14? (H/L/Yes): Yes Game over! Your mystery number is 14 Instructor's ignature:

You might also like