Lab 5 - Repetition. September 26, 2018

Similar documents
ME30 Lab3 Decisions. February 20, 2019

ME30_Lab1_18JUL18. August 29, ME 30 Lab 1 - Introduction to Anaconda, JupyterLab, and Python

Text Input and Conditionals

Chapter 2: Functions and Control Structures

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

LOOPS. Repetition using the while statement

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Programming for Experimental Research. Flow Control

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Statements 2. a operator= b a = a operator b

This is the basis for the programming concept called a loop statement

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Quiz 1: Functions and Procedures

Introduction. C provides two styles of flow control:

Flow Control: Branches and loops

ENGR 102 Engineering Lab I - Computation

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Flow Control. CSC215 Lecture

Conditionals and Recursion. Python Part 4

Ph3 Mathematica Homework: Week 1

Control of Flow. There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests.

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Score score < score < score < 65 Score < 50

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

5. Control Statements

Lecture 4 8/24/18. Expressing Procedural Knowledge. Procedural Knowledge. What are we going to cover today? Computational Constructs

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

3 The L oop Control Structure

Programming Lecture 4

The compiler is spewing error messages.

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

Introduction to Computer Programming for Non-Majors

REPETITIVE EXECUTION: LOOPS

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

Repetition CSC 121 Fall 2014 Howard Rosenthal

Chapter 13 Control Structures

CMSC 201 Fall 2018 Lab 04 While Loops

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Loop structures and booleans

Activity Guide - Will it Crash?

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Lecture 10. Daily Puzzle

Repetition, Looping. While Loop

CS 106 Introduction to Computer Science I

EE 355 Lab 3 - Algorithms & Control Structures

Programming Lecture 4

STUDENT LESSON A12 Iterations

(Ca...

Repetition, Looping CS101

Lecture 4. Conditionals and Boolean Expressions

Chapter 13. Control Structures

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

(Python) Chapter 3: Repetition

APCS Semester #1 Final Exam Practice Problems

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

CS Summer 2013

The for Loop. Lesson 11

Advanced Computer Programming

CS 112: Intro to Comp Prog

Python Programming: An Introduction To Computer Science

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Computer Science Lab Exercise 1

Algorithms and Data Structures

Chapter 4: Conditionals and Loops

Lecture 7 Tao Wang 1

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Repetition Structures II

LSMW (Legacy System Migration Workbench) Published by Team of SAP Consultants at SAPTOPJOBS Visit us at.

Chapter 8 Statement-Level Control Structures

Starting chapter 5. l First open file, and say purpose read or write inputfile = open('mydata.txt', 'r') outputfile = open('myresults.

Control Structures. Important Semantic Difference

Loops / Repetition Statements

Chapter 8. Statement-Level Control Structures

CMSC 201 Spring 2019 Lab 06 Lists

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

CMSC 201 Spring 2017 Lab 12 Recursion

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

KAREL UNIT 5 STUDENT JOURNAL REVISED APRIL 19, 2017 NAME SCHOOL, CLASS, PERIOD

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

CSE 115. Introduction to Computer Science I

Introduction to VPython This tutorial will guide you through the basics of programming in VPython.

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Unit 3 Decision making, Looping and Arrays

Fundamentals of Programming (Python) Control Structures. Sina Sajadmanesh Sharif University of Technology Fall 2017

Lecture 04 More Iteration, Nested Loops. Meet UTA Jarrett s dog Greta, lying in her nest

Recap: Assignment as an Operator CS 112 Introduction to Programming

Decision Control Structure. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Transcription:

Lab 5 - Repetition September 26, 2018 1 ME 30 Lab 5 - Repetition ME 30 ReDev Team Description and Summary: This lab introduces the programming concept of repetition, also called looping, where some operations in a section of code are repeated multiple times. This lab exploration will focus on the two main repetition constructs in Python: 1. While loops (which are condition-controlled) 2. FOR loops (which are sequence-controlled) Use the ME 30 Lab Report JupyterLab notebook template to write your lab report. *** 1.1 While Loops While loops have a conditional expression that is evaluated prior to the execution of the code to be repeated. If the condition is satisfied (True), the subsequent lines to be repeated are executed. After they are executed, the condition is checked again, and if satisfied, the block of code is executed again. If the condition is not satisfied (False), the code in the repetition block is skipped. While loops are especially useful when you want to repeat execution of code an unknown number of times, but where you can formulate a logical test for when the loop must end. The figure below graphically depicts how the while loop works: The form of the while loop in Python code is shown below. [Note: the parentheses around the condition are actually NOT required! However, using parentheses probably will result in more readable code, and it is good practice, especially if you want to learn the C programming language (where they are required for a while loop.] Just like with functions and if/if-else/if-elif-else code blocks, the statements that the while condition controls are indented (customarily by 4 spaces): while (condition): statements to execute In your lab report notebook, try this simple example in a Python code cell: i = 1 while ( i <= 10 ): 1

While loop structure Python running print( "Done with the loop! " ) print( "i now has the value of", i ) print( "Can you see why?" ) The last line in the indented code block increments the value of i by 1 each time the code block is repeated. After that line executes, the new value of i is tested in the condition of being less than or equal to 10. If the value of i satisfies the condition (True), the indented code is executed again. If the condition is not satisfied (False), then control passes to the first non-indented print statement, and then continues to the last two print statements. A short-hand for the the statement i = i + 1 is: i += 1 Try this statement in place of the earlier one, and see if you get the same result. [Note: when you work with repetition structures, it is likely that at some point you will introduce a program bug, such that condition you are testing for never becomes false, and you end up being stuck in the loop. Python won t tell you that you made a mistake in this way, but you can get an indication that this might be happening in the JupyterLab notebook by looking just to the left of your code cell. While the code in the cell is running, you will see an asterisk appear inside the square braces: If the asterisk never goes away, your code is still running. For simple programs that don t handle much data, the asterisk should disappear almost immediately. If it lingers for longer than 2

Restart the kernel it should, you may be caught in an infinite loop. To break out of an infinite loop in the JupyterLab notebook, just restart the kernel: If you are running Python code from a terminal window or within an IDE like Spyder, pressing CTL+C will usually stop execution of the code. 1.1.1 Breaking out of a repetition loop Sometimes you might want to break out of the loop even if the condition controlling the loop is satisfied (True). For example, consider this snippet of code: i = 1 while ( i <= 10 ): if ( i == 5 ): print( "i is 5; We're 'outta here!" ) break Try it out in a Python code cell in your lab report notebook. Report on what happens in a Markdown cell. 1.1.2 Skipping some code in a repetition loop without breaking out of the loop Sometimes you might want to skip executing a portion of the code block being repeated when some condition occurs, but not completely terminate the loop. This can be done using the continue keyword. Consider the snippet of code below: i = 1 while ( i <= 10 ): if ( i > 3 and i < 8 ): continue Try this snippet in a Python code cell in your lab report notebook. Report on what happens in a markdown cell. 3

1.2 For Loops For loops are the other way to repeat code in a controlled manner, and are especially useful for iterating over a sequence that you have defined or where you can specify the number of times the loop should operate. The form of a for loop is shown below: for variable in some_sequence: statements Consider the snippet of code below: names = [ 'John', 'Roberto', 'Hua', 'Emma' ] for name in names: print( name ) Try this snippet in a Python code cell in your lab report notebook. Report on what happens in a markdown cell. The first line of the code snippet created a list of strings (first names). The second line essentially creates a variable, called name, that is then used in the for loop to index through the list of names and print them out. The indexing and printing loop repeats until the sequence has been exhausted. The keywords break and continue work similarly in for loops as they do in while loops, and it is also possible to use an else alternative like was done with decision structures to be executed when the condition in the for loop is not satisfied. 1.3 Exercise 1 - Using repetition Build on the last example and what was explained earlier, to write a short program that will print out all the names in the list except Roberto s. 1.3.1 Ranges It is often useful to have a numeric index for many applications, especially in a for loop. This is such a common need that Python as a built-in function called range() that generates a sequence of numbers, and is extremely useful in for loops. For example, consider the code snippet below: for i in range(10): Copy this snippet into a Python code cell and run it. What number does the sequence generated by range(10) start with? What does it end with? Note your observations in a Markdown cell below your code. You will get more instruction about sequences later in the course, but check out the Python documentation" (section 4.6.6) to learn a bit more about it now. As the documentation explains, range() can alternatively take a start value, a stop value, and a step value. 4

54321 asterisk pattern 1.4 Exercise 2 - Using a for loop to print a countdown In a new code cell, explore the full potential of the range() function by modifying the range() code you were just exploring, but make it so it will count down (i.e., print sequentially the values from 10 to 1), and then print "Blast off!" *** 1.4.1 Nesting for loops Just like with decision structures, for loops can be nested, where the outermost loop will control the number of times that the inner loop is repeated. Nesting for loops is often done to index data structures such as matrices, where rows are accessed using one index (say the outer for loop), and the columns are accessed using another index (the inner for loop). Consider the following example: rows = 5 for i in range( rows ): for j in range( i + 1 ): print('*', end='') print('') Enter this snippet of code into a Python code cell and run it. Note what happens: 1. A variable named row is defined and given the value 5 2. The first for statement defines a loop for indexing the number of times the inner loop will be repeated. 3. The second for loop (indented) defines a loop for how many asterisks to print. Note in the print statement, end='' causes the printing of the asterisks to be done on the same line. Leaving off this optional argument will automatically insert a linefeed at the end of each print statement. 4. The last statement doesn t print anything, but since the termination character was not specified, it just adds a linefeed. 1.5 Exercise 3 - Using nested for loops - pt 1 In a new code cell, modify the code from the example above, but make it so it will print the asterisk pattern like this: 1.6 Exercise 4 - Using nested for loops - pt 2 In a new code cell, use nested for loops to print the asterisk pattern, so it looks like this: 5

12345 asterisk pattern 1.7 Exercise 5 - Approximate Pi Using one of the Series Representations of Pi, write a program which will ask a user for the precision required and will then approximate Pi to the requested precision using one of the Series representations for Pi Wolfram Alpha approximation for Pi What is the greatest precision which your program can generate? 2 What to Turn In Ask your lab instructor what he or she wants you to submit to Canvas for this lab session. 3 References + Control Structures - Repetition from FSU: http://ww2.cs.fsu.edu/~nienaber/teaching/python/lectures/contro repetition.html + Essential Python For Loop Command Examples: https://www.t: https://stackoverflow.com/questions/493386/how-to-print-without-newline-orspacehegeekstuff.com/2017/07/python-for-loop-examples/ + How to print without newline or space: https://stackoverflow.com/questions/493386/how-to-print-withoutnewline-or-space + Jupyter Notebook Users Manual (from Bryn Mawr College) https://jupyter.brynmawr.edu/services/public/dblank/jupyter%20notebook%20users%20manual.ipynb + Adam Pritchard s Markdown Cheatsheet https://github.com/adam-p/markdownhere/wiki/markdown-cheatsheet 6