Tutoring and TA-ing Schedules
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
if
if
if
-else
statement
if
and else
lines are Python statements that check whether a condition is a boolean True
value, or can be evaluated as True
.disaster = Trueif disaster: print("Woe!")else: print("Whee!")
if
/else
.if
Compare with if
, elif
, and else
If there are more than two possibilities to test, use if
for the first, elif
(meaning else if) for the middle ones, and else
for the last:
color = "mauve"if color == "red": print("It's a rasberry")elif color == "green": print("It's a green chili")elif color == "bee purple": print("I don't know what it is, but only bees can see it")else: print("I've never heard of the color", color)
if
Compare with if
, elif
, and else
if
and else
sections are paired.furry = Truelarge = Trueif furry: if large: print("It's a yeti.") else: print("It's a cat!")else: if large: print("It's a whale!") else: print("It's a human. Or a hairless cat.")
if
Comparison Operators
if
Comparison Operators
# Assign x to 7x = 7x == 5 # Test equalityx == 75 < xx < 10
if
Boolean Operator
A and B is True
if both A and B statements are True
.
A and B is False
otherwise.
A or B is True
if either A or B statement is True
.
A or B is False
otherwise.
A and not B is True
if A statement is True
and B statement is False
.
A and not B is False
otherwise.
if
Comparison Operators
Logical operators have lower precedence than the chunks of code that they’re comparing.
5 < x and x < 10
(5 < x) and (x < 10)
if
Comparison Operators
5 < x or x < 105 < x and x > 105 < x and not x > 10
and
-ing multiple comparisons with one variable, Python lets you do this:5 < x < 10 # It’s the same as 5 < x and x < 10
if
What Is True
?
True
and False
?False
value doesn’t necessarily need to explicitly be a boolean False
. False
:True
.if
What Is True
?
False
conditions:some_list = []if some_list: print("There's something in here")else: print("Hey, it's empty!")
if
Do Multiple Comparisons with in
if
statement:letter = 'o'if letter == 'a' or letter == 'e' or letter == 'i' \ or letter == 'o' or letter == 'u': print(letter, 'is a vowel')else: print(letter, 'is not a vowel')
if
Do Multiple Comparisons with in
in
, instead.vowels = 'aeiou'letter = 'o'letter in vowelsif letter in vowels: print(letter, 'is a vowel')
if
Do Multiple Comparisons with in
in
with some data types:letter = 'o'vowel_set = {'a', 'e', 'i', 'o', 'u'}letter in vowel_set
vowel_list = ['a', 'e', 'i', 'o', 'u']letter in vowel_list
vowel_tuple = ('a', 'e', 'i', 'o', 'u')letter in vowel_tuple
vowel_dict = {'a': 'apple', 'e': 'elephant', 'i': 'impala', 'o': 'ocelot', 'u': 'unicorn'}letter in vowel_dict
in
looks at the keys (the left-hand side of the :
) instead of their values.vowel_string = "aeiou"letter in vowel_string
if
Walrus Operator
tweet_limit = 280tweet_string = "Blah" * 50diff = tweet_limit - len(tweet_string)if diff >= 0: print("A fitting tweet")else: print("Went over by", abs(diff))
tweet_limit = 280tweet_string = "Blah" * 50if ( diff := tweet_limit - len(tweet_string) ) >= 0: print("A fitting tweet")else: print("Went over by", abs(diff))
if
Class Exercises
Choose a number between 1 and 10 and assign it to the variable secret
. Then, select another number between 1 and 10 and assign it to the variable guess
. Next, write the conditional tests (if
, else
, and elif
) to print the string 'too low
' if guess
is less than secret
, 'too high
' if greater than secret
, and 'just right
' if equal to secret
.
Assign True
or False
to the variables small
and green
, respectively. Write some if
/else
statements to print which of these matches those choices: cherry
, pea
, watermelon
, pumpkin
.
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 Quotes
print()
and the automatic echoing done by the interactive interpreter:poem_bluebirdprint(poem_bluebird)print('Give', "us", '''some''', """space""")
print()
strips quotes from strings and prints their contents. - It’s meant for human output. 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.
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:20:3] # From offset 4 to 20, 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)
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.Then 'tis not cold that doth the fire put outBut 'tis the wet that makes it die, no doubt.'''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 exists an old style of string formatting with %
and a new style of it with {}
, 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)}'
Tutoring and TA-ing Schedules
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 and TA-ing Schedules
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
if
if
if
-else
statement
if
and else
lines are Python statements that check whether a condition is a boolean True
value, or can be evaluated as True
.disaster = Trueif disaster: print("Woe!")else: print("Whee!")
if
/else
.if
Compare with if
, elif
, and else
If there are more than two possibilities to test, use if
for the first, elif
(meaning else if) for the middle ones, and else
for the last:
color = "mauve"if color == "red": print("It's a rasberry")elif color == "green": print("It's a green chili")elif color == "bee purple": print("I don't know what it is, but only bees can see it")else: print("I've never heard of the color", color)
if
Compare with if
, elif
, and else
if
and else
sections are paired.furry = Truelarge = Trueif furry: if large: print("It's a yeti.") else: print("It's a cat!")else: if large: print("It's a whale!") else: print("It's a human. Or a hairless cat.")
if
Comparison Operators
if
Comparison Operators
# Assign x to 7x = 7x == 5 # Test equalityx == 75 < xx < 10
if
Boolean Operator
A and B is True
if both A and B statements are True
.
A and B is False
otherwise.
A or B is True
if either A or B statement is True
.
A or B is False
otherwise.
A and not B is True
if A statement is True
and B statement is False
.
A and not B is False
otherwise.
if
Comparison Operators
Logical operators have lower precedence than the chunks of code that they’re comparing.
5 < x and x < 10
(5 < x) and (x < 10)
if
Comparison Operators
5 < x or x < 105 < x and x > 105 < x and not x > 10
and
-ing multiple comparisons with one variable, Python lets you do this:5 < x < 10 # It’s the same as 5 < x and x < 10
if
What Is True
?
True
and False
?False
value doesn’t necessarily need to explicitly be a boolean False
. False
:True
.if
What Is True
?
False
conditions:some_list = []if some_list: print("There's something in here")else: print("Hey, it's empty!")
if
Do Multiple Comparisons with in
if
statement:letter = 'o'if letter == 'a' or letter == 'e' or letter == 'i' \ or letter == 'o' or letter == 'u': print(letter, 'is a vowel')else: print(letter, 'is not a vowel')
if
Do Multiple Comparisons with in
in
, instead.vowels = 'aeiou'letter = 'o'letter in vowelsif letter in vowels: print(letter, 'is a vowel')
if
Do Multiple Comparisons with in
in
with some data types:letter = 'o'vowel_set = {'a', 'e', 'i', 'o', 'u'}letter in vowel_set
vowel_list = ['a', 'e', 'i', 'o', 'u']letter in vowel_list
vowel_tuple = ('a', 'e', 'i', 'o', 'u')letter in vowel_tuple
vowel_dict = {'a': 'apple', 'e': 'elephant', 'i': 'impala', 'o': 'ocelot', 'u': 'unicorn'}letter in vowel_dict
in
looks at the keys (the left-hand side of the :
) instead of their values.vowel_string = "aeiou"letter in vowel_string
if
Walrus Operator
tweet_limit = 280tweet_string = "Blah" * 50diff = tweet_limit - len(tweet_string)if diff >= 0: print("A fitting tweet")else: print("Went over by", abs(diff))
tweet_limit = 280tweet_string = "Blah" * 50if ( diff := tweet_limit - len(tweet_string) ) >= 0: print("A fitting tweet")else: print("Went over by", abs(diff))
if
Class Exercises
Choose a number between 1 and 10 and assign it to the variable secret
. Then, select another number between 1 and 10 and assign it to the variable guess
. Next, write the conditional tests (if
, else
, and elif
) to print the string 'too low
' if guess
is less than secret
, 'too high
' if greater than secret
, and 'just right
' if equal to secret
.
Assign True
or False
to the variables small
and green
, respectively. Write some if
/else
statements to print which of these matches those choices: cherry
, pea
, watermelon
, pumpkin
.
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 Quotes
print()
and the automatic echoing done by the interactive interpreter:poem_bluebirdprint(poem_bluebird)print('Give', "us", '''some''', """space""")
print()
strips quotes from strings and prints their contents. - It’s meant for human output. 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.
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:20:3] # From offset 4 to 20, 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)
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.Then 'tis not cold that doth the fire put outBut 'tis the wet that makes it die, no doubt.'''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 exists an old style of string formatting with %
and a new style of it with {}
, 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)}'