Download Chapter 4: For Loops, Strings, and Tuples

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter Topics Covered

Chapter 4: For Loops,
Strings, and Tuples




C10061 – Introduction to Computer Programming



Kent State University

Chapter 4: For Loops, Strings, and Tuples
1
A New Look at Constants






Make programs clearer and easy to interpret
Prevents retyping or mistyping of the same value
Example: string = “Hello, World!”
STRING = “Hello, World!”
Chapter 4: For Loops, Strings, and Tuples
2
A sequence is an ordered list of elements.
The elements are arranged in order from the
first element in the sequence to the last
element.

New twist to our current naming convention—
constants use all capital letters

Chapter 4: For Loops, Strings, and Tuples
Sequences
Recall that constants are variable values that
are unchangeable.
Valuable in two ways:

A new look at constants
Sequences
For loops and their uses
String functions
Sequence operators
Indexing sequences
String immutability
Slicing sequences
Tuples
3
Example: Given five elements in a sequence, the
elements are arranged as:
Computer’s
0
reference
Element 1
1
Element 2
Chapter 4: For Loops, Strings, and Tuples
2
Element 3
3
Element 4
4
Element 5
4
1
Sequences


For Loops
One type of sequence is a string.
Every character of the string is an element.


Example: Given the string “index”, the sequence
elements would be as follows:


Computer’s
reference
0
1
2
3
4
i
n
d
e
x
Repetitious and execution is based on a
sequence.
Provides for sequential access of data.


5
For Loops


The last element processed ends the loop.
Chapter 4: For Loops, Strings, and Tuples
6
For Loops
Loop variables do not need to be part of the
loop body.

From element 1 to element x.
Each element is processed in the loop body.

Chapter 4: For Loops, Strings, and Tuples
Unlike while loops that execute based on a
condition.

Syntax
for variable-name-for-elements in sequence-to-process:
Actions inside the loop body may not use the
variable.
loop body
Less restrictive in Python than in other
programming languages.


Required colon
Sequence operator
Other languages require a counter variable to
control the for loop (includes generics like i, j, k).
Python allows for direct access through the
sequence—no counter variable is used.
Chapter 4: For Loops, Strings, and Tuples
Reserved word in Python
7
Chapter 4: For Loops, Strings, and Tuples
8
2
For Loop Uses

For Loop Uses
Counting with sequences: range( ) function


One argument—positive number

Sequence range generated is 0 < positive number
Counting with sequences: range( ) function


Example: range(7)
will generate the sequence of
[0, 1, 2, 3, 4, 5, 6]
Three arguments—starting point, ending point,
number to count by
Sequence range generated is beginning point
< ending point with intervals determined by
number to count by
Example: range(5,-5,-1)
will generate the sequence of
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
Chapter 4: For Loops, Strings, and Tuples
9
String Functions

One argument needed

Argument may be any sequence


A specific string

Result of an I/O read
10
Sequence Operators
Counting sequence lengths: len( ) function

Chapter 4: For Loops, Strings, and Tuples

Checking existence or conditions: in operator


Use anywhere in a Python program
To check if an element is a member of a
sequence (single member only or an error).
Syntax: for element-to-check-for in sequence-to-check:
The length of the sequence is returned

The number of elements in the sequence

Includes all characters, spaces and symbols

To create a condition to check.
Syntax: if element-to-check-for in sequence-to-check:
Chapter 4: For Loops, Strings, and Tuples
11
Chapter 4: For Loops, Strings, and Tuples
12
3
Indexing Sequences



Indexing Sequences
Recall that all sequences are stored
sequentially, one element after another.
What if you want to access the fourth element
only?
Use indexing for random access.

Computer’s
0
1
2
3
4
Element 1
Element 2
Element 3
Element 4
Element 5
reference
Chapter 4: For Loops, Strings, and Tuples


13
1
2
3
4
Element 1
Element 2
Element 3
Element 4
Element 5
-4
-3
-2
-1
-5
Chapter 4: For Loops, Strings, and Tuples
Specify the index location as part of the variable.

Positive index is for sequential or positive random

Negative index is for negative random
Chapter 4: For Loops, Strings, and Tuples

0
Negative index

14
String Immutability
Computers begin counting at zero.
The range of sequence elements is 0 to
sequence length – 1.
Attempting to access beyond the bounds of a
sequence will result in an IndexError.
Positive index
Assign a sequence to a variable.
where x is the specific element to access.
Note:


Example: variable-name[x]
Indexing Sequences

Steps needed:


Sequences may be changeable (mutable) or
unchangeable (immutable).
Strings fall into the immutable category.
If we attempt to change the element in a
string through an assignment statement, an
error is generated (TypeError).
Example: string = “name”
string[0] = “s” will generate an error
15
Chapter 4: For Loops, Strings, and Tuples
16
4
String Immutability

Slicing Sequences
To “change” a string, create a new string.




Each character of a string is an element.
Elements may be concatenated, thus creating a
new string.
May be accomplished through a for loop and by
using the augmented assignment (+=) operator.




Example: user_input = raw_input(“Enter some text: “)

for i in user_input:

new_string =+ i

Chapter 4: For Loops, Strings, and Tuples
17
Slicing Sequences


1
Slice points may be positive or negative
Chapter 4: For Loops, Strings, and Tuples

Both may be positive
Both may be negative
One may be positive and one may be negative
0
A beginning slice point
An ending slice point
2
3
4
Avoid the impossible slice




5
Results from starting point > ending point
Results from backward references
Produces an empty slice (no error generated)
Examples: [4:3], [-1,-3], [1:-5], [-2:0]
0
Element 1
Element 2
Element 3
Element 4
1
-4
-3
-2
3
4
5
Element 2
Element 3
Element 4
Element 5
-1
-5
Chapter 4: For Loops, Strings, and Tuples
2
Element 5
Element 1
-5
18
Slicing Sequences
Example of slicing begin and end points:

Copy a single element like indexing
Copy all elements or the entire sequence
Copy partial elements within a range
Elements are now blocked in by two points
new_string = “ “
print new_string

Used to copy continuous sections of
elements (slices) in a sequence.
19
-4
Chapter 4: For Loops, Strings, and Tuples
-3
-2
-1
20
5
Slicing Sequences: Shorthand

Omit the start point [:3]



Starts at the first element of the sequence
Ends at the last element of the sequence
Omit both the start point and the end point [:]


Returns a “copy” of the entire sequence
Useful for quick copying and efficient
programming
Chapter 4: For Loops, Strings, and Tuples
21
Tuples

Create by naming the tuple and enclosing
the values within ( )

Numbers (integer or float)

Strings and numbers combined

Any type represented by a variable
22
Print tuple elements directly and the result
will appear on a single line.
Example: tuple = (1, “For”, “you and me”)
print tuple
Tuple with values

Strings
Chapter 4: For Loops, Strings, and Tuples

Example: empty_tuple = ( )


Tuples
Empty tuple

Another type of sequence where the
elements may be any of the following:
Omit the end point [1:]


Tuples
will generate the result of
Create by separating values by commas and
enclosing them within ( )
(1, ‘For’, ‘you and me’)
Example: string_tuple = (“value1”, “value2”)
number_tuple = (7,10)
combo_tuple = (1,”text”)
Chapter 4: For Loops, Strings, and Tuples
23
Chapter 4: For Loops, Strings, and Tuples
24
6
Tuples

Tuples
Print tuple elements using a loop and the
elements will print on separate lines.

What else may be done with tuples?

Example: tuple = (“I plan”, “to program”,
Everything that is done with sequences

“in Python”)


for i in tuple:

print i

will generate the result of

I plan
to program
Obtain a length
Check for a condition by using the in operator
Index sequentially or randomly
Slice
Concatenate
Final note: Tuples are immutable so copying
a tuple requires creating a new tuple.
in Python
Chapter 4: For Loops, Strings, and Tuples
25
Chapter 4: For Loops, Strings, and Tuples
26
7