+ - 0:00:00
Notes for current slide
Notes for next slide

Lecture 6


DANL 100: Programming for Data Analytics

Byeong-Hak Choe

September 15, 2022

1 / 34

Announcement

Accounting Expo

  • Are you interested in learning about Accounting, Consulting, Audit or Tax?
    • Stop in for pizza and meet 20+ Firms (alumni and employers) from the Big 4, National Players and Regional firms!
  • When? September 15th, 5:00 PM-7:00 PM
  • Where? Ballroom
  • Dress code? Business Casual
2 / 34

Workflow


3 / 34

Workflow

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.

    • Fn + / works too.
  • PgUp/PgDn moves the blinking cursor bar to the top/bottom line of the script on the screen.

    • Fn + / works too.
4 / 34

Workflow

Shortcuts

Mac

  • command + N opens a new script.
  • command + 1 is the shortcut for #.
  • command + 4 is the shortcut for block comment.

Windows

  • Ctrl + N opens a new script.
  • Ctrl + 1 is the shortcut for #.
  • Ctrl + 4 is the shortcut for block comment.
5 / 34

Workflow

More Shortcuts

  • Ctrl (command for Mac Users) + Z undoes the previous action.
  • Ctrl (command for Mac Users) + Shift + Z redoes when undo is executed.
  • Ctrl (command for Mac Users) + F is useful when finding a phrase in the script.
  • Ctrl (command for Mac Users) + R is useful when replacing a specific phrase with something in the script.
  • Ctrl (command for Mac Users) + D deletes a current line.
6 / 34

Workflow

Code and comment style

  • The two main principles for coding and managing data are:
    • Make things easier for your future self.
    • Don't trust your future self.
  • The # mark is Spyder's comment character.
    • The # character has many names: hash, sharp, pound, or octothorpe.
    • # indicates that the rest of the line is to be ignored.
    • Write comments before the line that you want the comment to apply to.
  • Consider using block commenting for separating code sections.
    • # %% defines a coding block in Spyder.
7 / 34

Numbers


8 / 34

Numbers

  • Let's look at the following Python’s simplest built-in data types in detail:

    • Booleans (which have the value True or False)

    • Integers (whole numbers such as 10 and 28)

    • Floats (numbers with decimal points such as 3.141592, or sometimes exponents like 1.0e8, which means one times ten to the eighth power, or 100000000.0)

9 / 34

Numbers

Integer Operations

  • Python can be a simple calculator.

  • Here is a table of the math operators:

  • Dividing by zero with either kind of division causes a Python exception
12 + 8
12 - 8
13 * 1.2
2 + 3 * 4
2 ** 3
2 / 0
2 // 0
10 / 34

Numbers

Integers and Variables

  • We can combine the arithmetic operators with assignment by putting the operator before the =.
a = 72
a -= 2 # This is like a = a - 2
b = 62
b += 2 # This is like b = b + 2
c = 72
c *= 2 # This is like c = c * 2
d = 62
d /= 2 # This is like d = d / 2
11 / 34

Numbers

Type Conversions

  • To change other Python data types to an integer, use the int() function.

    • int() keeps the whole number and discard any fractional part.
  • True and False are converted to integer values 1 and 0.

int(True)
int(False)
bool(1)
bool(0)
int(72.3)
int(1.0e4)
bool(1.0)
bool(0.0)
12 / 34

Numbers

Floats

  • To convert other types to floats, we use the float() function.
float(True)
float(False)
float(88)
float('89')
13 / 34

Workflow

Continue Lines with \

sum = 1 + \
2 + \
3 + \
4
sum
sum = 1 +
  • If you’re in the middle of paired parentheses (or square or curly brackets), Python doesn’t squawk about line endings:
sum = ( 1 +
2 +
3 +
4 )
sum
14 / 34

Numbers

Class Exercises

  1. Multiply the number of seconds in a minute (60) by the number of minutes in an hour (also 60) using Python.

  2. Assign the result from the previous task (seconds in an hour) to a variable called seconds_per_hour.

  3. How many seconds are in a day? Use your seconds_per_hour variable.

  4. Calculate seconds per day again, but this time save the result in a variable called seconds_per_day

  5. Divide seconds_per_day by seconds_per_hour. Use floating-point (/) division.

15 / 34

Choose with if


16 / 34

Choose with if

Compare with if, elif, and else

  • Now, we finally take our first step into the code structures that weave data into programs.

  • The following Python program checks the value of the boolean variable disaster and prints an appropriate comment:

disaster = True
if disaster:
print("Woe!")
else:
print("Whee!")
17 / 34

Choose with if

Compare with if, elif, and else

  • The if and else lines are Python statements that check whether a condition is a boolean True value, or can be evaluated as True.
disaster = True
if disaster:
print("Woe!")
else:
print("Whee!")
18 / 34

Choose with if

Compare with if, elif, and else

  • Python expects you to be consistent with code within a section—the lines need to be indented the same amount, lined up on the left.

    • The recommended style is to use four spaces.
    • When changing a line by hitting the key enter/return, Spyder takes care of indention pretty well.
disaster = True
if disaster:
print("Woe!")
else:
print("Whee!")
19 / 34

Choose with if

Compare with if, elif, and else

  • We did a number of things here:
disaster = True
if disaster:
print("Woe!")
else:
print("Whee!")
  • Assigned the boolean value True to the variable named disaster.
  • Performed a conditional comparison by using if and else, executing different code depending on the value of disaster.
  • Called the print() function to print some text.
20 / 34

Choose with if

Compare with if, elif, and else

  • We can have tests within tests, as many levels deep as needed:
furry = True
large = True
if 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.")
21 / 34

Choose with if

Compare with if, elif, and else

  • Indentation determines how the if and else sections are paired.
furry = True
large = True
if 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.")
22 / 34

Choose with 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)
23 / 34

Choose with if

Comparison Operators

  • Here are Python's comparison operators:

24 / 34

Choose with if

Comparison Operators

  • Here are Python's comparison operators:
# Assign x to 7
x = 7
x == 5 # Test equality
x == 7
5 < x
x < 10
25 / 34

Choose with if

Comparison Operators

  • Logical operators have lower precedence than the chunks of code that they’re comparing.

    • This means that the chunks are calculated first, and then compared.
5 < x and x < 10
  • The easiest way to avoid confusion about precedence is to add parentheses
(5 < x) and (x < 10)
26 / 34

Choose with if

Comparison Operators

  • Here are some other tests:
5 < x or x < 10
5 < x and x > 10
5 < x and not x > 10
  • If you’re 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
27 / 34

Choose with if

What Is True?

  • What does Python consider True and False?
  • A False value doesn’t necessarily need to explicitly be a boolean False.
    • The followings are all considered False:

  • Anything else is considered True.
28 / 34

Choose with if

What Is True?

  • Python programs use these definitions of "truthiness" and "falsiness" to check for empty data structures as well as False conditions:
some_list = []
if some_list:
print("There's something in here")
else:
print("Hey, it's empty!")
29 / 34

Choose with if

Do Multiple Comparisons with in

  • Suppose that you have a letter and want to know whether it’s a vowel.
    • One way would be to write a long 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')
30 / 34

Choose with if

Do Multiple Comparisons with in

  • Whenever you need to make a lot of comparisons like that, separated by or, use Python’s membership operator in, instead.
vowels = 'aeiou'
letter = 'o'
letter in vowels
if letter in vowels:
print(letter, 'is a vowel')
31 / 34

Choose with if

Do Multiple Comparisons with in

  • Here are some examples of how to use 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
  • For the dictionary, in looks at the keys (the left-hand side of the :) instead of their values.
vowel_string = "aeiou"
letter in vowel_string
32 / 34

Choose with if

Walrus Operator

  • The walrus operator looks like this:

tweet_limit = 280
tweet_string = "Blah" * 50
diff = tweet_limit - len(tweet_string)
if diff >= 0:
print("A fitting tweet")
else:
print("Went over by", abs(diff))
tweet_limit = 280
tweet_string = "Blah" * 50
if ( diff := tweet_limit - len(tweet_string) ) >= 0:
print("A fitting tweet")
else:
print("Went over by", abs(diff))
33 / 34

Choose with if

Class Exercises

  1. 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.

  2. Assign True or False to the variables small and green. Write some if/else statements to print which of these matches those choices: cherry, pea, watermelon, pumpkin.

34 / 34

Announcement

Accounting Expo

  • Are you interested in learning about Accounting, Consulting, Audit or Tax?
    • Stop in for pizza and meet 20+ Firms (alumni and employers) from the Big 4, National Players and Regional firms!
  • When? September 15th, 5:00 PM-7:00 PM
  • Where? Ballroom
  • Dress code? Business Casual
2 / 34
Paused

Help

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
oTile View: Overview of Slides
Esc Back to slideshow