Intro to
Programming
(with Python)

Fall 2018
course
site

Thu Oct 4

First up: discuss the homework due today.

My sample answers are in code/homework/oct4 :

Please take these examples of mine as "good coding practice" and where you can follow this format for everything else you do this semester: docstrings, doctests (where appropriate, they aren't always), and short, clearly defined functions with clean arguments (inputs) and return value (outputs).

Any questions about anything?

upcoming schedule

Here's the schedule I have in mind the rest of the term :

Then in our last month we should just about time to finish the text :

I will post assignment due next Thursday within the next few days - start by please reading chapter 7 this week.

Decision structures

I'll either just show examples or use the textbook's slides to walk through the topics in chapter 7 .

"max of 3 numbers" example

Which is biggest?

First try: "if x1 >= x2 >= x3" ... Hmmm. Valid in python but not in most code. Also, (5,2,4) gives False; doesn't identify x1 as biggest.

Second try : "if x1 >= x2 and x1 >= x3" ... better i. More about "and" in the next chapter.

if x1 >= x2 and x1 >= x3: 
    maxval = x1
elif x2 >= x1 and x2 >= x3: 
    maxval = x2
else:
    maxval = x3

or how about this instead

if x1 >= x2:
    if x1 >= x3:
        maxvval = x1 
    else:
        maxval = x3
else:
    if x2 >= x3:
        maxval = x2
    else:
        maxval = x3

Draw that as a flowchart and trace through some examples.

Or we could just test each in turn ...

maxval = x1
if x2 > maxval:
    maxval = x2
if x3 > maxval:
    maxval = x3

This approach scales nicely to bigger collections.

In this case python has a built-in ... max(x1, x2, x3). :)

https://cs.marlboro.college /cours /fall2018 /python /notes /chap7
last modified Mon April 29 2024 3:48 am