Python Loops and String Manipulation



Similar documents
Python Lists and Loops

Introduction to Python

Exercise 1: Python Language Basics

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

CS 1133, LAB 2: FUNCTIONS AND TESTING

Exercise 4 Learning Python language fundamentals

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.

Introduction to Python

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

Python Programming: An Introduction to Computer Science

CS106A, Stanford Handout #38. Strings and Chars

Turtle Power. Introduction: Python. In this project, you ll learn how to use a turtle to draw awesome shapes and patterns. Activity Checklist

Programming in Access VBA

Chapter 2 Writing Simple Programs

6.170 Tutorial 3 - Ruby Basics

PHP Debugging. Draft: March 19, Christopher Vickery

Introduction to Python for Text Analysis

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

COLLEGE ALGEBRA. Paul Dawkins

Writing Simple Programs

Python Programming: An Introduction To Computer Science

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

COMSC 100 Programming Exercises, For SP15

6. Control Structures

Outline Basic concepts of Python language

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

Programming Languages CIS 443

Chapter 15 Functional Programming Languages

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

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Base Conversion written by Cathy Saxton

14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06

Hypercosm. Studio.

SQL Server Database Coding Standards and Guidelines

Computer Science for San Francisco Youth

A Python Tour: Just a Brief Introduction CS 303e: Elements of Computers and Programming

Udacity cs101: Building a Search Engine. Extracting a Link

Introduction to Computer Science I Spring 2014 Mid-term exam Solutions

Week 2 Practical Objects and Turtles

The first program: Little Crab

Informatica e Sistemi in Tempo Reale

Moving from CS 61A Scheme to CS 61B Java

STEP 0: OPEN UP THE PYTHON EDITOR. If python is on your computer already, it's time to get started. On Windows, find IDLE in the start menu.

Object Oriented Software Design

2 The first program: Little Crab

Chapter 13: Program Development and Programming Languages

Line Tracking Basic Lesson

Chapter 9: Building Bigger Programs

Comparing RTOS to Infinite Loop Designs

BUSINESSLINE FEATURES USER GUIDE. Do more with your business phone

Welcome to Introduction to programming in Python

CSC 221: Computer Programming I. Fall 2011

understanding sensors

Introduction to Data Structures

Lab 2: Swat ATM (Machine (Machine))

mouse (or the option key on Macintosh) and move the mouse. You should see that you are able to zoom into and out of the scene.

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Problem Solving Basics and Computer Programming

Object Oriented Software Design

SPECIAL REPORT INFUSIONSOFT: 7 KEYS TO TOP RESULTS. What s Inside? OVERVIEW KEY # 1: RESPECT YOUR AUDIENCE

How to Make Money with Google Adwords. For Cleaning Companies. H i tm a n. Advertising

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Hands-on Exercise 1: VBA Coding Basics

River Dell Regional School District. Computer Programming with Python Curriculum

Once the schema has been designed, it can be implemented in the RDBMS.

Python Programming: An Introduction to Computer Science

AN INTRODUCTION TO MACRO VARIABLES AND MACRO PROGRAMS Mike S. Zdeb, New York State Department of Health

Invitation to Ezhil : A Tamil Programming Language for Early Computer-Science Education 07/10/13

Part 1 Foundations of object orientation

Introduction to Python

Limitation of Liability

UGBA 103 (Parlour, Spring 2015), Section 1. Raymond C. W. Leung

Chapter 2. Making Shapes

Selecting Features by Attributes in ArcGIS Using the Query Builder

Subnetting Examples. There are three types of subnetting examples I will show in this document:

How to Create a Campaign in AdWords Editor

VLOOKUP Functions How do I?

Visual Basic Programming. An Introduction

Section 1.5 Exponents, Square Roots, and the Order of Operations

Objectives. Python Programming: An Introduction to Computer Science. Lab 01. What we ll learn in this class

Formal Languages and Automata Theory - Regular Expressions and Finite Automata -

Gas Dynamics Prof. T. M. Muruganandam Department of Aerospace Engineering Indian Institute of Technology, Madras. Module No - 12 Lecture No - 25

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Concepts in IP Addressing...

LEARNING TO PROGRAM WITH PYTHON. Richard L. Halterman

Some Scanner Class Methods

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

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

Beginning to Program Python

The Basics of Robot Mazes Teacher Notes

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

MEDIABURST: SMS GUIDE 1. SMS Guide

JavaScript: Control Statements I

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. January 04, Python Software Foundation

Advanced Programming with LEGO NXT MindStorms

Transcription:

WEEK TWO Python Loops and String Manipulation Last week, we showed you some basic Python programming and gave you some intriguing problems to solve. But it is hard to do anything really exciting until you have mastered what we are covering this week. So read on 1 Loopy Python The thing about computers is that they aren t very smart, but they are extremely fast fast at doing exactly what we tell them to do over and over (and over and over) again. Last week, we introduced the if control structure that decides whether an (indented) block of code should run or not. Any control structure that repeats a block of statements is called a loop. We call each individual repetition an iteration of the loop. Almost all programming languages provide one (or more) loop control structures. Python provides two different types, the while loop and the for loop. We ll look at while loops now and save for loops for next week! 2 while loops Let s start with a simple example: >>> i = 0 >>> while i < 3: print i i = i + 1 0 1 2 A while loop is basically a repetitive version of an if statement. In fact, it uses almost exactly the same syntax: it starts with the while keyword, followed by a conditional expression i < 3 and a colon. On the next line, the block is indented to indicate which statement(s) the while controls, just like if. It works like this: while the conditional expression i < 3 is, the body of the loop is run. Here, the body consists of two statements, a print statement and i = i + 1. The variable i holds the number of times the body has been executed. When the program first reaches the while statement, i has the value 0. The conditional i < 3 is this time, so print i and i = i + 1 are run. At first, the i = i + 1 line might seem confusing. How can i have the same value as i + 1? The trick is to remember this is not an equality test, but an assignment statement! So, we calculate the right hand side first (take the value of i and add 1 to it), and then we assign that back into the variable i. The i = i + 1 simply adds one to (or increments) the value of i every time we go through the loop so we know how many iterations we have completed. So after the first iteration, i holds the value 1 and we go back to the top of the loop. We then recheck the conditional expression to decide whether to run the body again. When used this way, the variable i is called a loop counter. The loop keeps executing until the value of i has been incremented to 3. When this happens, the conditional expression i < 3 now False and so we jump to the statement after the loop body (that is, the end of the program in this case). c National Computer Science School 2005-2009 1

3 Anatomy of a Loop There are four things to think about when writing your own loops: starting Are there any variables we need to setup before we start a loop? This is often called loop initialisation. stopping How do we know when to stop? This is called the termination condition. doing What are the instructions we want to repeat. This will become the body of the loop control structure. changing Do the instructions change in any way between each repetition. For example, we might need to keep track of how many times we have repeated the body of the loop, that is, the number of iterations. You can use these four like a checklist to make sure the loops you write are doing what you want them to. Let s look at another example: >>> i = 0 >>> while i < 7: print i i += 2 0 2 4 6 The initialisation involves setting the loop variable to zero in i = 0. The loop will terminate when i is no longer smaller than seven i < 7. There are two statements in the body. The second one is a little different this time. Firstly, we re using a special abbreviation += for adding to an existing variable. So i += 2 is actually the same as i = i + 2. It can be used whenever you want to add something to an existing variable, and so you ll often see it for incrementing loop variables. Secondly, we re adding more than one at a time. The result is the loop will now print out all even numbers less than seven. 4 Reading multiple lines from the user So far we ve only seen examples where you know when you want to stop (e.g. before a number gets too large). However, they also work well when you don t know how many iterations you ll need in advance. For example, when you re reading multiple lines of input from the user: >>> command = raw_input( enter a command: ) >>> while command!= quit : print your command was + command command = raw_input( enter a command: ) enter a command: run your command was run enter a command: quit Here it depends on how many times it takes for the user to enter quit as the command. Rather than incrementing a loop counter, the thing that s changing involves asking the user for a new command inside the loop. 5 Common loop mistakes Loops (especially while loops) can be rather tricky to get right. Here is one mistake that is particularly common. This program is going to run for a long time: c National Computer Science School 2005-2009 2

i = 0 while i < 3: print i This program will run forever well until you turn your computer off, producing a continuous stream of 0 s. In fact, the only way to stop this infinite loop is to press Ctrl-C which terminates the program with an KeyboardInterrupt exception, which will look something like this: Traceback (most recent call last): File "example1.py", line 3, in -toplevelprint i KeyboardInterrupt The cause of the infinite loop is a very common mistake forgetting to increment the loop counter. Most loop mistakes involve starting, stopping or changing, so use the loop checklist to help debug your loops. 6 Getting pieces of a string Often we need to access individual characters or groups of characters in a string. Accessing a single character is done using the square bracket subscripting or indexing operation: >>> x[0] h >>> x[1] e You can also access strings from the other end using a negative index: >>> x[-1] d >>> x[-5] w A longer part of the string (called a substring) can be accessed by using an extended square bracket notation with two indices called a slice: >>> x[0:5] hello >>> len(x) 11 >>> x[6:11] world A slice starts from the first index and includes characters up to but not including the second index. So, the slice x[0:5] starts from the x[0] and goes up to x[5] (the space) but doesn t include it. There are a couple of shortcuts too: >>> x[:5] hello >>> x[6:] world c National Computer Science School 2005-2009 3

When the first index is zero (when taking a prefix of the sequence) the zero can be left out (like x[:5]). When the last index is the length of the string, (when taking a suffix of the sequence) the last index can be left out (like x[6:]). Negative indices work in the same way that they do for indexing. Slicing is slightly more general than indexing. The index values must fall within the length of the string, but slice indices do not have to. If the slice indices fall outside the length of the string then the empty string will be returned for all or part of the slice. Strings are also immutable, which means that once the string is constructed, it cannot be modified. For example, you cannot change a character in an existing string by assigning a new character to a subscript: >>> x[0] = X Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: str object does not support item assignment >>> You must instead create a new string by slicing up the string and concatenating the pieces, and then assigning the result back to the original variable: >>> x = X + x[1:] >>> x Xello world Every operation that looks like it is modifying a string is actually returning a new string. 7 Checking the contents of strings To check whether a string contains a particular character, all you need is the in conditional operator, like this: >>> x = hello world >>> h in x >>> z in x False The not in operator does the opposite. It returns when the string does not contain the particular character: >>> z not in x These operators also work for substrings: >>> hello in x >>> howdy not in x These conditional expressions can then be used with Python if and while loops: name = raw_input( Enter your name? ) if X in name: print Your name contains an X c National Computer Science School 2005-2009 4

8 Calling methods on strings Not only can you create new strings using operators like slicing (s[1:3]), addition ("hello" + "world") and multiplication ("abc"*3), but you can also call special functions on strings which create new strings with different properties. For instance, we can convert a string to lowercase or uppercase: >>> s = "I know my ABC" >>> s.lower() i know my abc >>> s.upper() I KNOW MY ABC We can also replace a particular substring with another substring: >>> s = "hello world" >>> s.replace( l, X ) hexxo worxd >>> s.replace( hello, goodbye ) goodbye world Notice that the convention for calling these string manipulation functions is different the string that we are manipulating comes first, followed by a period (or full stop), then the function name appears with any other info required in parentheses. These special functions that apply to a particular type of value are called methods. So for example, the s.replace( l, X ) is calling the replace method on the string stored in variable s. replace needs two additional pieces of information: the bit of the string to replace, in this case l and what to replace it with, in this case X. c National Computer Science School 2005-2009 5