Flow Control: Branches and loops

Similar documents
Conditionals and Recursion. Python Part 4

Decisions, Decisions. Testing, testing C H A P T E R 7

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Text Input and Conditionals

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

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

9.2 Linux Essentials Exam Objectives

Beyond Blocks: Python Session #1

How Do Robots Find Their Way?

Accelerating Information Technology Innovation

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

Visualize ComplexCities

Flow Control. So Far: Writing simple statements that get executed one after another.

Pupil Name. Year. Teacher. Target Level. Key Stage 3 Self-Assessment Year 9 Python. Spelling Test No 3. Spelling Test No 2. Spelling Test No 1

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

Introduction to Python (All the Basic Stuff)

CONTROL FLOW CREATING ALTERNATE PATHS OF EXECUTION USING: BRANCHING WHILE LOOPS FOR LOOPS

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

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

Hacettepe University Computer Engineering Department. Programming in. BBM103 Introduction to Programming Lab 1 Week 4. Fall 2018

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Chapter 8 Statement-Level Control Structures

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Simple Java Programming Constructs 4

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

MEIN 50010: Python Flow Control

Unit E Step-by-Step: Programming with Python

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Repetition Structures

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Chapter 8. Statement-Level Control Structures

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

LECTURE 5 Control Structures Part 2

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Introduction to Programming

Theory of control structures

Python Programming Exercises 3

Software Design & Programming I

Programming Fundamentals

Introduction to Python Code Quality

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Slicing. Open pizza_slicer.py

An Introduction to Python

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

CS100: CPADS. Decisions. David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania

CS 112: Intro to Comp Prog

DCS/100: Procedural Programming

CSI33 Data Structures

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

Introduction to Programming

Module 4: Decision-making and forming loops

Chapter 2 Writing Simple Programs

Algorithms and Data Structures

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Introduction to Programming

Introduction. C provides two styles of flow control:

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

(Refer Slide Time: 00:26)

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

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

Python: common syntax

TUPLES AND RECURSIVE LISTS 5

CS 1301 Exam 1 Fall 2010

Python 1: Intro! Max Dougherty Andrew Schmitt

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

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Flow Control. CSC215 Lecture

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

4.2 Function definitions the basics

Variable and Data Type I

Python for Informatics

CS50 Supersection (for those less comfortable)

CMSC 201 Computer Science I for Majors

In Delphi script, when values are assigned to variables, the colon-equal operator is used; :=

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

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Intro. Scheme Basics. scm> 5 5. scm>

Python for Non-programmers

Senthil Kumaran S

Chapter 8. Statement-Level Control Structures

MATLAB Operators, control flow and scripting. Edited by Péter Vass

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

DSC 201: Data Analysis & Visualization

Begin to code with Python Obtaining MTA qualification expanded notes

Computers and FORTRAN Language Fortran 95/2003. Dr. Isaac Gang Tuesday March 1, 2011 Lecture 3 notes. Topics:

Introduction to Python

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Python for Non-programmers

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Review Functions Subroutines Flow Control Summary

CS1 Lecture 3 Jan. 22, 2018

Transcription:

Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the simplest of scripts, the instructions will get carried out in sequence starting from the top and running one by one until all the instructions have been executed. In more sophisticated scripts and programs you might need to have more complex structures in your program. There are three key types of flow control structure in Python: loops, branches, and functions. This document concerns itself with the first two of these branches and loops. Branches The execution of your program branches when it reaches a decision point where it conditionally executes one bit of code or another. This is implemented in Python using the if-statement: The if-statement consists of the word if followed by a condition terminated with a colon. The next line must be indented, in PyCharm the editor will do this for you. The number of spaces doesn t matter but 4-spaces is a common choice. All the following lines with the same level of indentation are consider part of the if-block. The block continues until it reaches a line with a different level of indentation. The statements in the block will only be executed if the expression after the word if evaluates to true. The lines following the if statement with the same level of indentation are part of the if block and will only execute if the expression in the ifstatement is true 1 P age

You can also supply alternative code to execute if the expression is false using the else keyword: In this example, it will print the first message only if the expression is true, otherwise it will print the second message. The third message is not in the if or else blocks and so will always be printed You can even chain together alternative tests in the following way using the elif keyword (this is shorthand for else if : In this case each test is executed in order until it reaches the first one to match if none match then it will execute the else-block. Loops Loops are another type of flow control that involve repetition of instructions. There are two kinds of loop in Python the for-loop and the while-loop. For-loops The for-loop is used to operate on sequences with a set of instructions for each element of the sequence. Given a list of numbers the following code would loop over all numbers in the list in order to add them up: 2 P age

In this code, first a list is created and stored in a variable called numbers. Then a variable called total is initialized to 0 this is where the sum of all the numbers will be stored. Then comes the for-loop. The for-loop repeats everything in the indented block for each element of the sequence. It starts with the first element and assigns its value to the variable I. It then carries out the instructions in the block. When those instructions are finished it moves on to the next element of the sequence, assigning the value to the variable I and executes the instructions again. The loop keeps going until it have processed every element of the sequence. A special case of a for-loop is when you just want to repeat something a set number of times: In this case the code makes use of the range() function. The function range(a,b) creates an arithmetic progression from a to b including a but excluding b. So the above code will print the following to the output: You can also use this form to loop over the element of a data structure by index making use of the len() function: This will produce the output: 3 P age

This is a little overkill since you could just loop over the elements as before. If you want to over a subset of the element of the sequence you can either use the range() function with the appropriate values or use a slice (remember from the document N_3_BasicDataStructures.pdf). An example of this might be the following which prints out the last three elements of the list: While loops The second kind of loop is the while loop. The while loop is used to continue executing the same instructions over and over again until certain specific conditions are met. A while loop looks like this: In this example, a variable is created called a and set to the value 0. The loop then begins with the keyword while followed by a condition and a colon. The indented code on the following lines is repeatedly executed until the condition in the while loop is false. The code in the loop here reads a value from the console, converts it to an integer and stores the result in the variable a. The loop will keep asking you to enter a value until you enter something other than 0. When that occurs the test in the while-statement will become false and the loop will exit. Breaking the loop If for some reason you need to break out of a loop there are two important keywords: continue and break. If you put the word continue inside a loop then when it gets executed the loop will stop the current iteration where it is without executing anything after the continue statement and go on to the next iteration of the loop. If you use the break statement inside a loop then when it gets executed it will break out of the loop and continue executing from the first instruction after the loop. 4 P age

This code demonstrates the use of break it also demonstrates the use of True which is a value that always gives a true result for a test. So this loop is endless. The only way out of the loop is via the break statement. This will only get executed when a == 0. 5 P age