2-3.4 Intro Python

The Power of List Iteration

  • for in: for loop using in
  • for range: for range(start,stop,step)
  • more list methods: .extend(), +, .reverse(), .sort()
  • strings to lists,.split(), and list to strings, .join()
  • list cast & print("hello", end='')

> Student will be able to

  • Iterate through Lists using for with in
  • Use for range() in looping operations
  • Use list methods .extend(), +, .reverse(), .sort()
  • convert between lists and strings using .split() and .join()
  • cast strings to lists / direct multiple print outputs to a single line

 

Concepts

Converting a string to a list with .split()

view video

.split() by default, splits a string at spaces (" ") to create a list

tip = "Notebooks can be exported as .pdf"
tip_words = tip.split()

for word in tip_words:
    print(word)

 

Examples

In [1]:
# [ ] review and run example
tip = "Notebooks can be exported as .pdf"
tip_words = tip.split()

print("STRING:", tip)
print("LIST:", tip_words, "\n")

for word in tip_words:
    print(word)
STRING: Notebooks can be exported as .pdf
LIST: ['Notebooks', 'can', 'be', 'exported', 'as', '.pdf'] 

Notebooks
can
be
exported
as
.pdf
In [2]:
# [ ] review and run example
rhyme = "London bridge is falling down"

rhyme_words = rhyme.split()

rhyme_words.reverse()

for word in rhyme_words:
    print(word)
down
falling
is
bridge
London

 

Task 1

using .split()

In [3]:
# [ ] split the string(rhyme) into a list of words (rhyme_words)
# [ ] print each word on it's own line
rhyme = 'Jack and Jill went up the hill To fetch a pail of water' 

#Answer:
rhyme_words = rhyme.split()
for word in rhyme_words:
    print(word)
Jack
and
Jill
went
up
the
hill
To
fetch
a
pail
of
water
In [7]:
# [ ] split code_tip into a list and print the first and every other word
code_tip = "Python uses spaces for indentation"
#Answer:
code_tip_list = []
code_tip_words = code_tip.split()
for word in code_tip_words[0::2]:
    code_tip_list.append(word)
print('code_tip_list = ',code_tip_list)
code_tip_list =  ['Python', 'spaces', 'indentation']

 

Concepts

.split('-')

view video

to split on characters other than " " (space), provide .split() a string argument to use as break points

code_tip = "Python-uses-spaces-for-indentation"
tip_words = code_tip.split('-')

 

Examples

`.split('-') : split with an argument

In [ ]:
# [ ] review and run example
code_tip = "Python-uses-spaces-for-indentation"
tip_words = code_tip.split('-')

print(tip_words)
In [8]:
# [ ] review and run example - study the list print output
code_tip = "Python uses spaces for indentation"

# split on "a"
tip_words = code_tip.split('a')
print(code_tip)
print(tip_words)
Python uses spaces for indentation
['Python uses sp', 'ces for indent', 'tion']
In [9]:
# [ ] review and run example
# triple quotes ''' ''' preserve formatting such as spaces and line breaks
big_quote = """Jack and Jill went up the hill
To fetch a pail of water
Jack fell down and broke his crown
And Jill came tumbling after"""

# split on line breaks (\n)
quote_lines = big_quote.split('\n')
print(quote_lines, '\n')

# print the list in reverse with index slicing
for line in quote_lines[::-1]:
    print(line)
['Jack and Jill went up the hill', 'To fetch a pail of water', 'Jack fell down and broke his crown', 'And Jill came tumbling after'] 

And Jill came tumbling after
Jack fell down and broke his crown
To fetch a pail of water
Jack and Jill went up the hill

 

Task 2

.split()

In [12]:
# [ ] split poem into a list of phrases by splitting on "*" a
# [ ] print each phrase on a new line in title case
poem = "Write code frequently*Save code frequently*Comment code frequently*Study code frequently*"
#Answer:
poem_words = poem.split('*')
for word in poem_words:
    print(word)
Write code frequently
Save code frequently
Comment code frequently
Study code frequently

 

Concepts

.join()   build a string from a list

view video

.join() is a method applied to a separator string and iterates through its argument

tip_words = ['Notebooks', 'can', 'be', 'exported', 'as', '.pdf'] 

" ".join(tip_words)

a space (" ") is the separator that gets injected between the objects in the argument (the list "tip_words")

 

Examples

.join()

In [13]:
# [ ] review and run example
tip_words = ['Notebooks', 'can', 'be', 'exported', 'as', '.pdf'] 

# join tip_words objects with spaces
print(" ".join(tip_words))
Notebooks can be exported as .pdf
In [14]:
# [ ] review and run example
no_space = ""
letters = ["P", "y", "t", "h", "o", "n"]
print(no_space.join(letters))
Python
In [15]:
# [ ] review and run example - .join() iterates through sequences
dash = "-"
space = " "
word = "Iteration"
ellipises = "..."

dash_join = dash.join(word)
print(dash_join)
print(space.join(word))
print(ellipises.join(word))
I-t-e-r-a-t-i-o-n
I t e r a t i o n
I...t...e...r...a...t...i...o...n

 

Task 3

.join()

In [19]:
# [ ] .join() letters list objects with an Asterisk: "*"
letters = ["A", "s", "t", "e", "r", "i", "s", "k"]

#Answer:
asterisk = "*"
asterisk_join = asterisk.join(letters)
print(asterisk_join)
A*s*t*e*r*i*s*k

 

Task 4

Program: Choose the separator

  • get user input on what to use to join words (" ", *, -, etc...) - store in variable: separator
  • join pharse_words with the separator and print
In [21]:
# [ ] complete Choose the separator
phrase_words = ['Jack', 'and', 'Jill', 'went', 'up', 'the', 'hill', 'To', 'fetch', 'a', 'pail', 'of', 'water']
#Answer:
separator = input("Type the separator: ")
separator_join = separator.join(phrase_words)
print(separator_join)
Type the separator: -
Jack-and-Jill-went-up-the-hill-To-fetch-a-pail-of-water

 

Concept

More Python string tools (tricks?)

view video

Cast a string to a list of characters

hello_letters = list("Hello")

or insert any character as an end in print("String", end="+")

print('Hello', end = '')
print('world')

 

Examples

In [22]:
# [ ] review and run example
hello_letters = list("Hello")
print(hello_letters)
['H', 'e', 'l', 'l', 'o']
In [23]:
# [ ] review and run example
# cast sting to list
word_letters = list("concatenates")

# .join() concatenates the list
# print on same line setting the end character
print('~'.join(word_letters))
c~o~n~c~a~t~e~n~a~t~e~s
In [24]:
# [ ] review and run example
print("Hello ", end = '')
print("world")
Hello world
In [25]:
# [ ] review and run example
# This  is the default print end
print("Hello World!", end="\n")
print('still something to learn about print()')
Hello World!
still something to learn about print()
In [26]:
# [ ] review and run example
# end inserts any valid str character: A-z, 0-9,!,@,*,\n,\t or ''(empty string)...
for letter in "Concatenation":
    print(letter, end='*')
C*o*n*c*a*t*e*n*a*t*i*o*n*

 

Task 5

end=" " configuration in printing

print('The String', end='')

In [30]:
# [ ] use 3 print() statements to output text to one line 
# [ ] separate the lines by using "- " (dash space)
#Answer:
print('Hello everyone, ', end = '- ')
print('how are you ', end='- ')
print('today?')
Hello everyone, - how are you - today?

 

Task 6

cast: str to list

Msg_characters = list("Always test your code")

In [32]:
# [ ] create a string (fact) of 20 or more characters and cast to a list (fact_letters)
# [ ] iterate fact, printing each char on one line, except for spaces print a new line
#Answer:
fact = "Always test your code"
fact_letters = list(fact)
for letter in fact:
    if (letter==' '):
        print("\n")
    else:
        print(letter,end='')
Always

test

your

code

 

Task 7

Program: add the digits

  • create a 20 digit string, and cast to a list
  • then add all the digits as integers
  • print the equation and answer

Hint: use cast to sum the digits, and .join() to create the equation (1+2+3+...)

In [36]:
# [ ] create add the digits
#Answer:

digit_string = '12345678900987654321'
digit_list = list(digit_string)
digit_sum = 0
digit_equation = ""
for digit in digit_list:
    digit_sum += int(digit)
print("+".join(digit_list),' = ',digit_sum)
1+2+3+4+5+6+7+8+9+0+0+9+8+7+6+5+4+3+2+1  =  90

Terms of use   Privacy & cookies   © 2017 Microsoft