ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 5 Program Control



Similar documents
Chapter 2 Writing Simple Programs

Python. KS3 Programming Workbook. Name. ICT Teacher Form. Do you speak Parseltongue?

Exercise 4 Learning Python language fundamentals

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

Crash Dive into Python

ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 6 - File IO

Sources: On the Web: Slides will be available on:

Computer Science 217

Introduction to Python

Crash Dive into Python

Python Lists and Loops

Introduction to Programming with Python Session 3 Notes

CRASH COURSE PYTHON. Het begint met een idee

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Intro to scientific programming (with Python) Pietro Berkes, Brandeis University

PYTHON Basics

Introduction to Python for Text Analysis

Python Evaluation Rules

Software Tool Seminar WS Taming the Snake

Basic Python by examples

6. Control Structures

Computer Science for San Francisco Youth

Python Programming: An Introduction to Computer Science

Python Loops and String Manipulation

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

Lecture 2 Notes: Flow of Control

Computational Mathematics with Python

What Is Recursion? Recursion. Binary search example postponed to end of lecture

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

WAYNESBORO AREA SCHOOL DISTRICT CURRICULUM INTRODUCTION TO COMPUTER SCIENCE (June 2014)

Introduction to Java

Computational Mathematics with Python

CSC 221: Computer Programming I. Fall 2011

Unit 6. Loop statements

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Introduction to. Marty Stepp University of Washington

JavaScript: Control Statements I

Advanced Functions and Modules

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Python Programming: An Introduction to Computer Science

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

Conditional Statements Summer 2010 Margaret Reid-Miller

The Prime Numbers. Definition. A prime number is a positive integer with exactly two positive divisors.

1. Give the 16 bit signed (twos complement) representation of the following decimal numbers, and convert to hexadecimal:

Python Basics. S.R. Doty. August 27, Preliminaries What is Python? Installation and documentation... 4

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Writing Control Structures

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Example of a Java program

Lecture Notes on Linear Search

River Dell Regional School District. Computer Programming with Python Curriculum

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Automating SQL Injection Exploits

Programming with Data Structures

Bash shell programming Part II Control statements

Computer Programming Tutorial

Exercise 1: Python Language Basics

Python Programming: An Introduction to Computer Science

CS106A, Stanford Handout #38. Strings and Chars

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Answers to Review Questions Chapter 7

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

6. Standard Algorithms

for while ' while ' for * for <var> in <sequence>: <body> $ %%" 0 *0

Exercise 0. Although Python(x,y) comes already with a great variety of scientic Python packages, we might have to install additional dependencies:

Regression Verification: Status Report

Algorithm Analysis [2]: if-else statements, recursive algorithms. COSC 2011, Winter 2004, Section N Instructor: N. Vlajic

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Python Programming: An Introduction To Computer Science

Python for Education. Learning Maths & Science using Python and writing them in L A TEX

Introduction to Python

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Section IV.1: Recursive Algorithms and Recursion Trees

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Wrocław University of Technology. Bioinformatics. Borys Szefczyk. Applied Informatics. Wrocław (2010)

LEARNING TO PROGRAM WITH PYTHON. Richard L. Halterman

IVR Studio 3.0 Guide. May Knowlarity Product Team

13 Classes & Objects with Constructors/Destructors

NLP Programming Tutorial 0 - Programming Basics

Python Programming: An Introduction to Computer Science

Introduction to Python

Stacks. Linear data structures

Python for Rookies. Example Examination Paper

Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

Data Structures and Algorithms Lists

Chapter 3 Writing Simple Programs. What Is Programming? Internet. Witin the web server we set lots and lots of requests which we need to respond to

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

Outline Basic concepts of Python language

Transcription:

ESCI 386 Scientific Programming, Analysis and Visualization with Python Lesson 5 Program Control 1

Interactive Input Input from the terminal is handled using the raw_input() function >>> a = raw_input('enter data: ') Enter data: 45 >>> a '45' 2

Interactive Input (cont.) The raw_input() function treats all input as a string. If we wanted to bring in numerical data we have to convert it using either the float or int functions. >>> a = raw_input('enter data: ') Enter data: 34.7 >>> a = float(a) >>> a 34.7 3

Interactive Input (cont.) We could do the conversion all on one line >>> a = float(raw_input('enter data: ')) 4

Input of Multiple Values To input multiple values on one line we have to be creative, using the split method for strings. >>> in_string = raw_input('enter three numbers: ') Enter three numbers: 45.6, -34.2, 9 >>> x, y, z = in_string.split(',') >>> x, y, z ('45.6', ' -34.2', ' 9') 5

Code Blocks A code block consists of several lines of code that are uniformly indented. Code blocks can be used with if, else, elif, for, and while statements, as well as others. For this class: My preference is 4 spaces for indents, but you can use any number between 2 and 4 Be uniform! Pick an indent number and stick with it. 6

Conditional Statements Conditional statements include the if, then, and elif constructs. The form for a simple if statement is if condition: any statements to be executed if the condition is true go here, all indented by the same amount 7

Conditional Statements with else If there are also statements to be executed if the condition is not true, then the else statement is used as follows: if condition: any statements to be executed if the condition is true go here, all indented by the same amount else: any statement to be executed if the condition is false go here, again all indented by the same amount 8

Multiple Conditions If there are multiple conditions to consider, then the elif statement is used: if condition1: any statements to be executed if condition1 is true go here, all indented by the same amount elif condition2: any statements to be executed if condition2 is true go here, all indented by the same amount elif condition3: any statements to be executed if condition3 is true go here, all indented by the same amount else: any statement to be executed if none of the previous conditions are true go here, again all indented by the same amount 9

Single-line Conditional Statements Python does contain a single line form of an if-else statement. This has the form expression1 if condition else expression2 In this construct, expression1 is executed if condition is True, while expression2 is executed if condition is False. >>> x = 5 >>> print('yes') if x <=10 else 'No' Yes >>> x = 12 >>> print('yes') if x <=10 else 'No' No 10

Loops Looping in Python is accomplished using either the for or the while statements The most common way to loop is to use the for statement. The for statement requires an iterable object such as a list, a tuple, a range, an array, or even a string. 11

for Loop The basic construct for a for loop is for elem in iterable_object: statements to be executed within loop. For each pass through the loop the next item in the iterable object is passed to the variable elem. elem can be any valid variable name. It should be a new variable, not one already used. 12

for Loop Example >>> for n in [1, 3, 'hi', False]: print(n) 1 3 hi False 13

for Loop Example >>> for n in range(-5,30,5): print(n) -5 0 5 10 15 20 25 14

>>> for n in 'Hello': print(n) H e l l o for Loop Example 15

for Loop Example >>> b = [(1, 4, 3), (-3, 5, 2), (7, 1, -3)] >>> for x, y, z in b: s = x + y + z print(x, y, z, s) (1, 4, 3, 8) (-3, 5, 2, 4) (7, 1, -3, 5) 16

Using enumerate() The enumerate() function converts an iterable object into an enumerator object This allows the index of the elements to be obtained. >>> a = [1, 3, 'hi', False] >>> for i, n in enumerate(a): print(i, n) (0, 1) (1, 3) (2, 'hi') (3, False) 17

while Loops The while loop construct will execute the statements within a loop as long as a condition is met. It has the form: while condition: statements to be executed while the condition remains True 18

while Loop Example >>> a = [1, 3, 4, 5, 'hi', False] >>> i = 0 >>> while a[i]!= 'hi': print(a[i]) i += 1 1 3 4 5 19

Skipping to Top of Loop with continue The continue statement can be used within a loop to skip to the top of the loop. a = [1, 3, 5, 3, -8, 'hi', -14, 33] for n in a: if n == 'hi': continue print(n) 1 3 5 3-8 -14 33 20

Breaking out of a Loop The break statement can be used to exit a loop prematurely. a = [1, 3, 5, 3, -8, 'hi', -14, 33] for n in a: if n == 'hi': break print(n) 1 3 5 3-8 21

Verifying Input with while Loop A while loop can be used to ensure that interactive input meets certain bounds. import numpy as np x = -99 while x < 0: x = raw_input('enter non-negative number: ') x = float(x) # converts input to floating point print('y = ', np.sqrt(x)) Enter non-negative number: -6 Enter non-negative number: -3 Enter non-negative number: 5 ('y = ', 2.2360679774997898) 22