Control Structures 1 / 17

Similar documents
Introduction to Object-Oriented Programming

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

Python for Informatics

Conditionals and Recursion. Python Part 4

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Text Input and Conditionals

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

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

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

Introduction to Python (All the Basic Stuff)

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

Fundamentals of Programming (Python) Getting Started with Programming

SCHEME INTERPRETER GUIDE 4

Lecture 3. Input, Output and Data Types

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Getting Started with Python

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

CS1 Lecture 3 Jan. 22, 2018

Python Evaluation Rules

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Conditional Expressions and Decision Statements

Python: Functions. Thomas Schwarz, SJ Marquette University

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

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

Introduction to Bioinformatics

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

CS1 Lecture 3 Jan. 18, 2019

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

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

Real Python: Python 3 Cheat Sheet

Test #2 October 8, 2015

Visualize ComplexCities

CONTROL AND ENVIRONMENTS 1

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

CMSC201 Computer Science I for Majors

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

CIS192 Python Programming

CIS192 Python Programming

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

Advanced Python. Executive Summary, Session 1

CMSC 201 Computer Science I for Majors

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

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

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Selection Statements. Pseudocode

ENGR 101 Engineering Design Workshop

The current topic: Python. Announcements. Python. Python

CIS192 Python Programming

Programming in Python 3

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

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

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

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

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

MEIN 50010: Python Flow Control

Chapter 4: Making Decisions

CME 193: Introduction to Scientific Python Lecture 1: Introduction

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Chapter 4: Making Decisions

And Parallelism. Parallelism in Prolog. OR Parallelism

The Big Python Guide

CS150 Sample Final. Name: Section: A / B

Introduction to Python

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

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

Python 1: Intro! Max Dougherty Andrew Schmitt

61A Lecture 2. Friday, August 28, 2015

Python Programming: An Introduction to Computer Science

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

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

Conditionals: Making Choices

An Introduction to Python

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Python Tutorial. Day 2

Coral Programming Language Reference Manual

Variables, Expressions, and Statements

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Functions and Decomposition

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

Flow Control: Branches and loops

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

Python. Executive Summary

CS 115 Lecture 4. More Python; testing software. Neil Moore

CS150 Sample Final Solution

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Transcription:

Control Structures 1 / 17

Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops We ve already seen sequences of statements. Today we ll learn selection (conditional execution), and repetition. 2 / 17

Binary Values There are 10 kinds of people: those who know binary, and those who don t. 3 / 17

Python Booleans In Python, boolean values have the bool type. Four kinds of boolean expressions: bool literals: True and False bool variables expressions formed by combining non-~bool~ expressions with comparison operators expressions formed by combining bool expressions with logical operators 4 / 17

Comparison Expressions Simple boolean expressions formed with comparison operators: Equal to: ==, like = in math Remember, = is assignment operator, == is comparison operator! Not equal to:!=, like in math Greater than: >, like > in math Greater than or equal to: >=, like in math... Examples: 1 == 1 # True 1!= 1 # False 1 >= 1 # True 1 > 1 # False 5 / 17

Truth in Python These values are equivalent to False: boolean False None integer 0 float 0.0 empty string ~""~ empty list [] empty tuple () empty dict {} empty set set() All other values are equivalent to True. 6 / 17

Logical Expressions Boolean expressions can be combined using logical operators and, or, not. (1 == 1) and (1!= 1) // False (1 == 1) or (1!= 1) // True Logical expressions use short-circuit evaluation: or only evaluates second operand if first operand is False and only evaluates second operand if first operand is True What are the values of the following expressions? True and False True and 0 True and [] True and None type(true and None) False or 1 True or 1 Guard idiom: (b == 0) or print(a / b), or (b!= 0) and print(a / b) 7 / 17

The if-else Statement Conditional execution: if boolean_expression: # a single statement executed when boolean_expression is true else: # a single statement executed when boolean_expression is false boolean_expression is not enclosed in parentheses else: not required Example: if (num % 2) == 0: print("i like " + str(num)) else: print("i m ambivalent about " + str(num)) 8 / 17

Blocks Python is block-structured. Contiguous sequences of statements at the same indentation level form a block. Blocks are like single statements (not expressions - they don t have values). if num % 2 == 0: print(str(num) + " is even.") print("i like even numbers.") else: print(str(num) + " is odd."); print("i m ambivalent about odd numbers.") 9 / 17

Multi-way if-else Statements This is hard to follow: if color == "red": print("redrum!") else: if color == "yellow": print("submarine") else: print("a Lack of Color") This multi-way if-else is equivalent, and clearer: if color == "red": print("redrum!") elif color == "yellow": print("submarine") else: print("a Lack of Color") 10 / 17

Short-Circuit Evaluation Here s a common idiom for testing an operand before using it: if (kids!= 0) and ((pieces / kids) >= 2): print("each kid may have two pieces.") In this example Python uses short-circuit evaluation. If kids!= 0 evaluates to False, then the second sub-expression is not evaluated, thus avoiding a divide-by-zero error. 11 / 17

Loops Algorithms often call for repeated action, e.g. : repeat... while (or until) some condition is true (looping) or for each element of this array/list/etc.... (iteration) Python provides two control structures for repeated actions: while loop for iteration statement 12 / 17

while Loops while loops are pre-test loops: the loop condition is tested before the loop body is executed while condition: # condition is any boolean expression # loop body executes as long as condition is true Example >>> def countdown(n):... while n > 0:... print(n)... n -= 1... print( Blast off! )... >>> countdown(5) 5 4 3 2 1 Blast off! 13 / 17

for Statements for is an iteration statement iteration means visiting the elements of an iterable data structure In the for loop: >>> animal = Peacock >>> for animal in [ Giraffe, Alligator, Liger ]:... print(animal)... Giraffe Alligator Liger >>> animal Liger animal is assigned to each element of the iterable list of animals in successive executions of the for loop s body notice that the loop variable re-assigned an existing variable 14 / 17

break and else break terminates execution of a loop optional else clause executes only of loop completes without executing a break (weird - don t ever write code with for-~else~) >>> def sweet_animals(animals):... for animal in animals:... print(animal)... if animal == Liger :... print( Mad drawing skillz! )... break... else:... print( No animals of note. )... >>> sweet_animals([ Peacock, Liger, Alligator ]) Peacock Liger Mad drawing skillz! >>> sweet_animals([ Peacock, Tiger, Alligator ]) Peacock Tiger Alligator No animals of note. 15 / 17

Run-time Errors An error detected during execution is called an exception and is represented at runtime by an exception object. The Python interpreter raises an exception at the point an error occurs. The exception is handled by some exception-handling code. Here we don t handle the ValueError ourselves, so it s handled by the Python shell: >>> int( e ) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: e We can handle an exception by enclosing potentially error-raising code in a try block and handling errors in an except clause. try: code_that_may_raise_error() except ExceptionType: code_that_handles_exception() ExceptionType is optional. If left off, except clause will catch any exception. 16 / 17

Exception Handling Example >>> def get_number_from_user():... input_is_invalid = True... while input_is_invalid:... num = input( Please enter a whole number: )... try:... num = int(num)... # Won t get here if exception is raised.... input_is_invalid = False... except ValueError:... print(num + is not a whole number. Try again. )... return num... >>> get_number_from_user() Please enter a whole number: e e is not a whole number. Try again. Please enter a whole number: 3 3 For more information, see https://docs.python.org/3/tutorial/errors.html 17 / 17