an introduction to python - strings & i/o

26
An Introduction To Software Development Using Python Spring Semester, 2015 Class #4: Strings & I/O

Upload: blue-elephant-consulting

Post on 19-Jul-2015

164 views

Category:

Education


7 download

TRANSCRIPT

Page 1: An Introduction To Python - Strings & I/O

An Introduction To Software

Development Using Python

Spring Semester, 2015

Class #4:

Strings & I/O

Page 2: An Introduction To Python - Strings & I/O

First, Do It By Hand!

• Upon being handed a problem, you may first want to start coding – don’t!

• First solve the problem by hand.

• If you can’t do that, then you can’t code it.

Image Credit: blogs.msdn.com

Page 3: An Introduction To Python - Strings & I/O

The Floor Tile Problem

• A row of black and white tiles needs to be placed along a wall. For aesthetic reasons, the architect has specified that the first and last tile shall be black.

• Your task is to compute the number of tiles needed and the gap at each end, giventhe space available and the width of each tile.

• To make the problem more concrete, let’s assume the following dimensions:• Total width: 100 inches• Tile width: 5 inches

100

5”

Page 4: An Introduction To Python - Strings & I/O

Solving The Tile Problem

Total Width / Tile Size = 100 / 5 = 20 tiles

Problem:

Wrong Color!

5” 95”

10”

95” / 10” = 9.5 sets of tiles

Answer: 1 black tile + 9 sets of 2 tiles (18 tiles) = 19 tiles

Side Gap = 100” – (19 x 5”) = 100” – 95” = 5”, 5” / 2 = 2.5” on each side

Page 5: An Introduction To Python - Strings & I/O

Tile Problem Algorithm

number of pairs of tiles =

integer part of [(total width – one tile width) / (2 x one tile width)]

number of tiles = 1 + (2 x number of pairs)

gap at each end = (total width – (number of tiles x tile width)) / 2

Note: We can now solve this problem for any total width and tile width!

Page 6: An Introduction To Python - Strings & I/O

Describe The Steps Necessary For Finding A Solution To A Problem

Problem:

You put $10,000 into a bank account that earns 5 percent interest per year.

How many years does it take for the account balance to be double the original?

Page 7: An Introduction To Python - Strings & I/O

It’s All In The Description

Create a description of the steps for finding the

solution.

Each step must be clear and unambiguous, requiring

no guesswork.

Your informal description is called pseudocode.

Image Credit: http://ccechildren.wordpress.com/2010/04/15/learning-objectives-and-goals/

Page 8: An Introduction To Python - Strings & I/O

What Is An Algorithm?

An algorithm forsolving a problem isa sequence of stepsthat is unambiguous,executable, andterminating.

The existence of an algorithm is an essential prerequisite for programming a task.

You need to first discover and describe an algorithm for the task that you want to solvebefore you start programming

Image Credit: Clipart Panda

Page 9: An Introduction To Python - Strings & I/O

Say Hello To Strings!

• Your computer programs will have to process text in addition to numbers.

• Text consists of characters: letters, numbers, punctuation, spaces, and so on.

• A string is a sequence of characters.

• Example: “John Smith”

Image Credit: imgarcade.com

Page 10: An Introduction To Python - Strings & I/O

How Do We Deal With Strings?

• Strings can be stored in variables: answer = “a”

• A string literal denotes a particular string:“Mississippi”

• In Python, string literals are specified by enclosing a sequence of characters within a matching pair of either single or double quotes.

“fire truck” or ‘fire truck’

Image Credit: imgarcade.com

Page 11: An Introduction To Python - Strings & I/O

Concatenation and Repetition

• Concatenation

– Join two strings into one long string

• Vacation = “under”+”water” results in “underwater”

• How to insert a space: holiday = “Christmas”+ “ ”+”Tree” results in “Christmas Tree”

• Repetition

– Dashes = “-” * 25 creates “-------------------------”

Must be an integer

Image Credit: www.fotosearch.com

Page 12: An Introduction To Python - Strings & I/O

Converting Between Numbers and Strings

• Convert a number to a string

– str(): str(17) = “17”

– maxFallRate = str(9.8)+” meters / sec”

• “9.8 meters / sec”

• Convert a string to a number

– Integer: int(“17”) = 17

– Float: float(“17.0 ”) = 17.0

– houseNumber = int(“15715”)

Blank spaces are ignored

Image Credit: etc.usf.edu

Page 13: An Introduction To Python - Strings & I/O

Strings and Characters

• Strings are sequences of Unicode characters.

• You can access the individual characters of a string based on their position within the string.

• This position is called the index of the character.

Image Credit: www.fontspace.com

0 1 2 3 4

First Last

Page 14: An Introduction To Python - Strings & I/O

String Indexes

• name = “TILEZ”

• len(name) = 5

• name[0] = “T”, name[4] = “Z”

0 1 2 3 4

Page 15: An Introduction To Python - Strings & I/O

String Methods

• A method, like a function, is a collection of programming instructions that carry out a particular task.

Page 16: An Introduction To Python - Strings & I/O

All Characters Have Numbers

• A character is stored internally as an integer value. The specific value used for a given characteris based on its ASCII code (or Unicode code).

• Python provides two functions related to character encodings. – The ord function returns the number used to represent a given

character. ord(“A”) = 65

– The chr function returns the character associatedwith a given code. chr(65) = “A”

Image Credit: www.clipartpanda.com

Page 17: An Introduction To Python - Strings & I/O

What The Cool Kids Know

• Escape Sequences

– To include a quotation mark in a literal string, precede it with a backslash (\), like this: "He said \"Hello\""

– The backslash is not included in the string. It indicates that the quotation mark that follows should be a part of the string and not mark the end of the string. The sequence \" is called an escape sequence.

– To include a backslash in a string, use the escape sequence \\, like this:"C: \\Temp\\Secret.txt"

– Another common escape sequence is \n, which denotes a newline character. Printing a newline character causes the start of a new line on the display. For example, the statement print("*\n**\n***") prints the characters

• *• **• ***

on three separate lines

Image Credit: www.toonvectors.com

Page 18: An Introduction To Python - Strings & I/O

Input and Output

• When a program asks for user input, it should first print a message that tells the user which input is expected. Such a message is called a prompt. In Python, displaying a prompt and reading the keyboard input is combined in one operation.

– first = input("Enter your first name: ")

• The input function displays the string argument in the console window and places the cursor on the same line, immediately following the string.

– Enter your first name: █

Image Credit: blogs.msdn.com

Page 19: An Introduction To Python - Strings & I/O

Numerical Input

• The input function can only obtain a string of text from the user.

• To read an integer value, first use the input function to obtain the data as a string, then convert it to an integer using the intfunction.

numBottles = input("Please enter the number of bottles: ")

bottles = int(numBottles)

bottlePrice = input("Enter price per bottle: ")price = float(bottlePrice)

Image Credit: www.canstockphoto.com

Page 20: An Introduction To Python - Strings & I/O

Sample Program

• Write a program that reads a number between 1,000 and 999,999 from the user, where the user enters a comma in the input. Then print the number without a comma.

• Here is a sample dialog; the user input is in color:Please enter an integer between 10,000 and 99,999: 23,456

23456

Note: there are 2 different ways to solve this

problem

Page 21: An Introduction To Python - Strings & I/O

Formatted Output

• To control how your output looks, you print a formatted string and then provide the values that are to be “plugged in”.

• If the value on the right of the “%” is a string, then the % symbol becomes the string format operator.

• The construct %10.2f is called a format specifier: it describes how a value should be formatted.

– The 10 specifies the size of the field, the 2 specified the number of digits after the “.”.

– The letter f at the end of the format specifier indicates that we are formatting a floating-point value. Use d for an integer value and s for a string;

Page 22: An Introduction To Python - Strings & I/O

Formatted Output

• To specify left justification for a string, add a minus sign before the string field width:

title1 = "Quantity:“title2 = "Price:"print("%-10s %10d" % (title1, 24))print("%-10s %10.2f" % (title2, 17.29))

• The result is:Quantity: 24Price: 17.29

Image Credit: www.theindianrepublic.com

Page 23: An Introduction To Python - Strings & I/O

Python Format Specifier Examples

Page 24: An Introduction To Python - Strings & I/O

What’s In Your Python Toolbox?

print() math strings I/O

Page 25: An Introduction To Python - Strings & I/O

What We Covered Today

1. Algorithms

2. String

3. Input / Output

Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/

Page 26: An Introduction To Python - Strings & I/O

What We’ll Be Covering Next Time

1. IF Statement

2. Relational Operators

Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/