Class 3B: Introduction to Programming in Python cont’d#

We will begin soon! Until then, feel free to use the chat to socialize, and enjoy the music!

../../../_images/programming2.jpg


Photo by Christina Morillo from Pexels
Firas Moosvi

Class Outline:#

  • Announcements

    • Reminder: Next Wednesday’s class is Test 1!

      • Contents: Git, Terminal, Markdown, General installation info

  • 1st hour - Introduction to Python

    • Announcements (2 mins)

    • Introduction (3 mins)

    • Writing and Running Code (15 min)

    • Interpreting Code (15 min)

    • Review and Recap (5 min)

  • Digging Deeper into Python syntax

    • Basic datatypes (15 min)

    • Lists and tuples (15 min)

    • String methods (5 min)

    • Dictionaries (10 min)

    • Conditionals (10 min)

Learning Objectives#

  • Look at some lines of code and predict what the output will be.

  • Convert an English sentence into code.

  • Recognize the order specific lines of code need to be run to get the desired output.

  • Imagine how programming can be useful to your life!

Part 3: Interpreting code (15 mins)#

../../../_images/bus_stop1.jpg

Q1: Interpret Code#

Look at the following code chunk, can you predict what the output will be?

some_numbers = [1, 50, 40, 75, 400, 1000]

for i in some_numbers:
    print(i*5)





A. Prints 6 random numbers.

B. Prints the 6 numbers in some_numbers.

C. Prints the 6 numbers in some_numbers multiplied by 5.

D. I don’t know.

# Let's try it!

some_numbers = [1, 50, 40, 75, 400, 1000]

for i in some_numbers:
    print(i, i * 5)
1 5
50 250
40 200
75 375
400 2000
1000 5000

Q2: Interpret Code#

Look at the following code chunk, can you predict what the output will be?

some_numbers = [1, 50, 40, 75, 400, 1000]

for i in some_numbers:
    
    if i > 50:
        print(i/5)
    else:
        print(i)





A. Prints the 6 numbers in some_numbers.

B. Prints the number in some_numbers if it is less than 50, otherwise prints the number divided by 5.

C. Prints the number in some_numbers if it is greater than 50, otherwise prints the number divided by 5.

D. I don’t know.

# Let's try it!

some_numbers = [1, 50, 40, 75, 400, 1000]

for i in some_numbers:

    if i > 50:
        print(i / 5)
    else:
        print(i)
1
50
40
15.0
80.0
200.0

Q3: Interpret Code#

Look at the following code chunk, can you predict what the output will be?



some_numbers = [1, 50, 40, 75, 400, 1000]

def process_number(number): 
    return (number**2)/10

for i in some_numbers:    
    if i > 50:
        print(process_number(i))







A. Prints the number in some_numbers if it is greater than 50, otherwise prints nothing.

B. Prints the output of the process_number() function applied to some_numbers.

C. Prints the output of the process_number() function if the original number is greater than 50, otherwise prints nothing.

D. I don’t know.

# Let's try it!

some_numbers = [1, 50, 40, 75, 400, 1000]


def process_number(number):
    return (number**2) / 10


for i in some_numbers:
    if i > 50:
        print(process_number(i))
562.5
16000.0
100000.0

Q4: Order matters!#

Suppose you are asked to complete the following operation:

Take the number 5, square it, subtract 2, and then multiply the result by 10

Does the order of the operations you do matter? Yes!

# Let's try it:
((5**2) - 2) * 10
230
# Here is the same operation as above
# but in multiple lines

number = 5
number = number**2
number = number - 2
number = number * 10

print(number)
230

Q5: Parson’s problem#

A Parson’s Problem is one where you are given all the lines of code to solve the problem, but they are jumbled and it’s up to you to get the right order.

A student would like to get this as the final output of some code that they are writing:

3 is smaller than, or equal to 10.
4 is smaller than, or equal to 10.
5 is smaller than, or equal to 10.
6 is smaller than, or equal to 10.
7 is smaller than, or equal to 10.
8 is smaller than, or equal to 10.
9 is smaller than, or equal to 10.
10 is smaller than, or equal to 10.
11 is bigger than 10!
12 is bigger than 10!
13 is bigger than 10!
14 is bigger than 10!
15 is bigger than 10!

Here are ALL the lines of code they will need to use, but they are scrambled in the wrong order. Can you produce the desired output?

Hint: Pay attention to the indents!

my_numbers = [3,4,5,6,7,8,9,10,11,12,13,14,15]
for i in my_numbers:  
    if i > 10:
        print(i,"is smaller than, or equal to 10.")
    else:
        print(i,"is bigger than 10!")
my_numbers = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in my_numbers:
    if i <= 10:
        print(i, "is smaller than, or equal to 10.")
    else:
        print(i, "is bigger than 10!")
3 is smaller than, or equal to 10.
4 is smaller than, or equal to 10.
5 is smaller than, or equal to 10.
6 is smaller than, or equal to 10.
7 is smaller than, or equal to 10.
8 is smaller than, or equal to 10.
9 is smaller than, or equal to 10.
10 is smaller than, or equal to 10.
11 is bigger than 10!
12 is bigger than 10!
13 is bigger than 10!
14 is bigger than 10!
15 is bigger than 10!

Congratulations!!#

  • You have just shown that you can program!

  • Over 75% of the course programming content will be focused on details of the things you’ve seen above:

    • Numbers and Strings

    • Loops and Conditionals

    • Functions

  • If you followed along with most of what we covered, you’re in good shape for this course

https://media.giphy.com/media/11sBLVxNs7v6WA/giphy.gif

Break#

Basic datatypes#

  • A value is a piece of data that a computer program works with such as a number or text.

  • There are different types of values: 42 is an integer and "Hello!" is a string.

  • A variable is a name that refers to a value.

    • In mathematics and statistics, we usually use variables names like \(x\) and \(y\).

    • In Python, we can use any word as a variable name (as long as it starts with a letter and is not a reserved word in Python such as for, while, class, lambda, import, if, else, etc.).

  • And we use the assignment operator = to assign a value to a variable.

See the Python 3 documentation for a summary of the standard built-in Python datatypes. See Think Python (Chapter 2) for a discussion of variables, expressions and statements in Python.

Common built-in Python data types#

English name

Type name

Description

Example

integer

int

positive/negative whole numbers

42, -42, -10000

floating point number

float

real number in decimal form

3.14159

boolean

bool

true or false

True

string

str

text

"I Can Has Cheezburger?"

list

list

a collection of objects - mutable & ordered

["Ali","Xinyi","Miriam"]

tuple

tuple

a collection of objects - immutable & ordered

("Thursday",6,9,2018)

dictionary

dict

mapping of key-value pairs

{'name':'DSCI','code':511,'credits':2}

none

NoneType

represents no value

None

Numeric Types#

x = 45
print(x)
45
type(x)
int
float(x)
45.0
print(x)
45
x  # in Jupyter we don't need to explicitly print for the last line of a cell
45
pi = 3.14159
print(pi)
3.14159
type(pi)
float

Arithmetic Operators#

The syntax for the arithmetic operators are:

Operator

Description

+

addition

-

subtraction

*

multiplication

/

division

**

exponentiation

//

integer division

%

modulo

Let’s apply these operators to numeric types and observe the results.

1 + 2 + 3 + 4 + 5
15
0.1 + 0.2
0.30000000000000004

Tip

Note From Firas: This is floating point arithmetic. For an explanation of what’s going on, see this tutorial.

2 * 3.14159
6.28318
2**10
1024
type(2**10)
int
2.0**10
1024.0
int_2 = 2
float_2 = 2.0
float_2_again = 2.0
101 / 2
50.5
101 // 2  # "integer division" - always rounds down
50
101 % 2  # "101 mod 2", or the remainder when 101 is divided by 2
1

None#

  • NoneType is its own type in Python.

  • It only has one possible value, None

x = None
print(x)
None
type(x)
NoneType

You may have seen similar things in other languages, like null in Java, etc.

Strings#

  • Text is stored as a datatype called a string.

  • We think of a string as a sequence of characters.

  • We write strings as characters enclosed with either:

    • single quotes, e.g., 'Hello'

    • double quotes, e.g., "Goodbye"

    • triple single quotes, e.g., '''Yesterday'''

    • triple double quotes, e.g., """Tomorrow"""

my_name = "Firas Moosvi"
print(my_name)
Firas Moosvi
type(my_name)
str
course = "DATA 301"
print(my_name, ",", course)
Firas Moosvi , DATA 301

print(my_name + ” ————–> ” + course)

type(course)
str

If the string contains a quotation or apostrophe, we can use double quotes or triple quotes to define the string.

"It's a rainy day cars'."
"It's a rainy day cars'."
sentence = "It's a rainy day."
print(sentence)
It's a rainy day.
type(sentence)
str
saying = '''They say:

"It's a rainy day!"'''
print(saying)
They say:

"It's a rainy day!"

Boolean#

  • The Boolean (bool) type has two values: True and False.

the_truth = True
print(the_truth) 
True
type(the_truth)
bool
lies = False
print(lies)
False
type(lies)
bool

Comparison Operators#

Compare objects using comparison operators. The result is a Boolean value.

Operator

Description

x == y

is x equal to y?

x != y

is x not equal to y?

x > y

is x greater than y?

x >= y

is x greater than or equal to y?

x < y

is x less than y?

x <= y

is x less than or equal to y?

x is y

is x the same object as y?

2 < 3
True
"Data Science" != "Deep Learning" 
True
3 == "3"
False
2 == 2.00000000000000005
True

Operators on Boolean values.

Operator

Description

x and y

are x and y both true?

x or y

is at least one of x or y true?

not x

is x false?

True and True
True
True and False
False
False or False
False
# True                     and True
("Python 2" != "Python 3") and (2 <= 3) 
True
not True
False
not not not not True
True

Casting#

  • Sometimes (but rarely) we need to explicitly cast a value from one type to another.

  • Python tries to do something reasonable, or throws an error if it has no ideas.

x = int(5.0)
x
5
type(x)
int
x = str(5.0)
x
'5.0'
type(x)
str
str(5.0) == 5.0
False
int(5.3)
5
## RISE settings

from IPython.display import IFrame

from traitlets.config.manager import BaseJSONConfigManager
from pathlib import Path

path = Path.home() / ".jupyter" / "nbconfig"
cm = BaseJSONConfigManager(config_dir=str(path))
tmp = cm.update(
    "rise",
    {
        "theme": "sky",  # blood is dark, nice
        "transition": "fade",
        "start_slideshow_at": "selected",
        "autolaunch": False,
        "width": "100%",
        "height": "100%",
        "header": "",
        "footer": "",
        "scroll": True,
        "enable_chalkboard": True,
        "slideNumber": True,
        "center": False,
        "controlsLayout": "edges",
        "slideNumber": True,
        "hash": True,
    },
)