Contents
This notebook is based on "Think Python, 2Ed" by Allen B. Downey
https://greenteapress.com/wp/think-python-2e/
In [1]:
fruit = 'banana'
letter = fruit[1]
print( letter )
a
returned instead of b
?
In [2]:
len( fruit )
Out[2]:
In [3]:
length = len( fruit )
# Uncomment to see what happens
#last = fruit[ length ]
In [4]:
last = fruit[ length - 1 ]
last = fruit[ -1 ]
In [5]:
index = 0
while( index < len( fruit ) ):
letter = fruit[ index ]
print( letter )
index = index + 1
for
loop can also be used
In [6]:
# Use the for loop to keep track of the index
for index in range( len( fruit ) ):
print( fruit[ index ] )
# Have Python keep track of things for us
for char in fruit:
print( char )
In [7]:
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print( letter + suffix )
In [8]:
s = 'Monty Python'
print( s[0:5] )
print( s[6:12] )
[n:m]
returns a portion of the stringn
-th item is included, but the m
-th item is not
In [9]:
fruit = 'banana'
print( fruit[:3] )
print( fruit[3:] )
In [10]:
greeting = 'Hello world!'
# Uncomment to see the error generated
# greeting[0] = 'J'
object
is the string and the item
is the character
In [11]:
greeting = 'Hello world!'
new_greeting = 'J' + greeting[1:]
print( new_greeting )
print( greeting )
In [12]:
def find( word, letter ):
letter_index = -1
current_index = 0
while( current_index < len( word ) ):
if( word[current_index] == letter ):
letter_index = current_index
return letter_index
-1
In [13]:
word = 'banana'
new_word = word.upper()
print( new_word )
upper
is called on the string word
find
In [14]:
print( 'an' in 'banana' )
print( 'seed' in 'banana' )
In [17]:
word = 'apple'
if( word == 'banana' ):
print( 'All right, bananas.' )
if( word < 'banana' ):
print( 'Your word, ' + word + ', comes before banana.' )
elif( word > 'banana' ):
print( 'Your word, ' + word + ', comes after banana.' )
else:
print( 'All right, bananas.' )
In [16]:
word = 'banana'
index = 2
print( 'index=[', index, '] value=[', word[ index ], ']' )
In [ ]:
def is_palindrome( phrase ):
# YOUR CODE GOES HERE
return False
in
that determines if a character or a substring is contained in a larger string. It returns True
if the character or substring is in the larger string, otherwise, it returns False
. Write a function called in_string
that implements the same functionality.
In [ ]:
def in_string( substring, larger_string ):
# YOUR CODE GOES HERE
return False
In [ ]:
def create_username():
username = ''
# YOUR CODE HERE
print( username )