Tutoring/TA-ing at Data Analytics Lab (South 321)
Shortcuts
F9 runs a current line (where the blinking cursor bar is) or selected lines.
Home/End moves the blinking cursor bar to the beginning/end of the line.
PgUp/PgDn moves the blinking cursor bar to the top/bottom line of the script on the screen.
Shortcuts
Mac
#
.Windows
#
.# %%
defines a coding block in Spyder IDE.More Shortcuts
Data scientists often work with strings of text.
Strings in Python are immutable.
Create with Quotes
'Business'"Data"
Create with Quotes
"'Nay!' said the naysayer. 'Neigh?' said the horse."'The rare double quote in captivity: ".''A "two by four" is actually 1 1⁄2" × 3 1⁄2".'"'There's the man that shot my paw!' cried the limping hound."
Create with Quotes
'''Hi!'''"""Hello!"""
poem_bluebird = '''there’s a bluebird in my heart thatwants to get outbut I’m too tough for him,I say, stay in there, I’m not goingto let anybody seeyou.'''
Create with str()
str()
function:str(3.141592)str(1.0e4)str(True)
Escape with \
Python lets us escape the meaning of some characters within strings to achieve effects that would otherwise be difficult to express.
\
), we give it a special meaning. The most common escape sequence is \n
, which means to begin a new line.
palindrome = 'A man,\nA plan,\nA canal:\nPanama.'print(palindrome)
Escape with \
\t
(tab) is used to align text:print('\tabc')print('a\tbc')print('ab\tc')print('abc\t')
\'
or \"
to specify a literal single or double quote inside a string that’s quoted by the same character:testimony = "\"I did nothing!\" he said. \"Or that other thing.\""testimonyprint(testimony)
\
), type two of them (the first escapes the second):speech = 'The backslash (\\) bends over backwards to please you.'print(speech)
r
) negates these escapes:info = r'Type a \n to get a new line in a normal string'info
\n
) newlines:poem = r'''Boys and girls, come out to play.The moon doth shine as bright as day.'''poemprint(poem)
Combine by Using +
+
operator:'DANL 100: Programming for ' + 'Data Analytics'
'DANL 100: Programming for ' 'Data Analytics'
Duplicate with *
*
operator to duplicate a string. start = 'Na ' * 4 + '\n'middle = 'Hey ' * 3 + '\n'end = 'Goodbye.'print(start + start + middle + end)
Get a Character with []
To get a single character from a string, specify its offset inside square brackets after the string’s name.
Get a Character with []
To get a single character from a string, specify its offset inside square brackets after the string’s name.
letters = 'abcdefghijklmnopqrstuvwxyz'letters[0]letters[1]letters[-1]letters[5]letters[100]
Get a Character with []
name = 'Macintosh'name[0] = 'P'
replace()
or a slice (which we look at in a moment):name = 'Macintosh'name.replace('M', 'P')'P' + name[1:]
Get a Substring with a Slice
We can extract a substring (a part of a string) from a string by using a slice.
We define a slice by using square brackets ([]
), a start offset, an end offset, and an optional step count between them.
The slice will include characters from offset start to one before end:
Get a Substring with a Slice
[:]
extracts the entire sequence from start to end.letters = 'abcdefghijklmnopqrstuvwxyz'letters[:]
[ start :]
specifies from the start offset to the end.letters = 'abcdefghijklmnopqrstuvwxyz'letters[20:]letters[10:]letters[-3:]letters[-50:]
[: end ]
specifies from the beginning to the end offset minus 1.letters = 'abcdefghijklmnopqrstuvwxyz'letters[:3]letters[:-3]letters[:70]
[ start : end ]
indicates from the start offset to the end offset minus 1.letters = 'abcdefghijklmnopqrstuvwxyz'letters[12:15]letters[-51:-50]letters[70:71]
[ start : end : step ]
extracts from the start offset to the end offset minus 1, skipping characters by step.letters = 'abcdefghijklmnopqrstuvwxyz'letters[4:10:3] # From offset 4 to 9, by steps of 3 charactersletters[::7] # From the start to the end, in steps of 7 charactersletters[19::4] # From offset 19 to the end, by 4letters[:21:5] # From the start to offset 20 by 5:letters[-1::-1] # Starts at the end and ends at the startletters[::-1]
String-related Functions
len()
len()
function counts characters in a string:len(letters)empty = ""len(empty)
In Python, we can access attributes by using a dot notation (.
).
Unlike len()
, some functions use a dot to access to strings.
To use those string functions, type (1) the name of the string, (2) a dot, (3) the name of the function, and (4) any arguments that the function needs:
string_name.some_function(arguments)
.split()
split()
function to break a string into a list of smaller strings based on some separator.split()
uses any sequence of white space characters---newlines, spaces, and tabs:tasks = 'get gloves,get mask,give cat vitamins,call ambulance'tasks.split(',')tasks.split()
join()
join()
collapses a list of strings into a single string.crypto_list = ['Yeti', 'Bigfoot', 'Loch Ness Monster']crypto_string = ', '.join(crypto_list)print('Found and signing book deals:', crypto_string)
replace()
replace()
for simple substring substitution.setup = "a duck goes into a bar..."setup.replace('duck', 'marmoset')setupsetup.replace('a ', 'a famous ', 100) # Change up to 100 of themsetup.replace('a', 'a famous', 100) # If we're unsure the exact substring
strip()
strip()
functions assume that we want to get rid of whitespace characters (' '
, '\t'
, '\n'
) if we don’t give them an argument. strip()
strips both ends, lstrip()
only from the left, and rstrip()
only from the right. world = " earth "world.strip()world.lstrip()world.rstrip()
strip()
strip()
to remove any character in a multicharacter string:world = " earth "world.strip(' ')world.strip('!')blurt = "What the...!!?"blurt.strip('.?!')
count()
poem = '''All that doth flow we cannot liquid nameOr else would fire and water be the same;But that is liquid which is moist and wetFire that property can never get.'''word = 'the'poem.count(word)
Case and Allignment
setup = 'a duck goes into a bar...'setup.capitalize() # Capitalize the first wordsetup.title() # Capitalize all the wordssetup.upper() # Convert all characters to uppercasesetup.lower() # Convert all characters to lowercasesetup.swapcase() # Swap uppercase and lowercasesetup.center(30) # Center the string within 30 spacessetup.ljust(30) # Left justifysetup.rjust(30) # Right justify
Formatting
We’ve seen that we can concatenate strings by using +
.
Let’s look at how to interpolate data values into strings using f-strings formats.
f-strings appeared in Python 3.6, and are now the recommended way of formatting strings.
There are (1) an old style of string formatting with %
and (2) a new style of string formatting with {}
, for which we may not discuss here.
Formatting
To make an f-string:
thing = 'wereduck'place = 'werepond'f'The {thing} is in the {place}'f'The {thing.capitalize()} is in the {place.rjust(20)}'
while
and for
while
and for
while
and for
. Repeat with while
count = 1 while count <= 5: print(count) count += 1
count
.while
loop compared the value of count
to 5 and continued if count
was less than or equal to 5.count
and then incremented its value by one with the statement count += 1
.count
with 5.count
is now 2, so the contents of the while
loop are again executed, and count
is incremented to 3.count
is incremented from 5 to 6 at the bottom of the loop.count <= 5
is now False
, and the while
loop ends.while
Asking the user for input
input()
function gets input from the keyboard.input()
is called, the program stops and waits for the user to type something on Console (interactive Python interpreter).stuff = input()# Type something and press Return/Enter on Console # before running print(stuff)print(stuff)
while
Cancel with break
While
loop is used to execute a block of code repeatedly until given boolean condition evaluated to False
. while True
loop will run forever unless we write it with a break
statement.break
statement. while True: stuff = input("String to capitalize [type q to quit]: ") if stuff == "q": break print(stuff.capitalize())
while
Skip Ahead with continue
Sometimes, we don’t want to break out of a loop but just want to skip ahead to the next iteration for some reason.
The continue
statement is used to skip the rest of the code inside a loop for the current iteration only.
while True: value = input("Integer, please [q to quit]: ") if value == 'q': # quit break number = int(value) if number % 2 == 0: # an even number continue print(number, "squared is", number*number)
while
Check break
Use with else
while
with else
when we’ve coded a while
loop to check for something, and break
ing as soon as it’s found.
numbers = [1, 3, 5]position = 0while position < len(numbers): number = numbers[position] if number % 2 == 0: print('Found even number', number) break position += 1else: # break not called print('No even number found')
while
and for
Iterate with for
and in
Sometimes we want to loop through a set of things such as a string of text, a list of words or a list of numbers.
When we have a list of things to loop through, we can construct a for
loop.
A for
loop makes it possible for you to traverse data structures without knowing how large they are or how they are implemented.
while
and for
Iterate with for
and in
word = 'thud'offset = 0while offset < len(word): print(word[offset]) offset += 1
word = 'thud'for letter in word: print(letter)
for
and in
Cancel with break
break
in a for
loop breaks out of the loop, as it does for a while
loop:word = 'thud'for letter in word: if letter == 'u': break print(letter)
Skip with continue
continue
in a for
loop jumps to the next iteration of the loop, as it does
for a while
loop.word = 'thud'for letter in word: if letter == 'u': continue print(letter)
for
and in
Check break
Use with else
Similar to while
, for
has an optional else
that checks whether the for
completed
normally. If break
was not called, the else
statement is run.
for
loop ran to completion instead of being stopped early with a break
:word = 'thud'for letter in word: if letter == 'x': print("Eek! An 'x'!") break print(letter)else: print("No 'x' in there.")
for
and in
Generate Number Sequences with range()
The range()
function returns a stream of numbers within a specified range, without
first having to create and store a large data structure such as a list or tuple.
This lets us create huge ranges without using all the memory in our computers and crashing our program.
range()
returns an iterable object, so we need to step through the values with for
... in
, or convert the object to a sequence like a list.
range()
similar to how we use slices: range( start, stop, step )
. start
, the range
begins at 0. stop
; as with slices, the last value created will be just before stop. step
is 1, but we can change it.for x in range(0, 3): print(x)list( range(0, 3) )
for x in range(2, -1, -1): print(x)list( range(2, -1, -1) )
for x in range(0, 11, 2): print(x)list( range(0, 11, 2) )
while
and for
Class Exercises
Use a while
loop to print the values of the list [3, 2, 1, 0].
Assign the value 7 to the variable guess_me
, and the value 1 to the variable number
. Write a while
loop that compares number
with guess_me.
Print 'too low' if number
is less than guess me. If number
equals guess_me
, print 'found it!' and then exit the loop. If number
is greater than guess_me
, print 'oops' and then exit the loop. Increment number
at the end of the loop.
Use a for
loop to print the values of the list [3, 2, 1, 0].
Assign the value 5 to the variable guess_me.
Use a for
loop to iterate a variable called number
over range(10)
. If number
is less than guess_me
, print 'too low'. If number
equals guess_me
, print 'found it!' and then break
out of the for
loop. If number
is greater than guess_me
, print 'oops' and then exit the loop.
Tutoring/TA-ing at Data Analytics Lab (South 321)
Keyboard shortcuts
↑, ←, Pg Up, k | Go to previous slide |
↓, →, Pg Dn, Space, j | Go to next slide |
Home | Go to first slide |
End | Go to last slide |
Number + Return | Go to specific slide |
b / m / f | Toggle blackout / mirrored / fullscreen mode |
c | Clone slideshow |
p | Toggle presenter mode |
t | Restart the presentation timer |
?, h | Toggle this help |
o | Tile View: Overview of Slides |
Esc | Back to slideshow |
Tutoring/TA-ing at Data Analytics Lab (South 321)
Shortcuts
F9 runs a current line (where the blinking cursor bar is) or selected lines.
Home/End moves the blinking cursor bar to the beginning/end of the line.
PgUp/PgDn moves the blinking cursor bar to the top/bottom line of the script on the screen.
Shortcuts
Mac
#
.Windows
#
.# %%
defines a coding block in Spyder IDE.More Shortcuts
Data scientists often work with strings of text.
Strings in Python are immutable.
Create with Quotes
'Business'"Data"
Create with Quotes
"'Nay!' said the naysayer. 'Neigh?' said the horse."'The rare double quote in captivity: ".''A "two by four" is actually 1 1⁄2" × 3 1⁄2".'"'There's the man that shot my paw!' cried the limping hound."
Create with Quotes
'''Hi!'''"""Hello!"""
poem_bluebird = '''there’s a bluebird in my heart thatwants to get outbut I’m too tough for him,I say, stay in there, I’m not goingto let anybody seeyou.'''
Create with str()
str()
function:str(3.141592)str(1.0e4)str(True)
Escape with \
Python lets us escape the meaning of some characters within strings to achieve effects that would otherwise be difficult to express.
\
), we give it a special meaning. The most common escape sequence is \n
, which means to begin a new line.
palindrome = 'A man,\nA plan,\nA canal:\nPanama.'print(palindrome)
Escape with \
\t
(tab) is used to align text:print('\tabc')print('a\tbc')print('ab\tc')print('abc\t')
\'
or \"
to specify a literal single or double quote inside a string that’s quoted by the same character:testimony = "\"I did nothing!\" he said. \"Or that other thing.\""testimonyprint(testimony)
\
), type two of them (the first escapes the second):speech = 'The backslash (\\) bends over backwards to please you.'print(speech)
r
) negates these escapes:info = r'Type a \n to get a new line in a normal string'info
\n
) newlines:poem = r'''Boys and girls, come out to play.The moon doth shine as bright as day.'''poemprint(poem)
Combine by Using +
+
operator:'DANL 100: Programming for ' + 'Data Analytics'
'DANL 100: Programming for ' 'Data Analytics'
Duplicate with *
*
operator to duplicate a string. start = 'Na ' * 4 + '\n'middle = 'Hey ' * 3 + '\n'end = 'Goodbye.'print(start + start + middle + end)
Get a Character with []
To get a single character from a string, specify its offset inside square brackets after the string’s name.
Get a Character with []
To get a single character from a string, specify its offset inside square brackets after the string’s name.
letters = 'abcdefghijklmnopqrstuvwxyz'letters[0]letters[1]letters[-1]letters[5]letters[100]
Get a Character with []
name = 'Macintosh'name[0] = 'P'
replace()
or a slice (which we look at in a moment):name = 'Macintosh'name.replace('M', 'P')'P' + name[1:]
Get a Substring with a Slice
We can extract a substring (a part of a string) from a string by using a slice.
We define a slice by using square brackets ([]
), a start offset, an end offset, and an optional step count between them.
The slice will include characters from offset start to one before end:
Get a Substring with a Slice
[:]
extracts the entire sequence from start to end.letters = 'abcdefghijklmnopqrstuvwxyz'letters[:]
[ start :]
specifies from the start offset to the end.letters = 'abcdefghijklmnopqrstuvwxyz'letters[20:]letters[10:]letters[-3:]letters[-50:]
[: end ]
specifies from the beginning to the end offset minus 1.letters = 'abcdefghijklmnopqrstuvwxyz'letters[:3]letters[:-3]letters[:70]
[ start : end ]
indicates from the start offset to the end offset minus 1.letters = 'abcdefghijklmnopqrstuvwxyz'letters[12:15]letters[-51:-50]letters[70:71]
[ start : end : step ]
extracts from the start offset to the end offset minus 1, skipping characters by step.letters = 'abcdefghijklmnopqrstuvwxyz'letters[4:10:3] # From offset 4 to 9, by steps of 3 charactersletters[::7] # From the start to the end, in steps of 7 charactersletters[19::4] # From offset 19 to the end, by 4letters[:21:5] # From the start to offset 20 by 5:letters[-1::-1] # Starts at the end and ends at the startletters[::-1]
String-related Functions
len()
len()
function counts characters in a string:len(letters)empty = ""len(empty)
In Python, we can access attributes by using a dot notation (.
).
Unlike len()
, some functions use a dot to access to strings.
To use those string functions, type (1) the name of the string, (2) a dot, (3) the name of the function, and (4) any arguments that the function needs:
string_name.some_function(arguments)
.split()
split()
function to break a string into a list of smaller strings based on some separator.split()
uses any sequence of white space characters---newlines, spaces, and tabs:tasks = 'get gloves,get mask,give cat vitamins,call ambulance'tasks.split(',')tasks.split()
join()
join()
collapses a list of strings into a single string.crypto_list = ['Yeti', 'Bigfoot', 'Loch Ness Monster']crypto_string = ', '.join(crypto_list)print('Found and signing book deals:', crypto_string)
replace()
replace()
for simple substring substitution.setup = "a duck goes into a bar..."setup.replace('duck', 'marmoset')setupsetup.replace('a ', 'a famous ', 100) # Change up to 100 of themsetup.replace('a', 'a famous', 100) # If we're unsure the exact substring
strip()
strip()
functions assume that we want to get rid of whitespace characters (' '
, '\t'
, '\n'
) if we don’t give them an argument. strip()
strips both ends, lstrip()
only from the left, and rstrip()
only from the right. world = " earth "world.strip()world.lstrip()world.rstrip()
strip()
strip()
to remove any character in a multicharacter string:world = " earth "world.strip(' ')world.strip('!')blurt = "What the...!!?"blurt.strip('.?!')
count()
poem = '''All that doth flow we cannot liquid nameOr else would fire and water be the same;But that is liquid which is moist and wetFire that property can never get.'''word = 'the'poem.count(word)
Case and Allignment
setup = 'a duck goes into a bar...'setup.capitalize() # Capitalize the first wordsetup.title() # Capitalize all the wordssetup.upper() # Convert all characters to uppercasesetup.lower() # Convert all characters to lowercasesetup.swapcase() # Swap uppercase and lowercasesetup.center(30) # Center the string within 30 spacessetup.ljust(30) # Left justifysetup.rjust(30) # Right justify
Formatting
We’ve seen that we can concatenate strings by using +
.
Let’s look at how to interpolate data values into strings using f-strings formats.
f-strings appeared in Python 3.6, and are now the recommended way of formatting strings.
There are (1) an old style of string formatting with %
and (2) a new style of string formatting with {}
, for which we may not discuss here.
Formatting
To make an f-string:
thing = 'wereduck'place = 'werepond'f'The {thing} is in the {place}'f'The {thing.capitalize()} is in the {place.rjust(20)}'
while
and for
while
and for
while
and for
. Repeat with while
count = 1 while count <= 5: print(count) count += 1
count
.while
loop compared the value of count
to 5 and continued if count
was less than or equal to 5.count
and then incremented its value by one with the statement count += 1
.count
with 5.count
is now 2, so the contents of the while
loop are again executed, and count
is incremented to 3.count
is incremented from 5 to 6 at the bottom of the loop.count <= 5
is now False
, and the while
loop ends.while
Asking the user for input
input()
function gets input from the keyboard.input()
is called, the program stops and waits for the user to type something on Console (interactive Python interpreter).stuff = input()# Type something and press Return/Enter on Console # before running print(stuff)print(stuff)
while
Cancel with break
While
loop is used to execute a block of code repeatedly until given boolean condition evaluated to False
. while True
loop will run forever unless we write it with a break
statement.break
statement. while True: stuff = input("String to capitalize [type q to quit]: ") if stuff == "q": break print(stuff.capitalize())
while
Skip Ahead with continue
Sometimes, we don’t want to break out of a loop but just want to skip ahead to the next iteration for some reason.
The continue
statement is used to skip the rest of the code inside a loop for the current iteration only.
while True: value = input("Integer, please [q to quit]: ") if value == 'q': # quit break number = int(value) if number % 2 == 0: # an even number continue print(number, "squared is", number*number)
while
Check break
Use with else
while
with else
when we’ve coded a while
loop to check for something, and break
ing as soon as it’s found.
numbers = [1, 3, 5]position = 0while position < len(numbers): number = numbers[position] if number % 2 == 0: print('Found even number', number) break position += 1else: # break not called print('No even number found')
while
and for
Iterate with for
and in
Sometimes we want to loop through a set of things such as a string of text, a list of words or a list of numbers.
When we have a list of things to loop through, we can construct a for
loop.
A for
loop makes it possible for you to traverse data structures without knowing how large they are or how they are implemented.
while
and for
Iterate with for
and in
word = 'thud'offset = 0while offset < len(word): print(word[offset]) offset += 1
word = 'thud'for letter in word: print(letter)
for
and in
Cancel with break
break
in a for
loop breaks out of the loop, as it does for a while
loop:word = 'thud'for letter in word: if letter == 'u': break print(letter)
Skip with continue
continue
in a for
loop jumps to the next iteration of the loop, as it does
for a while
loop.word = 'thud'for letter in word: if letter == 'u': continue print(letter)
for
and in
Check break
Use with else
Similar to while
, for
has an optional else
that checks whether the for
completed
normally. If break
was not called, the else
statement is run.
for
loop ran to completion instead of being stopped early with a break
:word = 'thud'for letter in word: if letter == 'x': print("Eek! An 'x'!") break print(letter)else: print("No 'x' in there.")
for
and in
Generate Number Sequences with range()
The range()
function returns a stream of numbers within a specified range, without
first having to create and store a large data structure such as a list or tuple.
This lets us create huge ranges without using all the memory in our computers and crashing our program.
range()
returns an iterable object, so we need to step through the values with for
... in
, or convert the object to a sequence like a list.
range()
similar to how we use slices: range( start, stop, step )
. start
, the range
begins at 0. stop
; as with slices, the last value created will be just before stop. step
is 1, but we can change it.for x in range(0, 3): print(x)list( range(0, 3) )
for x in range(2, -1, -1): print(x)list( range(2, -1, -1) )
for x in range(0, 11, 2): print(x)list( range(0, 11, 2) )
while
and for
Class Exercises
Use a while
loop to print the values of the list [3, 2, 1, 0].
Assign the value 7 to the variable guess_me
, and the value 1 to the variable number
. Write a while
loop that compares number
with guess_me.
Print 'too low' if number
is less than guess me. If number
equals guess_me
, print 'found it!' and then exit the loop. If number
is greater than guess_me
, print 'oops' and then exit the loop. Increment number
at the end of the loop.
Use a for
loop to print the values of the list [3, 2, 1, 0].
Assign the value 5 to the variable guess_me.
Use a for
loop to iterate a variable called number
over range(10)
. If number
is less than guess_me
, print 'too low'. If number
equals guess_me
, print 'found it!' and then break
out of the for
loop. If number
is greater than guess_me
, print 'oops' and then exit the loop.