Skip to content
Home » University of Michigan » Python for Everybody Specialization » Programming for Everybody (Getting Started with Python) » Week 5: Chapter Three: Conditional Code

Week 5: Chapter Three: Conditional Code

Ready to unlock your code’s decision-making power?

We’re about to level up from one-track sequential code to the exciting world of conditional code! Get ready to learn how software makes choices, directing its path with “if this, then that” logic. Let’s dive into how to control which lines of code run and when, creating more dynamic and responsive programs.


Lecture materials


Video: 3.1 Conditional Statements

Chapter 3 Summary: Introducing Conditional Code in Python

This chapter dives into conditional execution, a key concept in adding intelligence to your Python programs. It allows you to control the flow of your code based on conditions instead of simply running one line after another.

Key Takeaways:

  • if statements: The heart of conditional execution, introducing a question that determines whether to execute the following code block.
  • True or False: The answer to the if statement’s question, determining which code path to take.
  • Indentation: A crucial aspect of Python, marking the scope of the conditional code block. Indent to enter, de-indent to exit.
  • Comparison operators: Tools like >, <, <= and != help formulate meaningful questions in your if statements.
  • One-way decisions: if statements lead to either the indented block or skipping it based on the condition.
  • Two-way decisions (if-else): else allows offering an alternative code path if the if condition is false.
  • Nesting: You can have if statements within other if statements, creating complex decision trees.

Remember:

  • Indentation matters! Keep consistent spacing within blocks to avoid errors.
  • Use tabs with caution or convert them to spaces for Python compatibility.
  • Think in blocks: visualize the scope of each if statement and its corresponding code.

Coming up: More about conditional patterns like elif, exploring logic and control flow in greater depth.

Here’s a tutorial on conditional code in Python:

Understanding Conditional Execution:

  • Sequential vs. Conditional: Sequential code executes lines one after another, while conditional code allows for decision-making.
  • Making Choices: Conditional code enables your programs to choose which path to execute based on certain conditions.

The if Statement:

  • Asking Questions: The if statement introduces a question to be evaluated.
  • True or False: The question evaluates to either True or False.
  • Indentation: Indentation defines the code block that executes if the condition is True.
  • Colon: The if statement ends with a colon, indicating the start of the indented block.

Comparison Operators:

  • Tools for Questions: Use comparison operators like ==, !=, >, <, >=, and <= to create meaningful questions in your if statements.

One-Way Decisions:

  • Executing or Skipping: If the condition is True, the indented code block executes. If False, it’s skipped.

Two-Way Decisions with else:

  • Alternative Path: The else keyword provides an alternative code block to execute if the if condition is False.

Nesting if Statements:

  • Complex Decisions: Embed if statements within other if statements for intricate decision-making.

Key Points to Remember:

  • Indentation Matters!: Python relies on consistent indentation for code blocks. Use four spaces per level.
  • Tabs vs. Spaces: Use spaces for indentation to avoid potential errors.
  • Visualize Blocks: Conceptualize the scope of each if statement and its corresponding code block.

Practice and Experiment:

  • Apply Concepts: Write code examples to solidify your understanding.
  • Explore Variations: Try different conditional patterns and values.

Next Steps:

  • Elif Statements: Learn about the elif statement for multiple conditions.
  • Logical Operators: Combine conditions with and, or, and not.
  • Control Flow: Master conditional execution for programming logic.

Hello and welcome to Chapter 3. Now we’re going to talk
about conditional execution. Conditional execution is where we start
sort of adding more intelligence. Sequential execution,
you just type them in and Python does it. But sequential execution is where
you can choose one of two paths. Turn left, or turn right, or go straight. You can make choices and this is an essential part of
making computers seem intelligent. And so the key to this
is the if statement. So the if statement is the reserved word
that indicates that we’re going to do something conditionally and
it’s not that hard to read. So the if statement has a condition,
it’s really a question. Unlike x = 5, which changes
potentially the value of x, x less than 10 is asking a question.
It’s asking, is x less than 10? And that returns a true or a false. In this point because x is 5,
x is indeed less than 10 so it’s true. These if statements end in a colon. And they start an indented block of text. It’s kind of like an outline that
basically says, if this is true, do this statement. Otherwise, skip the statement. So in this case, it comes in, x is less
than 10, so it does the statement. Then it comes back and says, if x is greater than 20, this one
evaluates to false, and so that skips it. So that’s why we see Smaller print out
and Finis print out, and this line never executes. So that’s why I call it conditional. Depending on this question
that’s being asked, the line inside the indented block
will either execute or not execute. And so you can kind of look at this
as if you were driving a car, right? You execute this statement then it goes to
the next one, then it asks the question. Is x less than 10? If the answer is yes,
it turns this way and drives down here and runs this code, does that thing. And then it rejoins. And then it says, oh, is x less than 20? Well, since x is 5, the answer is no. And so that skips that completely and
then it runs this and then it’s done. And so this code never runs, okay? And so when we say conditional, we say,
yes that one ran but that one did not run. And so that’s why we call it conditional
because it may or may not run. The other thing that’s important
about this is this indenting notion. That we start with an if,
have this colon, and then we indent. The indenting can be a variable. We tend to indent by four spaces. That’s the recommended pattern. And we’ll see in a bit the indents
can be longer than one line. This is only a one-line indent where you
have one line that’s conditional but you will see in a second how we can
do this with more than one line. So, good time to talk about
the comparison operators. Again, the problem here has to do with the
limitations of the keyboards in the 1950s and the 1960s of computers when most of
these languages were kind of designed. So less than is on keyboards, less than followed by an equal
sign is less than or equal to. Double equal, this is probably the
part that’s the hardest. Double equal is a question mark. Remember equals is an assignment
statement, it has kind of direction. x = 1, right? x = 1. That puts 1 in x. This, if you say x == 1,
you’re asking the question, is x equal to 1 and it doesn’t harm x, So that’s probably, it takes a while. If I was designing a language,
I would say, assign x into 1 and then this would be single equals. But, sorry, I didn’t design Python so
that’s not the way it is. So, double equals is the question
mark version of equality. Greater than or equal to and greater than,
and then not equal is exclamation point. Another word for exclamation is bang. We say bang equal or not equal and so the exclamation point is like
not equal, sort of like emphasis. I don’t know. That’s how I remember it. Remember that none of these harm
the data that they’re looking at. They evaluate and
then return us a true or a false. So here’s an example of all
these things kind of in action. For x = 5, they’re all going to be true. If x = 5, remember that’s the question mark. If x is greater than 4,
and the answer’s yes, print Greater than 4. If x greater than or equal to 5,
that’s also true so this part runs. You can also, if it’s
only one line of stuff, you can sort of pull this
line up to the end here. If x less than 6, print Less than 6. If x less than or equal to 5,
print Less than or equal 5. If x is not equal to 6, print 6. And so you see this pattern of indent,
end of indent. Indent, end of indent. Indent, end of indent. Indent, end of indent. So this is an important part of Python. Not a lot of languages make
the indenting of lines a syntactically meaningful thing,
but that is how Python works. And so if you don’t indent it, it’s not
going to work the way that you expected. Especially if you’re coming from
a programming language like JavaScript, or Java, or C where the actual
spacing doesn’t matter. In Python, the spacing does matter. And so this is an example of a longer
block of text that’s indented. And you can now see kind
of how this indent works. x is 5, we print Before 5. If x = 5,
this is going to be true because it is. Colon starts an indented block. Now by maintaining the same indent, you make this all part of
the conditionally executed block. So this is three lines
of code that it runs, it runs this line then sequentially runs
this line, sequentially runs this line. And we indicate when it is that we
want to get out of this block and then continue by de-indenting, okay? So when it’s true it runs all of them,
then now it’s running sequentially, sequentially, sequentially. And now it says, oh if, if x = 6. Well this one’s going to be false,
then that skips all of these. None of these run. Skips all of the indented blocks. And so this indenting is a way to,
in effect, make bigger blocks of conditional code,
or multi-line blocks of conditional code. So, indentation is important in Python. It’s more important in Python
than literally almost any other programming language. We always use indentation in other
programming languages to mentally keep track of blocks of text, but it’s not where the programming language
will complain if you get it wrong. So you have to sort of think why did
you increase the indent, which is like if, after an if or a for or a while
statement, which we’ll see in a bit. You maintain the indent, which means you
stay the same, or then you de-indent or you reduce the indent back, and
that is the way to end a block. So you reduce it. Blank lines don’t matter, and then comments by themselves on a line
don’t make any difference for indenting. And so, as you’re doing this indenting, it’s really natural to hit the tab
key on your computer and to move in. So you do if blah, blah, blah, and
then on the next the line, you hit tab. The problem is is that Python can
get very confused if you sometimes are using four spaces, space, space,
space, space, and sometimes you use tab. And the danger is it can look
right on your screen, but Python will still complain to you. And so if you’re using a text editor that
might be putting tabs into your document, find where it turns them off. So a programmer editor,
we’re not talking a word processor now, we’re talking about a programmer editor
like Notepad or Text Wrangler. These have a setting, whether or
not to turn tabs into spaces or not. So it either puts a tab in the file or
puts spaces. And so this is a good time,
if you’re using one of these text editors, to make sure to turn tabs off,
or cause tabs to be expanded. So you don’t end up with,
in a few weeks or a few days, with Python errors that you just don’t
understand, and that makes you grouchy. Here’s the good news, and that is,
if you’re using our recommended Atom text editor, once you save
the file with a .py extension, it automatically just uses, you can hit
the tab key and it moves in spaces. And so that is very nice and it’s just
one of the many reasons that we recommend and like Atom to edit these files. So just understand that tab and
spaces might look the same on your screen, but to Python, they may or
may not be equivalent. And you can up with spurious
errors that Python will give you if you get your tabs wrong, okay? So here’s just some of the screens. Depending on your tool that you’re using, your editor that you’re using,
you might have to find it. But it’s like auto-expand tabs,
or replace tabs by spaces, etc. The idea is don’t put
tabs in your document. The best practice is to use spaces and don’t put tabs in your document when
you’re writing Python programs. So, you have to think about this,
about the indenting and the de-indenting, when do you go in,
and when do you come back out? And so,
it’s the way that we define blocks. So we have sequential code,
which maintains the same indent. Now we see the if and we see the colon,
that means we start an indent. And then to stay inside that block
of code, you maintain the indent. And then to end that block of code,
you de-indent. So you think of this like I am
de-indenting, I’m doing this on purpose, it’s not like randomly. If this was in,
then it would function differently. The fact that this print is out means
it’s not part of this if block. These two statements are part of
the conditional code, the print really is the thing after the if, right? And so this is going to run no matter
what, these two may or may not run. In this case, because it’s true,
they are going to run and come back out. So, this is conditional code, this is sequential code. And if we continue down, we haven’t talked
about loops yet but the for keyword is a loop and this is telling it to run this
thing five times, and it ends in a colon. And then you go in and then you have some sequential code, then
you have an if, this is called nested. That’s a block within a block. So the if has another colon so
we go in even farther. And then we de-indent to
this level of this if, and later we de-indent to the level of the for. So you kind of have to
match these things up and decide how you’re going to end your
conditional code, or end the looping code, which we’re going to learn in
the next section how that works. So what you want to do after a while, and
it won’t take you too long, but sort of train yourself to start thinking about
the fact that these are blocks of code. That you can sort of draw these
squares around the blocks of code. And I’ve drawn the square here,
the if starts it. You can also kind of use the colon
as your little mechanism. And then the de-indent stops it, and
so this is the conditional code. And then you can see where the if
starts and then it’s the line that lines back up with the for,
that is the scope of the entire for loop. Same here with with the if. The thing that lines up,
that is the scope of that if block. So mentally, you have to realize
that the de-indenting and indenting adds meaning to your program. I mean, they absolutely define which
things are going to run as part of an if statement or regardless of
the value in the if statement. So start seeing these,
and in terms of nesting, you can see them inside one another. It’s like the Russian dolls,
where you’ve got a block of code, within it you’ve got
another block of code. And believe me, we’ll go down, down,
down, down, down, out, out, out, out, out. And so,
start seeing these indenting as blocks. Just start feeling that. Like I said, nested decisions,
if there was a for loop with an if, we can also have a decision where
there’s an if within an if. And so in this case, x is 42,
if x is greater than 1, that’s true. So then we’re going to print this,
if x is less than 100, that’s again true. So we’re going to go in and run this,
and then we’ve de-indented twice. And so this does line up with the if, so this functions as the end of both
this block and the end of this block. Because it lines up out here. So, if we look at it from
a GPS perspective, it’s true, x is greater than 1, we print that. We ask another question,
that’s a question, and it’s yes and now, we’re continuing back down. So we’ve kind of come out
of the indent block. And as you’ve drawn,
we kind of see this is indented once and this one is indented twice,
just the way I drew it. And the same is true here. This is indented once, once and
then getting too busy here. This one’s indented once,
this one’s indented once, this one is indented twice, all right? So start counting those indents and
knowing how the de-intents works. So we have one-way decisions and
very commonly, we have a two-way decision. We call this else. We want to basically do one thing or
another, it’s like a fork in the road. If something is true,
in this case, is x greater than 2? Well, it’s 4, so it is true. We do one thing. And if it’s false, we do another thing. In this particular example,
we don’t do this one. We only do this one over here. But you got the idea
that with one if test, we choose alternatively between one and
the other of the choices. So this is how we write that in Python. We say sequential code,
question mark, colon. And then we have the true part, this is the part that executes if
the question evaluates to true. And then we de-indent and use the keyword
else, so else is a Python keyword. And you see another colon here so
we sort of de-indent, say else and then re-indent and then we have this part. And so that’s how we capture
the other half and then of course it runs no matter what. So, if we were to do this. If it’s true, it runs this and
then skips that. And if it were false,
which it’s not, it would skip this, run this, and then continue. The point is,
if you use an if-else structure, one of these two things is going to run. And it’s sort of the same as this, it comes in here,
there’s no scenario in which both run. It’s going to run one, and by running one,
it’s not going to run the other one. That’s how an if-then-else happens. So coming up next, we’re going to talk
about some more conditional execution patterns, a little more complex stuff,
else if, etc.

Video: 3.2 More Conditional Statements

Summary of the video on Conditional Code in Python:

This chapter dives deeper into conditional execution, the ability to make your code choose which path to take based on certain conditions. Here’s a breakdown of the key points:

Building Blocks:

  • Comparison operators: Tools like >, <, ==, etc., help formulate meaningful questions in your if statements.
  • Logical operators: Combine conditions with and, or, and not for even more flexibility.
  • Indentation: Crucial for defining the scope of your conditional code blocks.

Decision Structures:

  • One-way decision (if): Executes code if the condition is True, skips it if False.
  • Two-way decision (if-else): Offers an alternative code path if the if condition is False.
  • Multi-way decision (elif): Combines multiple if statements with different conditions, triggered one at a time in order.
  • Nested decisions: Embed if statements within other if statements for complex decision trees.

Handling Errors:

  • try/except: Catches potential errors in specific code blocks and runs alternative code instead of crashing.

Key Takeaways:

  • Think in blocks: visualize the scope of each conditional statement and its corresponding code.
  • One entrance, one exit: Each block has a clear starting point and an ending point.
  • Order matters: elif statements are checked in sequence, and only one will trigger.
  • Use try/except strategically: Don’t put your entire program in it, focus on catching specific errors.

Remember:

  • Indentation is vital. Consistent spacing defines your code blocks.
  • Use tabs with caution, spaces are preferable for Python compatibility.
  • Practice and experiment. Apply these concepts to solidify your understanding and build logic into your programs.

Next Steps:

  • Explore advanced conditional patterns like case statements.
  • Master logical operators and complex decision-making.
  • Learn about control flow and program execution beyond basic conditional statements.

By understanding these concepts, you’ll be able to build more powerful and versatile Python programs that can make decisions and adapt to different situations.

So welcome back, now we’re going to build
up and talk about some slightly more complex conditional execution
patterns that you can build up. So as you do the if-then-else, again, one of the things to do is to visualize
the blocks, start thinking of the blocks. And in this case, you’d think of the block
as sort of starting at the if and then ending after the last indented line. But the if and the else kind of
are a piece of one thing and you can sort of think of
this as the block, right? And one of the things about these blocks
is they have one entrance and one exit, not that that’s a big deal. But it’s a good way to think about how
you mentally start drawing the blocks. You see one entrance and one exit,
and there’s some complexity, there’s some logic that
you’re sort of building. And that’s how these blocks work. So the next step up in
complexity is a multi-way if. And that uses a keyword called elif, which
is really a combination of else and if. So the way it works is, probably easier
to do this on a GPS version of it. Is it comes down here,
forget what’s in here, it asks yes or no. If it’s yes, it runs this one,
and then it’s all done. If it’s no and then yes,
it runs this one, and it’s all done. And if it’s no, no, no,
it runs this one and it’s done. A key thing is it’s only
going to do one of these three. It’s not going to do two,
it’s only going to do one. And it checks these questions in order. And then this else is like a catch-all. So let’s take a look at how
this particular one works. It depends on the value of x. So let’s, what if x were 0? Well, if x were 0, it would come in,
ask the question, is x less than 2? Yes, it is. So it’d run this code and
it would finish down here. So it would come over here, true,
run, and now skip all the way down. If you draw blocks,
the box would be this box right here. It skips out of the box, or if you draw the box over here,
the box would be right here. Once you’re done with this line of code,
with this block of text right there, or block of code, you exit the block. You don’t like come back and
look at this question. You have run, one thing has turned true,
and you’re done. If, on the other hand, x was 5, you would
see a situation where it would come in. This would be false, and so it would skip. Then it comes to this next elif,
this becomes true. So then it jumps in and
does this code, runs out, and is done. Does not run that,
does not run that, does run that. So, comes in. No, it’s not less than 2. It is less than 10, so
we’ll run that little block of code, and now we are all done completely. So no, no, but yes, okay? And so that’s how it works. These are done in sequence. They’re not looked at sort of in
parallel or all at the same time. If, on the other hand, x was 20,
it would say false, skip, question mark. False, skip. Oh, else. Then the else always gets
triggered if it gets that far, and then it runs that one. So here we say if it’s less than 2, no
it’s not, is it less than 10, no it’s not. And if it’s there, then we just hit
the else part, and we finish and we continue on. So this part doesn’t run,
this part doesn’t run, and that part runs. The rule is one of the three will run,
and the other two will not. It only triggers once. Once it’s triggered, then it’s
done with the whole if statement. And again, I think of this as the block,
and you’ll see in a second. Once one of these things hits true, it runs
this and then exits the block completely. So there’s other variations on this. You can if you want have no else. So there’s no need to have an else. What we’ve done is we’ve simply
deindented this next line. There’s no else here, but that’s okay. It does mean that for some value of,
they might not either execute, right, because there’s no else. If there’s else,
then at least one will execute. But if there’s no else, then it could
be possible that zero executed. In this case, x is 5,
it’s not going to do this one but it is going to do that one
because x is less than 10. But if x was, for example,
50, then that would be false, that would be false, and we just go. And then neither of these two
things would execute if x were 50. Okay? So it just means you don’t have
to have an else if you don’t want to. Further, you can have lots of elifs. If x is less than 2, do this,
elif, elif, elif, elif, elif. And remember, it checks them in order,
first, second, third, fourth, fifth. So if x was 15, this would be false,
this would be false, this would be true, so
it would run this code. And then it would come down
whatever is next down here. So again, only one of these
is going to trigger. No, no, yes, no, no, no. I mean, 15 is indeed less than 40. If it came here, it would be true, but
it doesn’t matter, because one is triggered, and so then it takes the entire block,
and there’s our entire block. So as soon as it executes one, the next thing to do is exit
right out of the block. Okay, got it? Okay, so here are a couple of puzzles. I’ll give you a second to pause this. And the question is, to look at
some of these, depending on for a particular value of x,
you will have none of them execute. So which will never happen for
some particular value of x? Meaning you can pick any value for
x you want, but there’s some that you
can’t cause to execute. Okay? So I’ll pause for a second and let you pause
the video if you want and then I’ll come back and
explain it to you. Okay, you had some time to pause. Hopefully, you did pause or
didn’t pause, but it doesn’t matter. You can still pause while I’m
talking until I start drawing and telling you the answer. Okay, so in this one, if x is less than 2, do this, else if x greater than or
equal to 2. The one that’s never going to
execute is this one right here. And that’s because, no matter what
value of x, it is either less than equal to 2 or greater than or equal to 2. So for any value of x, no matter what you
pick, it’s either going to run this one or this one. But it’s never going to run that one for
any value of x, okay? So, that’s a little tricky. I just happened to have constructed my
logical questions in such a way that they covered all values of x, and
so the else was kind of irrelevant. Now, I wouldn’t even draw this this way. If I was going to draw this,
or write this code, I would probably just make this be
an else : and this not be there. But this was more of
a puzzle than anything else. So in this next one, we have to remember
that these things happen in order. So if x is less than 2,
we’re going to run this. If it’s less than 20,
we’re going to run this. If it’s less than 10
we’re going to run this. But the problem is, all values of x
that are less than 10, for which this would become true,
this is always true. So a value like 6, this becomes true. So that means that if it’s something
like 6, it’s going to run this and come out and
never ask this question, right? So that’s the key, even though this
is true and this is true for the 6, it never even gets here because
this one triggered first. Okay, and so that’s why this is the line
of code that no matter what the value for x, will never run. Okay, so the last conditional
code is what’s called the try and except structure. And if you learn other
programming languages, this sort of catching errors
is a more advanced concept. But in Python, we tend to have to use it
earlier because there are things where if you don’t use it, the code blows up. And the whole idea of a try
except is that you have a bit of code that you know might fail,
and so you kind of want a take out an insurance policy on it and
say, hey, give this a try. If it works, great, if it doesn’t,
do this other thing. Don’t blow up, don’t get a traceback. And so this is a way to eliminate or catch a traceback. Something that would
otherwise be a traceback. That’s what this is for. So if you got some line of code, and
you know that this might blow up and have a traceback,
then you use try/except around it, okay? So let’s take a look at something. This is a sample we had
from the previous code. And it comes down, it sticks Hello Bob in,
then it converts this to an integer. And we know that if these things
are aren’t digits, this code blows up, and so it runs and we get the traceback. And the traceback happens because of this
line right here, but the key thing about the traceback is that the traceback,
as I told you before, it stops. And it stopped at line 2, which means
this is the last line it executed, but it doesn’t continue,
which means this code is gone. I mean, it never gets there
because it’s like, I’m confused, I’m quitting,
I have quit at line 2, okay? I quit at line 2. So that code, it’s as if it’s not there. Now sometimes that’s fine with you,
you just want to blow up and you want to see the message, you want to
go look at line 2 and fix line 2 or maybe you typed the wrong stuff in. But sometimes you want to
control for this. You want to say, you know what,
I know what I want to do here, and I don’t want to die,
I don’t want to blow up. I want to continue, I want to put
out an error message instead. And so, the key is, is when this code
blows up, it’s something that you kind of take personally because you
are that set of instructions, and when a traceback happens inside the memory
or CPU, that’s you that’s being vaporized. You’ve been traced back, and so
we take it kind of personally. I mean, if you were to use software
that I built, like the autograder for this class and
you started getting tracebacks, I’m like, hey,
that’s kind of a personal thing. I didn’t do my job well,
I didn’t catch all the errors. I didn’t think of everything. You could type something that
will cause my code to blow up. And so I take that kind of personally. And so we have to be able to
compensate for situations that we know
might cause errors. Especially those where
the user can type something that can cause my program to blow up. That’s really, like,
I’m going to let you blow my program up? I am going to compensate. I’ll tell you, sorry, that’s bad data. But I don’t want you to
ever see a traceback because it’s kind of shameful to see
a traceback for a professional programmer. Okay, so here’s how it works, it’s a bit
of stuff with some indentation and colons. It looks like a lot, but
don’t worry, you’ll figure it out. So the idea is, is you have a line
of code that you know is dangerous. So this conversion of an integer, let’s just say this came
from an input statement. In this case,
we’ll just make it be Hello Bob. We know this is going to fail. And so, this is the line in which we
kind of want to take out insurance on it. So instead of just putting
this line in here, like we did in the previous example,
we just had it right there. Instead of taking that line there, we’d say,
you know what, we’re going to take and stick this in a try and except block. So we say the word try. Try ends in a colon, which means
it’s an indented block of code. And then we put the dangerous line
in there, and then we put except. And then the except is kind of
like an else, an if-then-else, but what it really is is code that Python
will execute if something goes wrong. So this is either going to run and
work and skip this. Or if it goes bad, it’s going to run,
blow up, and then run this stuff and then continue on. But in no case you will get a traceback,
meaning if this line is going to generate a traceback,
it actually just runs the except clause. So it’s kind of like if things work out,
do this, if things don’t work out,
do this other thing. So in this case, when this runs, this is
going to fail, because that’s Hello Bob. And then it’s going to come out here and
set this to -1. So that’s going to blow up. Set this to -1,
that’s going to print it out. So it says, First equals -1. And so we didn’t traceback. In the previous time we ran this,
it traced back because we caught it. Now, the way the try/except works is,
if everything is fine, it has no effect. So if we, the next thing we’re going to
convert is 123, the digits, 1, 2, 3, in a string. We do a try, and we try to convert it and
it works, and so we just keep on going. We don’t run the except. So this code does not run
because this code succeeded, there was no traceback that
was going to be generated. There’s a traceback generated up here. There was no traceback generated here,
so it comes through, and the result is istr ends up
with a integer, 123. And so it’s an insurance policy or
it says, I know this might blow up and if it does, I’m giving you alternate
text or alternate code to run. So the thing about the try/except block,
and you might be tempted to do this, and that is,
if you’re getting tired of tracebacks and blowing up, you might want to put your
entire program in a try and except block. And you might say try blah,
blah, blah, blah, and then except something bad happens. The problem is,
is if your program’s blowing up, you actually want to know about it. And the way the try and except block works
is, if it’s in the middle of a try and except block and something goes wrong,
like in this particular line, it doesn’t come back and
finish the try and except block. It actually exits to the except and
then comes out. And to draw this in a diagram,
so here we go, we start this thing,
we’re in the try block. We’re doing print,
print’s safe, doesn’t hurt anything. We do this,
this blows up with a traceback. Traceback and
then that says go to the except block, run whatever is in the except block and
then continue on. What’s not going to happen is it’s not
going to go back up and do this, or back up and try this one again. No, no, no, no, no. Once it gets the except block,
there’s only one way out to the bottom, so this line of code never executes. And so that’s one of the things
we try to do where we just, you don’t put too much stuff in. You would put this print statement out
here and this print statement out here, and you’d only put one line in
the try/except block, if possible. Sometimes you put a few more lines
in there, but you try to minimize. You know what line is dangerous. Print is not dangerous,
these two prints are not really dangerous, don’t put them in the block. Because any line in the block, as soon
as it hits a bad line with a traceback, it’s out of the block,
runs the except, and then continues on. So here’s a more practical example, Where we’re going to read
a number from the user and print out either Nice work or
Not a number. And so, we take an input statement,
which stops and waits for us to type, and then we type 42. And 42 goes into rawstr and
then we know that this int is dangerous. Right? And this rawstr came from the user,
whatever the user typed. And so we put it in the try block,
and if it’s 42, it converts and it says ival is greater than 0,
we print it out, so it says Nice work. Now, we’ll run this code again. Okay, we run it a second time and
now we enter something, it says forty-two but it’s like f-o-r-t-y. And so forty-two is what goes in here. We as the programmer had no control over
what our crazy user was typing, right? You’re starting to be a programmer and
crazy users do crazy things to your poor programs, even if they’re
only like seven lines long. So we got forty-two coming in here, we know this is going to blow up, this
int is going to blow up with a traceback. But that’s okay, we’ve compensated for
that and we told Python, hey, we know that might happen and
if you detect a traceback, jump straight into the except block, run
this, set it to -1, and then continue on. So this is the de-indent of
the try/except block, and if it’s greater than 0 we say Nice work. But in this case, it’s not, and
we say, Not a number, and so it comes out with Not a number. What’s not here is a traceback. There is no traceback in this,
that’s what we achieved. And it doesn’t hurt. When it works, the try/except kind of
does nothing because the except code, when it works, is ignored. So it’s like code you add in case
something happens in an other line of code. Pretty cool, actually. So you have a couple exercises and
I’ve got some videos of those exercises. So in summary, what we talked about in this chapter is
comparison operators, logical questions. A key is that these comparison
operators don’t change their arguments. You can say if x is less than 5,
doesn’t change the value for x. We have indentation and
how important indentation is. One-way decisions with if,
two-way decisions with if-then-else. Nested decisions where you have an if
inside of an if that moves on in. Else-if, and then try and except to catch
errors that you want to catch, okay? So, thanks a lot.

Review: Chapter 3


Assignment: Chapter 3


Graded App Item: Assignment 3.1

Code

Video: Worked Exercise: 3.2

Summary of video on Exercise 3.2:

Challenge: Fix the Python program from 3.1 to handle errors when entering non-numeric input.

Solution:

  1. Identify the error: Line 4 (converting “ten” to float) throws a traceback.
  2. Implement try/except block:
    • try: Wrap the dangerous lines (conversion and calculation) in try.
    • except: If an error occurs (e.g., non-numeric input), print an error message and quit the program using quit() instead of continuing with traceback.
  3. Bonus:
    • Add a sanity check by ensuring both inputs are numbers before conversion.
    • Remove unnecessary print statements for a cleaner code.

Key Takeaways:

  • try/except block helps handle errors gracefully without crashing the program.
  • Catch specific exceptions instead of catching everything.
  • Consider quitting the program if the error renders it unusable.
  • Keep code clean and efficient by adding checks and removing redundancy.

This exercise demonstrates basic error handling techniques in Python, a crucial skill for building robust and user-friendly programs.

Hello, welcome to Python for Everybody. I’m Charles Severance, your instructor. And in this short video,
we are going to do exercise 3.2, which is really just
a rewrite of exercise 3.1. We’re going to deal with some error
conditions using try and except. So let’s go ahead and get started, but
this is a good example of something where you want to start with
the previous assignment. So let’s open the file that I did before,
and so this happens to right here, ex_03_01. And there’s my previous
program that I wrote for exercise 3.1. And let me set myself up with Python,
so I can actually run it. cd Desktop, cd py4e, these will get better, cd ex _03_01 ls. And I can say python3 ex_03_01.py, and it works fine if you
give it the right data. But if you give it bad data,
10 and t-e-n, it blows up, right? And like always, you’re getting
tracebacks for all kinds of things. But this one’s pretty clear. If you slowly but surely don’t get mad, just say, oh, line 4,
what could be wrong in line 4? Could not convert string to float ‘ten’, so
what it’s complaining about is on line 4, this variable sr, which is the string t-e-n,
the letters t-e-n, is not working. So this function is blowing up, okay? So that’s what it’s complaining about and
that’s what we want to deal with. Now when you’re using try and except,
you don’t want to just put a try, you want to limit how much data you
put in the try and except. So let’s get started on assignment 3.2, so the nice thing that we can
do here is that we can say file, save as, and
go up a folder to PY for Everybody. Make a new folder called ex_03_02, and then save the file as ex_03_02.py. Okay, so now make sure, get rid of that. So make
sure this is different, we’re in a different folder, so we’re not editing that old file. And the first thing I’m going to do is,
hey, come on. Well, I’m going to get rid of
some of these print statements. I mean, the code’s going to work. Come on. Okay. So the dangerous line of code is right
here and so, the problem becomes how are we going to deal with this?
And so, let me do this as well. So here is, if I do pwd, I’m in ex_03_01,
this could drive you crazy. Oh wait, I’m in the wrong folder,
how come this is in the wrong folder? I put ex_03_01, why is this in? See, you’ve got to watch this. I think I’m in the wrong folder. File, open. ex_03_02, ex_03_02. Okay, so now I’m in the right spot. I don’t know why that wasn’t
showing up right, but keep your eye on this, especially if
your using file names that are so. So, I’m in this ex_03_01, so
I’m going to use a command, and you can use this both in Windows and
in Linux and in Mac, cd dot, dot. And what that does is
that goes up a folder. Part of the goal of this course is to
teach you how to use things like this, just how to use these command lines. Because to be a programmer, even doing the
simplest stuff, you’ve got to manipulate files, and
you’ve got to be able to use command line. You’ve got to use all these things. Not everything is a full screen
clickety pointedly thing, okay? And so what does cd do? Well, it looks at this and it goes up
one folder, so it moved us up into here. And so you can see after the cd,
my current working directory is that, and I can do ls to see the folders. And now I see my new ex_03_02, so I’ll say cd ex_03_02 and
part of being a programmer is having a lot of folders with
wierd names to organize your stuff. So here we go, now we have this file and this file in the same place, pwd, this matches this, that
file matches this name, and I can say python3 ex_03_02.py 10, 10. Okay. So now, I’m just nervous enough
to want to double-check this, and so I will do something like this,
I will say XYZ Pay, and save it, and
then run it again, python3. I don’t care about the numbers. See the XYZ Pay? So now I know I’m in that file, so
I do stuff like this all the time to triple-check that I’m really
working with the file. So, now I’m in this file and now let
me make my mistake again. 10, ten. And now there is my failure, right? So there’s the mistake, and
that’s the thing we’ve got to fix. So, we have these lines of code. So what you do in Python when you know
that there’s a dangerous set of lines and you want to take out insurance on those. You put them in a try-catch block,
a try/except block, and what are we supposed to
say when it blows up? It says, error, please enter numeric
input, I’ll just copy that and paste this, print “error,
please enter numeric input” make that a little bit wider,
print that out. And I want to put this
print statement back in. Okay? So here we go. So now what’s going to happen,
is we’re going to come in here, we’re going to run these. If they work,
we’ll skip the except block and continue. If they blow up,
then it’s going to run this except block. So let’s run it. Let’s start with the working case,
that still works, that’s good. it comes and does this extra
print that I’ve got on line 9. Let’s go in the bad case, 10, ten. Okay, so we’re going to parse this
a little bit. So it says error, please enter numeric input, but
then I still get a traceback. And you’re like, I hate computers,
because doesn’t this look beautiful? I got a try and indent it,
it looks just like what I saw, right? It’s so beautiful. Why does this computer hate me so badly? Well, then take a step back,
and say, you know what? The computer is admitting that it’s
confused by what you’ve given it. And so, just look, what line
are you mad about, dear computer? Line 9. Okay, let’s take a look at line 9. It’s always this line or
the one before it, almost always. Almost always it gets it right. And it says name ‘fr’ is not defined. So let’s just focus on this,
it’s complaining about this. And the problem is that it came
down here, it run through here, came down here, ran through here, and
this blew up, that line never ran. That’s the line that blew up,
and then it ran this error. So it never, never,
never got a variable or a value in fr. And that’s because, in this particular
case, we would either have to put an if statement in to make sure
the rest of this code, or we can say, if everything is just so bad in this
thing and I don’t want to continue, quit basically says
do not continue, okay? So when it comes in here, it runs this,
it blows up, it comes down to here, it prints this, and then it quits. And then it doesn’t continue on. So now I can run this again,
10, 10 it works. 10 and t-e-n, and
it fails exactly the same way, this part here is exactly
the same as this part here. The difference was as soon as
we print this out, we quit, so we don’t continue on, okay? So if you’re doing really simple input
checking, sanity checking is one of the things we call this, just is the
data make sense and don’t continue. If the data doesn’t make sense,
if these two statements don’t work, then whatever we’ve been given is
nonsensical data that we’re not capable of handling, okay? So that is how to write exercise 3.2. And I hope that you have found this little
video useful, and thanks for watching.

Graded App Item: Assignment 3.3

Code

Bonus: Chapter 3


Video: Interview: Massimo Banzi: The Arduino

Summary of the Arduino Interview:

Early days and challenges:

  • Arduino started as a project to teach electronics and prototyping to non-technical students.
  • Existing tools were limited and didn’t work well on Macs, lacked USB support, and were expensive.
  • The team experimented with existing platforms and eventually built their own based on Processing and open-sourced hardware.

Growth and adoption:

  • Initial versions were distributed as PCBs for people to assemble themselves.
  • Workshops and online communities played a crucial role in spreading awareness and knowledge.
  • Key events like collaborations with NYU and SparkFun Electronics fueled growth in the US.
  • The “viral aspect” of user-generated projects and documentation boosted adoption.

Vision for the future:

  • Empowering people to be creative with technology and understand the world around them.
  • Moving beyond passive device consumption to active design and programming.
  • Encouraging innovation and questioning the status quo in the digital space.
  • Avoiding a world where technology dictates our lives instead of vice versa.

Overall:

The interview paints a picture of Arduino’s journey from a niche academic project to a global phenomenon democratizing electronics and empowering creativity. It highlights the importance of open source, community, and education in fostering technological innovation and shaping a future where people are masters of the technology they use.

[MUSIC] [MUSIC] [MUSIC] When you’re doing production design
there is this idea that you need to be able to
build prototypes. Because one of the, in a way,
important elements of that discipline is being able to test the
things you do with people. So, you know, you want to make a website,
you make the prototype, a mockup of the website, you try it with
people, you see how they react. And the same thing with physical devices, but physicals means you need to
learn about electronics. So we had to create different classes
that would basically make electronics approachable to people that
don’t have a background in electronics. They next to zero software
development background. So, what we did when I started
teaching is that I started to experiment with the tools that
were available on the market. [COUGH] And then I realized
there were a number of shortcomings, like, every, designers
mostly like to use Macs. Mac haven’t had serial ports for ages. They all have USB ports. And still, you know, there are
professionals that have their development tools that
are released now in 2013 they still only have serial ports, which,
it’s really weird, because I haven’t seen a serial port on,
on a laptop for a long time. And on desktops, sometimes don’t
even have them anymore. So we had to make something that would run
on a Mac, that would be easier to use, that would be cheaper than what was available on the market back then
which, you know. And also we had this programming language
we sort of inherited from the MIT called Processing, which was used to teach about
programming to artists and designers. So we thought, well, you know,
why don’t we try to make that run on a microcontroller, so that
was based on Java. Microcontrollers tend to, they don’t
like Java very, very much. They prefer languages, it’s easier to work
with languages like C++ or C. So we did some experiments,
then one student of mine did a thesis on the [UNKNOWN]. So different projects sort of
followed and then we ended up with the first
version of Arduino which, based on the work that this student
Hernando Barragan did on a project called Wiring, we
re-implemented it from scratch. So we reused the APIs but we rewrote the
whole thing to be completely open source, because we also wanted
something that would be easy for people to reproduce,
to build upon. So we wanted to remove the barriers, and
one of the things that we did is also that, since at the time we haven’t got, in
a way, a clue how we were going to manufacture,
we didn’t want to set up like a classic manufacturing
company, or go to a venture capitalist or something
because obviously there was, back then nobody would have
even talked to us. So we thought, you know, let’s release the
hardware as open source so that people can build it if they want to. And they started to make, we just started
to make the PCBs of the sort of two-hole version and, and so we, we would just
give them away to people as a gift. So, just take this PCB, assemble one. And some people started to assemble it.
So they went on the website, they got the instructions,
they started to write. That’s to, to download the code,
to solder the, the boards. And so we got some feedback and we started
to build up a little bit of an audience. And, and, you know, that’s, that’s
how we started. >> So, so, talk a little bit about the the transition from people coming in to
the four-week class and spending the first three days soldering to the, to the sort of scaled-up
manufacture. >> [LAUGH]. >> I mean, what happened? How, how did you get pushed? What triggered the >> Well, we started to do
introductory workshops for people outside of the school. I originally started this project with a
friend of mine called Avit Quartinas who teaches in Sweden, and the two of us
both had similar issues with our students. We wanted to, you know,
there was a bunch of input that we gathered and so we started to make the
first of the two-hole versions. Then we met an engineer that was
living and working in Ivrea that had experience in
manufacturing stuff. He was actually helping me a lot when, whenever the school wanted to manufacture
something with electronics. I would ask this, Gianluca Martino
is his name, I would ask Gianluca to help me do that. So I said, well, you know, can we
manufacture 200 of these pre-made? That we can just, you know,
sell to people? And then me and David managed
to convince both Ivrea and the school in Marma to
buy 50 each. So 100 were sold and then we said, you know,
let’s see if we can sell the other 100. You know, who cares? >> What, on a website or something? >> Well, we started to actually sell them
like this, like in this, by hand, by sort of really like saying okay, I’m going to run a workshop
in this place, I need 20 boards and we would just sell them to
people at the moment. The platform was unknown, it was not really proven, we were
at the beginning. Luckily we did some public
demonstrations of how you can do with this,
and people understood. So some people in different communities
started to put out the word that there was this Arduino thing
that was very promising. So we got people. We organized a
workshop at the end of 2005 in London, which was the first workshop where really
we put an ad and people paid and came. I think there were a number of events
that lined up that created, kind of fueled, this kind
of viral aspect. So, obviously, first of all, we had a
friend that was teaching these kind of topics in the U.S.
at NYU in a school called ITP. And he had a much bigger
number of students. He had something like 120 students. And so, we met him one summer
in Italy, doing a work, a project together and we
showed him Arduino, he started to play with it, he thought, okay, I like this. We can go
somewhere with this thing. So he brought back a few prototypes, we
shipped him a few more boards. And he started to use it with some of the
second-year students. And then at some point in 2006, I think, the
platform started to work properly. You could do good projects with it. And so the first-year students they saw
what the second-year students were doing and they said well you know we
want that Arduino ourselves. So I would say that generated, that kind of
gave us 120 power users. People who make beautiful projects
and designers of these features, that tend to take their projects and document
them very nicely put them online because
it’s their portfolio. Well with Arduino the idea is that you
download a file, you plug the board, okay back in the days you had
to install a few drivers. But then, you know, in the space of a hour
or something you were working. >> You got a blinking LED. >> Yeah, the blinking LED was
the hello world. The blinking LED is the hello world
of physical computing. So yeah, I think this viral aspect also
coupled with the fact that we asked SparkFun Electronics,
their online store was again beginning to become
very successful. So we asked Nathan to carry Arduino, you know, and he sort of graciously
accepted to do that. And so we, he kind of fueled our
growth in the U.S. Then me and David Cuartielles spent
many, a number of years traveling around the world, but mostly in
Europe at the beginning, doing workshops. And we, you know, sometimes for free. You know, just going somewhere and, you
know, sleeping in a >> Couch

Whatever we could sleep. Yeah, and then run workshops and that obviously kind of fueled
that kind of aspect. But then it was a lot of people making
projects, documenting them, putting them online and then sharing information about how they
built the product. >> Where do you think this thing is
going to go and what, what, what are your, some of your dreams of how it
could sort of change our world >> [LAUGH]
in powerful ways?. >> Well, in a way I think there’s a
wider, wider discussion about empowering people to be
creative with technology. So because obviously nowadays
the world that’s around us is made a lot of digital technology. And there is an, there is a trend that I’m
not particularly happy with where people just buy devices and they
just use the devices, but they are not aware of how you program, how you design,
you build things with the device. So, you know, for me the iPad sometimes is
the TV set of the 21st Century, you know. Obviously at home I have an iPad
and I use it for a TV, because you’re browsing the Web, you’re watching TV, you’re maybe
listening to music. Yeah, you can create with the iPad with
certain applications, but it’s not something’s that kind of makes you
want to program the device to do more. And, and I think it’s important,
especially for kids to, for them to understand that the world we live in,
now especially if you look at this room, this is a building that was
made, designed by human beings, built by human beings, every single bit was
designed and built by a human being. So clearly, if you know how to design and build things, you can affect the world
that’s around you. If you are not able to participate in this,
in the world of creation in the digital space, you’re left out. Somebody else is going to
design your world. At some point, you know, if there’s no
innovation, if there is no sort of renovation, in a way, inside the
marketplace, then one company decides that that’s the way you do a
certain thing, and that becomes the only answer to a certain question and
nobody starts to debate that. Or, you know in a way I think it’s
important to be masters of the technology. [SOUND] [MUSIC]

Video: Office Hours: Seoul Korea

Summary of Internet History and Security Office Hours in Seoul, Korea:

Student Testimonials:

  • Nikolay Ketchoff (Russia, LG Electronics):
    • First online class, enjoyed the community and Dr. Chuck’s inspiration.
    • Learned basic internet knowledge in a fun way.
    • Recommendation: add online games or learning activities based on the material.
    • Also enjoys TED Talks for self-education and found inspiration from Shimon Schocken’s talk on online games for learning.
    • Has two Master’s degrees: Computer Science (Russia) and Electrical Engineering (Korea).
  • Julie (Korea):
    • First course to earn a certificate, motivated to study computer science next year.
    • Course was perfect: free, hands-on, sparked interest in computer networks.
    • Planning to study computer science in Virginia.
    • Has degrees in physics and biology but shifting towards computer science and programming.
  • Choongil Kim (Chicago, working in Korea):
    • Enjoyed the course despite non-computer science background (aerospace engineering and IT).
    • Particularly liked the history aspect.
    • Looking forward to Dr. Chuck’s next class.
    • Has Master’s, PhD, and post-doctorate degrees from University of Michigan (Dr. Chuck’s alma mater).

Overall:

  • Students enjoyed the course and found it valuable for learning about internet history and security.
  • Dr. Chuck’s teaching style and the online community atmosphere were appreciated.
  • Suggestions for improvement include more interactive learning activities like online games.

Bonus:

  • Office hours took place in Seoul, Korea, highlighting the global reach of online courses.

Hello, this is Dr. Chuck here and
I’m coming to you right now in the continuing saga of
Internet History Technology and Security. I’m coming to you right now from Seoul,
Korea, and we are having office hours here in Seoul,
Korea. And I’d like you to meet some
of your fellow students. >> Hello, my name is Nikolay Ketchoff,
I am from Russia but I am working here in Korea for
LG Electronics. And I took this Internet History and
Security class, and they are this vicious certificate. Actually it was my first online class,
and I really enjoyed it, because it involved me in this
community of online courses. And Dr.
Chuck was really inspiring person for me, and it really helped me to realize
how these online courses worked. And also learn basic knowledge
in fun way about the Internet. I think this course was really great,
and these online spirit courses about to learn not to get,
not to be stressed by grades. And what I just want to
add more to this course, kind of recommendation to add
more learning activities. Maybe some kind of online games based on
this material, or something like that. Actually, what I also
enjoy in the Internet, I learn, I watch TED very often. And recently I watched this
talk from Shimon Schocken. So he also talked about self-education,
self-learning, and about his online courses, and
that I got idea about online games. For learning, so
have fun and learn online. >> Did you mention what
your degrees were in? >> I had two master degrees,
one in Computer Science in Russia and one in Electrical Engineering in Korea. >> Good, thank you. >> Yeah, thank you very much for
this class. >> What’s your name? >> My name is Julie. And I’m from Korea, so this is actually
my first course that I got certificate, and I am going to study
computer science for next year. So this course is perfect for
me because it’s free, but also it gives a me, kind of more
hands up on a computer network. And I will continue to study
about computer science and I’m actually pretty much interested
in computer network as well. Well, I have a degree in physics and
biology, but I got pretty much more interested in
computer science and programming. So, thank you for this whole lecture and I hope you enjoy every lectures of Dr.
Chuck in Coursera. >> Thank you. >> Thank you. >> Hi, my name is Choongil Kim. And I’m actually from Chicago and
I’m working in Korea right now. I really enjoyed the course, well actually
my background is different from computer science, I’m an aerospace background,
but worked in the IT industry. So this was the first Internet or any
type of computer science course I took. And I really enjoyed it and I actually
enjoyed the history part of it a lot. So thank you very much and we’re looking
forward to see next class from Dr. Chuck. >> You failed to mention where
you got your degrees from. >> Oh yeah, code blue. >> Tell us where you
got your degrees from. >> I got my degree from
University of Michigan, the best school in the world, where Dr.
Chuck’s also a professor at. And airspace engineering, so. >> And was that masters, PhD? >> Masters and PhD, and
even post-doctorate. >> Julie, Julie,
where did you get your degree at? >> I got my degree in South Korea,
Dong Uk University. >> Okay.

Yeah, and well I’m going to Virginia
to study computer science. >> Great, so
are you gonna actually go to Virginia and >> This December, yeah. >> And so you’re preparing in a sense
to sort of spend some time in Virginia. >> Yep.
Work on your master’s degree. >> Yep. That’s right.
Outstanding. Okay, back to me. Flip. So there you have it. Zoom out a little bit, zoom out. So there you have it. Here we have wonderful office
hours here in Seoul, Korea and now we’re gonna go all take some
pictures so see you on the Net.