SlideShare a Scribd company logo
An Introduction To Software
Development Using Python
Spring Semester, 2015
Class #4:
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
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, given
the 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”
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
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!
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?
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/
What Is An Algorithm?
An algorithm for
solving a problem is
a sequence of steps
that is unambiguous,
executable, and
terminating.
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 solve
before you start programming
Image Credit: Clipart Panda
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
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
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
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
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
String Indexes
• name = “TILEZ”
• len(name) = 5
• name[0] = “T”, name[4] = “Z”
0 1 2 3 4
String Methods
• A method, like a function, is a collection of
programming instructions that carry out a
particular task.
All Characters Have Numbers
• A character is stored internally as an integer value. The
specific value used for a given character
is 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 associated
with a given code. chr(65) = “A”
Image Credit: www.clipartpanda.com
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: TempSecret.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
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
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 int
function.
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
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
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;
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: 24
Price: 17.29
Image Credit: www.theindianrepublic.com
Python Format Specifier Examples
What’s In Your Python Toolbox?
print() math 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/
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/

More Related Content

PPTX
Unicode 101
PDF
Python iteration
PPTX
파이선 문법 조금만더
PDF
Unicode basics in python
PPTX
The Awesome Python Class Part-3
PPTX
Python Programming Essentials - M35 - Iterators & Generators
PDF
Promoting Polymorphism
Unicode 101
Python iteration
파이선 문법 조금만더
Unicode basics in python
The Awesome Python Class Part-3
Python Programming Essentials - M35 - Iterators & Generators
Promoting Polymorphism

Similar to An Introduction To Python - Strings & I/O (20)

PPTX
An Introduction To Python - FOR Loop
PPTX
An Introduction To Python - Python Midterm Review
PDF
Introduction to programming - class 2
PDF
A01
PDF
Lec08-CS110 Computational Engineering
PPTX
Chapter 1 Python Revision (1).pptx the royal ac acemy
PPTX
Lecture 2
PPTX
#Code2Create: Python Basics
PDF
MATLAB_Practice_lect details about matlab3 (1).pdf
PPTX
20BCT23 – PYTHON PROGRAMMING.pptx
PPTX
Unit I - 1R introduction to R program.pptx
PDF
Introduction of c_language
PPTX
Review 2Pygame made using python programming
DOCX
CS150 Assignment 7 Cryptography Date assigned Monday.docx
PPSX
Programming in c
PPTX
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
PPT
All C ppt.ppt
PDF
python.pdf
PDF
Acm aleppo cpc training fifth session
PDF
ACM init() Spring 2015 Day 1
An Introduction To Python - FOR Loop
An Introduction To Python - Python Midterm Review
Introduction to programming - class 2
A01
Lec08-CS110 Computational Engineering
Chapter 1 Python Revision (1).pptx the royal ac acemy
Lecture 2
#Code2Create: Python Basics
MATLAB_Practice_lect details about matlab3 (1).pdf
20BCT23 – PYTHON PROGRAMMING.pptx
Unit I - 1R introduction to R program.pptx
Introduction of c_language
Review 2Pygame made using python programming
CS150 Assignment 7 Cryptography Date assigned Monday.docx
Programming in c
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
All C ppt.ppt
python.pdf
Acm aleppo cpc training fifth session
ACM init() Spring 2015 Day 1
Ad

Recently uploaded (20)

PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Lesson notes of climatology university.
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
master seminar digital applications in india
PDF
Classroom Observation Tools for Teachers
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Cell Types and Its function , kingdom of life
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
A systematic review of self-coping strategies used by university students to ...
Microbial disease of the cardiovascular and lymphatic systems
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Lesson notes of climatology university.
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
master seminar digital applications in india
Classroom Observation Tools for Teachers
202450812 BayCHI UCSC-SV 20250812 v17.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Cell Structure & Organelles in detailed.
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
2.FourierTransform-ShortQuestionswithAnswers.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Microbial diseases, their pathogenesis and prophylaxis
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Cell Types and Its function , kingdom of life
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Ad

An Introduction To Python - Strings & I/O

  • 1. An Introduction To Software Development Using Python Spring Semester, 2015 Class #4: Strings & I/O
  • 2. 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
  • 3. 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, given the 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”
  • 4. 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
  • 5. 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!
  • 6. 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?
  • 7. 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/
  • 8. What Is An Algorithm? An algorithm for solving a problem is a sequence of steps that is unambiguous, executable, and terminating. 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 solve before you start programming Image Credit: Clipart Panda
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 13. 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
  • 14. String Indexes • name = “TILEZ” • len(name) = 5 • name[0] = “T”, name[4] = “Z” 0 1 2 3 4
  • 15. String Methods • A method, like a function, is a collection of programming instructions that carry out a particular task.
  • 16. All Characters Have Numbers • A character is stored internally as an integer value. The specific value used for a given character is 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 associated with a given code. chr(65) = “A” Image Credit: www.clipartpanda.com
  • 17. 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: TempSecret.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
  • 18. 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
  • 19. 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 int function. 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
  • 20. 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
  • 21. 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;
  • 22. 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: 24 Price: 17.29 Image Credit: www.theindianrepublic.com
  • 24. What’s In Your Python Toolbox? print() math strings I/O
  • 25. What We Covered Today 1. Algorithms 2. String 3. Input / Output Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
  • 26. 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/

Editor's Notes

  • #2: New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.
  • #8: Start with a year value of 0, a column for the interest, and a balance of $10,000. Repeat the following steps while the balance is less than $20,000 Add 1 to the year value. Compute the interest as balance x 0.05 (i.e., 5 percent interest). Add the interest to the balance. Report the final year value as the answer.
  • #9: The step sequence is unambiguous when there are precise instructions for what to do at each step and where to go next. There is no room for guesswork or personal opinion. A step is executable when it can be carried out in practice. Had we said to use the actual interest rate that will be charged in years to come, and not a fixed rate of 5 percent per year, that step would not have been executable, because there is no way for anyone to know what that interest rate will be. A sequence of steps is terminating if it will eventually come to an end. In our example, it requires a bit of thought to see that the sequence will not go on forever: With every step, the balance goes up by at least $500, so eventually it must reach $20,000.
  • #21: Solution 1: noComma=number.replace(",","") Solution 2: >>> print(int(noComma)) 23456 >>> print(len(number)) 6 >>> print(number[3]+number[4]+number[5]) 456 >>> print(number[0]+number[1]) 23