Skip to content
Home » University of Michigan » Python for Everybody Specialization » Programming for Everybody (Getting Started with Python) » Week 4: Chapter Two: Variables and Expressions

Week 4: Chapter Two: Variables and Expressions

In this chapter we cover how a program uses the computer’s memory to store, retrieve and calculate information.


Lecture materials


Video: 2.1 – Expressions

Chapter 2 Summary: Building Blocks of Python Programs

This chapter delves deeper into the fundamental elements of Python, focusing on:

1. Constants:

  • Familiar types like numbers and strings used to represent fixed values.

2. Variables:

  • Named storage locations for data that can change during program execution.
  • Naming guidelines discussed, emphasizing clarity and avoiding confusingly similar names.
  • Mnemonic variable names encouraged for easier code comprehension by humans, though not essential for Python itself.

3. Assignment Statements:

  • Distinguished from mathematical equations. The equal sign acts as an arrow, assigning the evaluated right-hand side expression to the variable on the left.
  • Variables can appear on both sides, with the right-hand side being calculated first and then assigned to the left-hand side, effectively overwriting its previous value.

4. Expressions:

  • More details on expressions coming up in the next section.

Overall:

The chapter highlights the importance of choosing informative variable names for program readability and emphasizes the distinction between assignment statements and mathematical equations.

Hello, and welcome back to Chapter 2. In this we’re going to dive a little
more in depth on the atoms, the nuggets,
the little pieces that make up Python. And then we’re going to work though
our first real program that has a sort of beginning, middle, and end. So, here we go. A big part of any programming
language is the syntax for constants. The nice thing about this
it’s kind of instinctive. So, like a 123 or 98.6, numbers both
integer and floating point numbers. We’ve been using this on calculators. They make a lot of sense to us. The kind of constants that are a little
bit different are things like string constants. So “Hello world” is a string constant. We use that so that our program can say nice things
to people that are using our program. And so, we call them constants
because they don’t change but it’s kind of obvious, constants. It’s just a piece of the language,
so that’s a constant. What else? Variables and reserved words. So the other thing other than
constants are reserved words. And as I said in a earlier lecture,
these are like dog language. Blah, blah, blah, blah, class. Blah, blah, blah, del. Blah, blah, blah, else. Blah, blah, blah, lambda. So these are words that when
you say them to Python, Python expects them to mean exactly
what Python wants you to mean. Now, why is this special? It’s actually kind of instinctive. It just
means don’t use these for other things. Don’t name functions, don’t name classes,
don’t name variables. Places where you get choices to use words. Don’t use these words. And
most of them aren’t too big of a problem. I don’t know, maybe break or
in, or from, maybe. Some of these you might naturally use. Most of them are kind of weird enough that
you’re probably not going to use them as variable names. And so
the third atom basically is variables. And you get to pick the variable names. And it’s a little weird that you
get to pick variable names, but you’ll get used to it. And so variable names are places where
you’re asking Python to allocate a bit of memory and stick something
in it and you’re choosing the label. And so if we take a look at this. When we have this assignment statement, and remember that assignment statements
always have a direction, right? Think of these equal signs
as having an arrow on them. In some languages, I saw a language that
uses kind of an arrow that uses a less than and a dash as the assignment. I went, that’s how it should be because equal confuses us. Because equal means something different in
mathematics than it does in Python or other programming languages. So look at this very first statement. What we’re really saying is,
it’s a pretty complex statement. After a while, you’ll just use it. Python, find us a spare piece
of memory somewhere and give it a label of x, and put 12.2 in it. And remember that,
remember all that stuff. That’s one of things that Python does for
us, it remembers stuff. Then we go to the second statement. It says oh, hey Python, find some spare
memory that you got laying around, label it y and put 14 into that, okay? And so that’s how these things work and
you chose x and you chose y. Now if we keep on going in this code, and now we have another line and
we say oh, hey, x, wait a sec. I already told you about x,
x already exists so don’t go out and grab any new memory, but stick 100 in that. So 100 goes in and
it wipes out the old value. So, that’s what happens. When this sequence starts,
this happens first, second, third. And so
the third thing is the last thing and so x ends up with a residual
value of 100 in it. So that’s kind of variables and
assignment statements. You have some naming rules. You can start variable names with letters
or underscores, although we avoid underscores because Python tends to use
underscores for its own internal purposes. And the rest of it can be letters,
numbers, and underscores. And it’s case sensitive. But we don’t want you to depend on that. So, spam all lowercase,
Spam with one uppercase, and SPAM. These all are different variable names but you’re not doing anybody any favor
if you think that’s being clever. We tend to sometimes use uppercase to
signal things, which we’ll talk about later, but we tend to use mostly lowercase. Some applications use what’s
called camel case, which is a mix. But you tend not to depend on
the fact that these are unique because you really are misleading
the person who’s reading your code. But we have some good ones, spam,
eggs, spam 23, numbers are fine. It’s fine to start with a underscore. It’s bad to start with a number. It is bad to start with a pound sign,
although that turns into a comment, and you can’t use characters other than
letters and numbers in the variable. And so those are all good variable names. Now we lead these things into
sentences or lines. And so these things. This is just another sequence of code, and it shows how you can also use
the variable on the right-hand side. So put 2 in some memory and label it x. Pull that 2 back out and then add 2 to it. So this little thing here becomes 4. And then stick 4 into x. And then this is a print function. And the way functions work is
they are the name of a function, followed by a parenthesis,
followed by another parenthesis. And then you can print something,
what you want to print. And so, this causes on some
output 4 to come out. So, print is the function that
you call to cause output. Now I emphasize that one of the key
things about variable names is that you get to name them. And we have a technique called mnemonic.
I think I pronounced that right. And the idea is that when
you choose a variable name, you should choose a variable
name to be sensible and Python doesn’t care whether you choose
mnemonic variable names or not. And the name that you choose for a variable does not communicate any
additional information to Python, okay? So when you’re a beginning student, sometimes if you use variable names
that are too good it’s confusing. So you’ll notice as I write, especially in
these first two chapters, some of my code uses really dumb variable names and
some of them uses really clever ones. So I go back and forth to emphasize to you
that the name of the variable as long it’s consistent within a program doesn’t
matter, and Python is perfectly happy. So here is a little code. It’s four lines of code. And start at the top, run this line and
that says find a little piece of memory and label it that thing and
stick 35 in it. Find a little piece of memory and
label it that thing, stick 12 in it. Pull that first thing out and
pull the second thing out, multiply them together, and
put them yet into a third variable. If you look at these things really
closely, they’re all unique and distinct, and you do have to look at them very closely.
Then you print the third thing out. And Python loves this code. Python thinks great. I don’t know why you picked those variables,
I do not care. All I care is that they’re unique. Python really has no opinion
about these variables. But if you hand this code to a friend and
then you say, what is this code doing there? They’re like, why did you pick
such insane variables? because I have to stare at it and like,
the difference between like these two things is just the letter z and
the letter p. So this one we’re pulling
the p guy out and this time we’re pulling the z guy out,
right? And these two just have a difference
of those letters, I think. I mean, you could do it. Python loves this stuff. To Python this is perfectly
understandable code. To human beings it is not
perfectly understandable code. So like people aren’t going to like you,
but Python is going to be very, very happy. I can’t draw a happy snake,
otherwise I would draw a happy snake. So, this is tacky, bad, not friendly. So, let’s make it a little more friendly. You could choose variable names. To those, Python looks at these two
things as like, those are the same. They’re totally the same,
Python doesn’t care. But now we can look at it and go,
I see. The first variables is a and we’re putting that a thing there and
the second variables is b. We’re putting the b thing there. And then we’re
multiplying them and going to put them in a c thing and then we’re printing the c thing out. That’s pretty nice. So this is a little better, right? At least we can parse it and read it and
understand what the code is going to do without having to check to see if these
two characters are the same or different. So that’s better but
it’s not mnemonic, okay? Mnemonic means that we choose
a variable name that makes sense for what we’re using it for. Again, the variable name and Python looks
at all these three things as the same. All Python cares is that this
matches this, this matches that and that matches this. But, humans are much happier. Humans are much happier. Now, we understand mentally that
the first variable 35 was the hours. The second was the rate per hours and then
we computed a pay and we printed it out. So this is really understandable. The problem is for beginning programmers,
it sometimes is too understandable, right? It’s too understandable. Right? Huh? Python knows about payroll? Because if I name a variable hours, shouldn’t Python know
that that means hours? And if I name a variable pay does that
mean that Python knows about this? And the answer is, no. Python treats all these three as equal. Python doesn’t look at the name
of your variables and think, hey, you just had a bug, right? So what if, for example, I rewrote this
code and I said hours times hours. And it’s like wouldn’t Python
say hey that doesn’t make sense. Why would you even multiply it
in a payroll calculation? Why would you multiply hours times hours? And the answer is, Python
will happily do it because it’s not looking at those words. But a human being who’s trying to
understand what your code is or trying to help you, when you’re
writing code debug your code, will be very thankful that
you chose good names. And now I can look at your code, and if I
see you say pay equals hours times hours, like, why did you multiply
hours times hours? Didn’t you really mean to
multiply hours times rate? So mnemonic variables are only for
humans. We will later see things that will
confuse you when I name one variable friend and another one friends. And you’ll be like, so
Python understands plurals? And the answer is no, Python
doesn’t understand plurals, okay. It’s really helpful to read stuff, so that
when something has more than one thing in it, you might maybe use a variable
that’s got a plural in it. So, okay, enough about that. I hope I made my point. These are all the same to Python, but human beings certainly prefer
the second or the third. And so, but be careful. And after Chapter 10,
you’ll start using mnemonic variables and it won’t be a problem. But in the first few chapters,
you have to worry about it. So as I mentioned, assignment statements
basically are not like mathematics. Equal sign means equality. Assignment statements means arrow. And the key thing is you can almost think
of this as like there’s a little wall there and it completely
computes this expression. This is an expression,
on the right-hand side, gets that down to a single variable and
then writes it into the memory location. And that’s why it’s possible to have
the same variable on both sides because this side happens first,
ignoring this side. And then once this side is done, then it
actually puts it into that other side. And so, if, for example, x before
the statement started, had a 0.6 in it. It like firewalls this part off, and it computes this part here by
pulling the 0.6, the old value of x, doing the computation, running through
the things, getting the new value. And then after it’s got that new value,
then, and only then, does it store the 0.936 into x and that
overwrites the 0.6 that was in x, okay? And so one side finishes, produces
a result, and then it can overwrite. It doesn’t mean you have to put
the variable on both sides. But it’s why you can put it. So sometimes we’ll say
something like x = x + 1. And that’s our way of adding 1 to x. And that’s because whatever x is, maybe
x is 6 or something, this becomes a 7. And then the 7 goes into x and
then it overwrites it to the 7. We call this increment. We’ll see this soon, okay? But that’s why you can put the same thing. Now in mathematics, x = x + 1
makes absolutely no sense one but in programming, it is one of
the more common things that we do. Okay, so that gets us through variables and
constants and now we’re going to talk a little bit
more in detail about expressions.

Video: 2.2 – Expressions Part 2

Chapter 2 Summary: Building Blocks of Python Programs (Continued)

Expressions:

  • More operators introduced: addition, multiplication, division, remainder, and power.
  • Order of evaluation follows mathematical conventions: parentheses, exponents, multiplication/division (left to right), addition/subtraction (left to right).
  • Parentheses can be used to override default order.

Data Types:

  • Python distinguishes between integers, floating-point numbers, and strings.
  • The type() function reveals the type of a variable or constant.
  • Conversion functions like int() and float() allow changing data types.

Integer Division:

  • Python 3 treats integer division differently than Python 2, resulting in floating-point values for non-exact divisions.

String Conversions:

  • Strings can be converted to integers or floats if they contain valid numerical representations.
  • Non-numerical strings cause errors when converted.

Input Function:

  • The input() function reads user input from the keyboard and stores it as a string in a variable.
  • User input can be combined with other strings using the + operator.

Next:

  • Creating a first program with practical application.

So welcome back. Now, we’re going to continue on the
right-hand side of assignment statements and talk a little bit more
about some complexity about what you can do with these expressions. So, all programming languages
have various operators where you say x+1 or x-1 or something like that. These operators historically come
back to come from the kind of characters that were on computers
keyboards in the 1960s, literally. These things called Teletypes came
from the end of World War II, and they had a certain set of characters. And we were going kind of from
a mathematical character set, where multiplication is a big cross or
a dot in the middle and exponentiation is raising
a little tiny number above it. And we just couldn’t represent those on
these really rudimentary key punches or rudimentary terminals. So we had to map mathematical formulas and
functions into what could be done. And so those keyboards from 40 years ago,
50 years ago, they had a plus on it. So plus is a plus, they had a minus on it. But multiplication, which is normally
cross, is star. And division, which you can’t put things on top of one another,
so you just made a slash for division. And raising to the power is a double star. Now, the remainder operator is something
that’s not typically on calculators, but it’s really important for computers and
we’ll take a look at this. So, the addition operator,
pretty straightforward. I’ve kind of been using that without even
talking about it, the multiplication, and the division. So, this is 5,280 divided by 1,000,
which gives me 5.28. But the one that’s probably the most
interesting is this modulo, or remainder, operation. And so,
the way the remainder operation works is, in particular if this is an integer,
is it does the division. So it’s almost like a division,
j divided by 5, but instead of giving the quotient, this is
the quotient, it gives the remainder. So, 5 divided 23 is 4 remainder 3. The 3 is what you get back. Now you might ask yourself,
why is this useful? So one of the ways to make this useful
is to pick a large random number and then use the modulo operator,
the remainder operator, with 52. And then you end up with a number between
0 and 51, and then you can pick a card. So you can take a random number,
but you modulo at 52 and now you can have a random
number that is of card. Or if you want to roll a dice,
you’d make a big, random number and you’d take it modulo 6 and
then it tells you what side of the dice. So, like games and stuff. There’s other situations where you
can do even and odd calculations. Like is this an odd number
an even number? Divide it by 2 and see what the remainder is. And so,
this whole notion of the modulo operator, it’s really useful in some situations. And so, that’s why we obsess
about it a little bit. The power operator, this is like
4 times 4 times 4, which is 64. So those are the numeric expressions. Now these also have
an order of evaluation, and the way it works is in mathematics,
there’s order of evaluation. There are some operators that are more
powerful than other operators. And you can always, if you’re clever,
just put parentheses in, and most programmers always
put parentheses in. So if I was writing this line of code, and
I want it to be friendly to you so that you could read it more easily, I would
simply put the parentheses in for you. So I’d say 5 to the sixth
power goes first. Then this 4 divided by that goes next. Then this 2 times 3 goes next, and then we evaluate the rest of
these things left to right. So I just added the parentheses
that are the same. This is exactly the same as what it
would be without the parentheses, because this happens first. This part here happens second,
this happens third, and then all this other stuff happens fourth. So there’s an order, but we’re
going to teach you what the order is, if you weren’t going to use parentheses. So the rule is,
parentheses override everything. Exponentiation is the most powerful,
multiplication and division and remainder are equal. They’re the next most powerful. And addition
and subtraction. And then when in doubt, you just go left to right. So if there’s a bunch of additions,
you just go left to right. If there’s an addition and
subtractions in a bunch of stuff, you go left to right, okay? So this is a classic exam question
on computer science homework that you’d just say, okay,
what does this evaluate to? Now of course, if you have Python, you just type it in and
it tells you what the answer is. So the way I used to do these, back in
the day when I was doing these homeworks, because I would write the expression
down on a piece of paper. And then I would look through it and I would figure out what the first thing
was and I’d be very careful about this. I’m like, okay,
exponentiation happens first. So I’ll do the 3 to
the third power which is 8. And then I’ll rewrite the whole thing,
1 + 8 divided by 4 times 5. And then I would forget about this one,
and I’d look here, and go, okay, what’s the first thing here? Well, 8 divided by 4 is
the first thing there. So, then I’d be like, 8 divided by 4,
well, that gives us 2. In this case, it gives us 2.0. And then I’d have 1 + 2.0 times 5. And I look, and that’s the next one, so
that actually ends up being 10.0, and that ends up being 11.0. And that’s why this prints out 11.0. And so if there are no parentheses,
you can figure out. Another kind of exam question is to
ask what the parentheses would be. So the exponentiation happens first,
the division happens second, and then actually you put another parentheses,
because that result is multiplied by 5. And so that’s another way to kind of
answer the same question is say put the parentheses in where they belong. Like I said, parentheses first, power
second, multiplication third, addition, and then left to right. So when you’ve got nothing but addition and
subtraction, you go left to right. When you’ve got nothing but multiplication
and division, you go left to right. Start with the leftmost one. Sometimes it doesn’t matter. In addition and subtraction, it generally
doesn’t matter, but in multiplication and division, it can matter, left to right. Okay, so
we’ve been talking about variables, we’ve been talking about constants, and
we’ve been talking about expressions. But we also have constants that
are integers, we have constants that are floating point numbers, and
we have constants that are strings. And we can manipulate these. And Python carefully tracks not only
what the value in a variable is but what kind of a value it is. So is it a string, is it an integer,
is it a flowing point? And sometimes this makes a difference. And here’s a little example code. We have this plus operator. And the plus operator is looking
at its two operands, 1 and 4. It’s like, oh, those are integers. I know what to do with integers. That means addition. And so, it adds this to be 5 and
then sticks it into ddd and out comes 5. On the other hand, we can actually use the
same plus operator concatenating strings because the plus operator
looks to its left, looks to its right, says,
whoa, those are strings. And I know what you mean. I think you mean to concatenate this. And so we end up with, hello, the space
is very carefully constructed right there because the plus doesn’t add a space. So this ends up being hello space there,
and that little space is the space here. And so Python knows, in this example,
these are all constants, but it knows type of constants, and
it knows the type of variables. And it can do very different things.
And it can blow up and be unhappy, as we’ll soon see,
based on the type of things. So here we have an example
of something that’s unhappy. So I have now concatenated hello and
there, and then Python’s perfectly happy to do that,
and then I stick that in eee. And now I say I want to add 1 to it, and
it looks to its left, looks to its right, this is a string and this is an integer. And Python says,
I don’t know how to do that. Python could know how to do it, but
it’s chosen now to know how to do that. And so you get the dreaded traceback,
and traceback is like syntax error. It’s not Python telling you that you’re
a bad programmer or that you’re never going to be a programmer or that you’re
completely unsuitable for a programmer. What Python is saying is I,
Python, am lost. You told me to do something
I don’t know how to do. You need to go remember what it is
that I’m capable of doing as Python. Please come back and fix it. It also means that the program stops. Meaning that if you’re in a multi-line
script and you’re doing a bunch of stuff and there’s a traceback here,
the code after that quits, okay? And that’s because you’ve hit
this line that Python is lost and Python is loathe to continue. Now we’ll see in a bit that you’ll be
able to force it to continue if you want. But because you said something
that Python didn’t understand, it just quits at that point. And traceback, line 1 in this case, tells
you where it is that this thing blew up. And so this looks like nasty gibberish but
after a while, it won’t take you long at all to just
relax, look for the word traceback. That means Python quit somewhere. It tells you where. And then you look a little bit farther and
it tells you what’s wrong. TypeError, it’s unhappy with the type, and
it’s still referring up to this line of code. It says, I can’t convert integer
objects to string implicitly. So it’s like you have told it to do
something combining a string and an integer. And Python is like, I am lost, but
I’m giving you as much clue as to how I got lost, what got me lost,
where I got lost. I got lost, where I got lost, and
what caused me to get lost, and Python is trying as hard as it can to
clue you in to what’s going wrong. So, don’t look at this as like bad. Look at this as like, oh. I have not quite communicated to
Python the way I want to communicate. There’s a way to solve this,
there’s a way to do something here, but. So if we take Python and we think about
Python and say, hey, you’re so picky and you blow up if I do the least
little mistake on types. Help me out here. And so it turns out that Python has
a built-in function called type. So again, it’s type with parentheses, function
calls have parentheses on them, and we pass something in. And we’re like, hey Python, tell me
what the type of the variable eee is and Python prints out, oh, it’s a string. What is the type of the constant ‘hello’?
That’s a string. What is the type of the constant 1?
That would be an integer. And so Python keeps track of
the value of variables and constants, the value and the type of it. And so we have to kind of manipulate this and
be aware of this as we move forward. And so there are several types of
numbers that we’ve already been implicitly playing with. Like I said, you can give a variable to
type or you can give a constant to type. Variables and constants that don’t
have decimal places are integers, what are called integers. And variables that have decimal
places are called floating points. Even if this was a 98.0,
it would still be a floating point. As soon as you put the point there,
then that means it’s a floating point. They are represented
internally differently. Floating point numbers have a greater
range than integer numbers, but they’re not always as
precise as integer numbers. So floating point numbers have more range and less precision. So integers are perfect but
there’s a limit, like four billion or four trillion or something,
there’s a limit. Don’t worry too much about that. There is a choice that you make. You tend to use floating point numbers for
things like temperatures or speed. Turns out that you don’t use
floating point for money. You don’t use it for money,
even though in our first examples, we’ll be bad and we’ll use it for money. But, shh, don’t tell anybody that
I’m using floating point for money. If you want,
you can play with floating point and start finding some things
where money goes bad. Okay, there’s actually is a number of
different movie plots that come to have to do with computer programs that
use floating point for money. I think Office Space is one of
them that I particularly like, but there’s other ones as well. Why you don’t use floating point for
money, We kind of got off track on that,
but that’s okay. So we also have a set of built-in
functions that can convert from one type to another. There’s float, there’s int. And so float is a function and
it again has parentheses. We pass in 99. So as this expression is being evaluated,
it has to call float. It passes in 99, and
then what comes back is 99.0, which is a floating point
representation of the number 99. 99 and 99.0 are not the same. This is a floating point number. So when this addition happens,
it produces 199.0, so that is a floating point 199.0. By calling float, you are force converting
that to a floating point number. If we look at, like i is 42,
we ask what type it is, well, that i is an integer,
we can take a variable and pass it into the float function and
get back 42.0 and 42.0 comes back. And we say what kind of thing is an f? Well, f is a float. Right? So you can see how we’re manipulating
the type of things and controlling it. And any time we get a little confused,
we use the type function and say, hey, what’s going on here? Why don’t I understand
what’s going on here? Integer division is something that
actually changed between Python 2 and Python 3. It’s one of the bigger changes, the bigger
non-upwards-compatible changes between Python 2 and Python 3. And so this, I’m just reviewing. There are some things that
were different in Python 2. So 10 divided by 2,
even those are both integers, produces a floating point result. This kind of doesn’t make much difference
if these are evenly divisible. But if they’re not evenly divisible,
it makes a big difference. So 9 over 2 is 4.5. Think about if you’d put in 9
divided by 2 in a calculator, you wouldn’t expect it to say 4. And in Python 2, it said 4, it actually
truncated, it actually threw this bit away. But in Python 3, it just automatically
converts divisions to floating point and so it works out quite nice, okay? So 9 over 2 is 4.5. In Python 2, this used to be 4. And then 99 over 100 is 0.99,
exactly what you would expect in Python 3. In Python 2, that was a 0. Why? Because it truncated. It didn’t even round the numbers,
it chopped them off. So this was really quite
a silly artifact of Python 2. In Python 2, if you get stuck in Python 2,
you’d just use floating point numbers. And once either side of the division or
any other operation is a floating point number, then the calculation
is done in floating point. So, if it’s floating point input on either
side, then it’s floating point output. And this is what we used to have to do
kind of in Python 2 is force things to be floating if we were doing divisions. It wouldn’t hurt to do it in Python 3, but now integer division in Python 3
makes a lot more sense, thank heaven. Okay, string conversions. So if we read data,
which we’re going to see in a second, from the outside world
it comes in as strings. Whether we’re reading it from a network or
from a database, we tend to get these things as strings. And so what we’re showing here
is a string value that’s 123, but it’s not really 123, it’s three characters. It might as well be A, B, C, so 1, 2, 3,
are the first three characters. So, we take this string constant,
we put it in there and we say, okay, what kind of thing is in there. It’s a string. And if we try to add 1
to it as we saw before, you add a string and an integer and
Python gets really unhappy. Can’t convert an int object
to string implicitly. But what if we know that inside of this
string are actually digits, and we want to get an integer representation, or
a floating point representation of that? Well, in that case we can
call the int function, or the float function, passing in a string and
getting back an integer. So, this basically reads
these characters, the 1, 2, 3 and goes, that’s 123 and gives us back 123. And we say,
what kind of thing is in there? Well, now, in ival there’s an int. Now I’m being mnemonic here. I’m remembering that
this is an integer and this is a string, but Python doesn’t
care what I name my variables. Remember, Python never cares
about what I name my variables. So, if I start naming them conveniently,
don’t all of a sudden think that everything that starts with
the prefix i is an integer, and everything that starts with
the prefix s is a string. It’ll be a number of lectures
before I stop reminding you of that. So, ival ends up with an integer,
the number 123. And now we can indeed add 1 to it,
because it’s an integer and Python’s happy, and out comes a 124. So, this works pretty well unless
the string that in question has no digits. So, if there’s no digits,
it’s going to blow up, it’s like, whoa. Now, let’s read it. Traceback means, I quit. Where? Line 1, it’s always line 1 because
we’re in this interactive environment. But if you were in a script,
it would tell you what line it is. And then it says, invalid literal for
int() with base 10: ‘x’. And that’s like, okay, it’s not working very well. And so, you know, it’ll say, that’s an invalid letter. And, again, we’ll find ways to
cope with this in later lectures. Okay? Now,
how do we get data from the outside world? So, this is the keyboard, eventually we’ll
talk to networks and databases and files. But right now, we want to take
the keys from the keyboard, and get it into a variable. So, we have another function,
a special function, the input function. And when Python comes running in here,
it starts the input function, and the parameter to the input function
is what’s called a prompt. It prints out who are you,
and then it waits, and then we type into the keyboard,
Chuck, and then we hit the Enter key. And then it takes this string right here, and then it puts it in this
variable right here. It is a string. Even if I typed in 1, 2, 3, 4, it would
be the string 1, 2, 3, 4, not 1,234. Okay? And so, that is the way. And so, this program at this
point pauses until we type, and we hit the Enter key, and then it takes
that line of input including spaces, whatever I type, and
puts it in that variable. And then the program continues. And in this case, it just prints out welcome, comma, and
then the contents of the variable nam. And in this case, this space right here
that you see between welcome and Chuck, that is caused by this comma. We’ve mostly seen print being
printing one thing, but you can have as many things as you
want with commas in print, and every comma adds a space, and
so, it’s kind of friendly. If you wanted to you’d have to
concatenate these things together to eliminate that space,
but most commonly when you’re printing out a list of things you
probably want spaces between them. Okay? So that’s how we read input. Up next, we’re going to
combine all these things, and we’re going to make our very first program
that does actually something useful. So, we’ll see you in a bit.

Video: 2.3 – Expressions – Part 3

Chapter 3 Summary: Building Your First Python Program

Focus: Writing a complete program with input, processing, and output.

Problem: Converting European floor numbers to their equivalent US floor numbers (ground floor = 1 in US, 0 in Europe).

Solution: A three-line program:

  1. Read input floor number as a string (inp).
  2. Convert inp to an integer and add 1 (usf).
  3. Print “US Floor,” usf.

Key Points:

  • Comments explain program purpose and variables.
  • input() stores user input as a string.
  • int(inp) converts the string inp to an integer.
  • Mnemonic variable names like inp and usf improve readability.
  • This program demonstrates input, processing, and output.

Next: Chapter 4: Conditional execution with if and else statements.

So now, we’re going to combine everything in the previous lectures and we’re going to actually make our first program. So before we make this program, we need to talk a little bit about documentation. We talked about mnemonic variables as a friendly thing for humans. Another thing that’s a friendly thing in programs for humans, and you will tend to realize that the human that you’re being friendly to when you’re writing code and you’re doing it well, is yourself. So good variable names are going to help you a lot. They might help your teaching assistant but they’re also going to help you. Comments. Comments are a way for us to add text that’s ignored by Python to our programs. So it’s a great way to give a little idea what’s going on in code, maybe there’s a couple of lines coming up that are 10 lines long that’s a little complex and you want to say, “Oh, all this is really doing is reversing the order of these two things,” or who knows what. Or you might document who wrote the code and you can actually just take a line of code and put a pound sign in front of it instead of deleting the line of code. Sometimes, you do that for debugging. You add debugging code and then when you don’t want the debugging code, you just put a pound sign in case you want to take the pound sign out to turn the code back on. So I use it as a way to turning off and on lines of code. So here is a word frequency that we keep coming back to and what I’ve added here is I’ve added four comments. I’ve added comments that basically help us understand what’s going on, and remember I call these like paragraphs. Our first paragraph has human-readable code, human-readable text. Get the name of the file and open it. That’s what’s going to happen in the next two lines. These next five lines are count the word frequency, maybe I should say make a histogram. So make a histogram and you can just read this. So, again, don’t think of this as like the teacher’s telling you you’ve got to write comments. Think of this as like, “I’ll write comments so I remember what I was doing here. Why did I write this code?” So write the comments to help yourself out. Now, here, the last thing, we’re all done and we’re printing this stuff out, okay? So that’s comments, it’s an important part of documenting your code so that you can figure it out later. Again, the human who’s going to like you for doing all this stuff is you. All right. So this is you and you’re giving a gift to the future you, right? So you are writing comments so that the future you can read the comments. Because in a day or a week or a month, you won’t quite remember what you were doing so go ahead and write comments. But don’t write them because I said so. Write only the ones that you find useful and don’t do something like x equals 1, pound sign, put one in x. That’s silly, everyone can figure out what x equals 1 means. So you don’t put silly comments in just for silliness, you just put them in especially when you have to understand what’s going on here so that people don’t have to read quite so detailed. One of things they would do is they would read this and check to see if it really did what you said it was going to do to help you debug it, for example. So that’s comments. Documentation, very important. Okay. So now, we’re going to do our first programming code. Now, the pattern that’s going to happen in here is a pattern that I call and I was taught 25, 30, many years ago. Input processing and output are the essential things that computers do. They gather some input maybe from a file or from a web service. They do some work to it and then they produce something. In, work, out. The work is the hard part usually. So this program is our first program that demonstrates all three of those things; input, processing, and output. It’s a three line program with one comment. So the problem that this program is trying to solve, for those of you who have traveled in the US and traveled everywhere else, is that the ground floor in hotels in most of the world is the zero floor and the ground floor in United States is the one floor. So you might find yourself in a European elevator asking what is the equivalent United States floor to this floor that I’m sitting on. So if I’m on floor seven, what would be this floor if I was in the United States? That’s the problem we’re going to solve. Now, it’s probably not going to make us rich if we build an app for this but perhaps someone can get the European elevator converter app into some app store and maybe you will get wealthy after all. But for now it just is sufficient to teach us about a full blown program that does input, processing, and output. This is simple a program as I could make. So let’s take a look at it. A comment, convert elevator floors, that has nothing to with Python, has to do with you or me reading about this. Then input. Well, remember, input prints out the prompt and then pauses and waits. Then we type and then we type the Enter key, right? Then this zero, this is a string. The string ends up being input in the variable inp. Then it continues to the next line and it works on the right-hand side. We’re going to pull this string zero, we have to convert it to an integer, otherwise, we can’t add one to it. If we just inp plus one, we’d get a trace back. But we say int of inp, convert it to an integer. Now, if you mess this up and put Bob in, then this thing is going to blow up because int can’t convert Bob to an integer. But because we have a zero here, we’re okay. So then we add one to it and store that in usf, mnemonic variable name, United States floor, inp, the input we got from the user, I’m using good variable names here. So we store this in and so we got that becomes one and then we print out US Floor comma usf, remember the comma produces this little space down here. So we have our input, processing, and output in a way that builds us an application. Okay? Now, there’s lots of things, it will have to do. Most programs aren’t one line long and there’s a lot of work that we’re going to have to learn, but this gets us a start. So we’ve talked a lot of stuff. We talked about constants, we’ve talked about variables, we’ve talked about reserved words, we’ve talked about type, we talked about mnemonic variable names which are both wonderful and a little confusing at the same time, operators, operator precedence, focused a little bit on division where we talked about Python 2 versus Python 3, type conversion and comments and then writing an entire program. So up next, we’re going to start talking about conditional execution, using the if and the else and other of the reserved words. This is where some of the intelligence starts to seem to come into computers. So up next, conditional execution.

Assignment: Chapter 2


Graded App Item: Assignment 2.2

Code

Graded App Item: Assignment 2.3

Code

Video: Worked Exercise: 2.3

Chapter 4 Summary: Running Exercise 2.3

This video explains how to run Exercise 2.3 of the “Python for Everybody” course, which involves:

1. Setting Up:

  • Create a directory named ex_02_03 for Exercise 3.
  • Open a text editor like Atom and create a file named ex_02_03.py.

2. Writing the Code:

  • Use input statements to prompt for hours (xh) and rate (xr).
  • Convert xh and xr to floats using the float() function.
  • Calculate pay (xp) by multiplying xh and xr.
  • Print the message “Pay:” followed by xp.

3. Running the Code:

  • Open a terminal program and navigate to the ex_02_03 directory.
  • Run the script using python3 ex_02_03.py.
  • Enter the requested hours and rate values.
  • Verify that the calculated pay amount matches your expectations.

4. Troubleshooting:

  • If you encounter errors like “sequence of non-int of type str”, it means you haven’t converted the input strings to floats before multiplying.
  • Use the traceback information to identify the line and type of error.
  • Fix the errors in your code and rerun the script.

5. Using the Autograder:

  • You can also paste your code into the autograder to check it against test cases.
  • Ensure your code matches the autograder’s output format (e.g., message and formatting).

Benefits:

  • This exercise helps you practice writing and running Python code for basic calculation and input/output tasks.
  • It teaches you how to debug and fix errors in your code.
  • You can use the same approach to run other Python scripts in the future.

Remember:

  • Save your code regularly.
  • Use the autograder only after confirming your code works locally.
  • Don’t be afraid to experiment and learn from your mistakes.

Hello, and welcome to Python for
Everybody, my name’s Charles Severance. In this short video, I will be
explaining how to run exercise 2.3 where we prompt for some hours,
prompt for some rates, and multiply them together, and
print them out with a little pay message. And so, this is 2.3,
some of you will immediately want to go to the autograder, and sort
of do your homework in the autograder. I really rather you didn’t do that, unless
of course you’re doing this on an iPad, or an Android, or something where
you can’t install Python, but you have to realize that the autograder
isn’t forever. You can only go so far with the autograder, and eventually,
you have to write a real Python program. So, I’ll eventually show you
how to run this autograder, but I’m going to instead show you
how to run it in the terminal. So, I’m first going to go into my
Python for Everybody folder, and I’m going to make a new folder,
command Shift+N is what I just did there, ex_02_03, for Exercise 3, so
there’s exercise 3. And I’m also going to go into Atom, which is my
text editor, and see I have that folder. And so, I’m going to make a new file, and I will say print,
I’ll just say PY4E, oops, PY4E, and then I will say File,
Save As, and I want to make sure it’s in here,
and it’s going to be ex_02. I don’t like putting spaces in file names,
some operating systems can’t handle them, that’s why I’m using underscores here, so I would avoid using spaces in file names. So as soon as I give that a PY4E,
as soon as I give it a python suffix I’m there, and
so it shows up there in my desktop, and now I’m going to run the terminal
program, so that I can get there. So, cd Desktop/ cd py4e/
That’s the folder on my desktop, If I do an ls I see a couple folders and
a file, you can say ls -l and see a little more detail that these are folders, these
two are folders, and this one’s a file. So change directory cd ex_02_03, and so now I’m in that folder,
and if I do an ls -l, I see that file. I can also do an ls
without the -l, and see the file. And now I say
python3 ex_02_03.py, and it runs. And you’ll see me,
no matter how many times you watch me, you’ll see that the first thing that I do,
is get to the point where I know I’m in the right directory, and
I can run a little hello program, before I start coding.
I just don’t like being crazy, right? So now, I’m going to go back and take a look at my assignment, Enter Hours,
you’ve got a prompt for hours, ask for a number, Enter Rate, prompt for
rate, and then calculate Pay. So, there’s a couple of input statements
here, xh is my variable I’m going to choose, later I’ll choose more
effective variables, but for now I’m going to make them silly,
Enter Hours, colon, space. And then I’m going to copy, and
paste and call this xr for rate. When you’re doing this, you need to be very careful to, and so now I’m going to calculate xp times, which is xh * xr, and I’ll say print Pay. I don’t need to put a space because this
comma effectively creates a space, xp. And then I want to save that, and I’m
going to switch to my terminal program, clear my screen in my terminal program,
and I’m going type up arrow, because I already typed
python3 ex_02_03.py. So my hours, I’ll just start with
something really simple that I can calculate in my head, 10 and 5. Whoops, can’t multiply
sequence of non-int of, by sequence of non-int of type str. Here we have a traceback, and again I encourage you to realize
that these tracebacks are not personal attacks by Python on you,
even though they might be frustrating. And so the way to parse this
is start by saying line 3, something’s wrong at line 3, it’s
pretty good at knowing what line it is, or it’s either that line or
the line above it, and it’s something about multiplying.
What it’s really saying is I’m confused, I have to stop because I
cannot understand your instructions. So, the problem here of course
is that this is of type string. And so you can’t multiply
a string times a string. Okay, and so we can convert this
using a float, float, so that’s a function call now, we’re passing the
string xh in, and the value we get back is the floating point version of that,
and then, we call float for this as well. And so now I’ll save that,
always remember to save. I’m going to run it, and so
I’m going to run it my hours of 10, and my rate of 10, and it’s 100, and so
that looks pretty good, okay? So let’s go ahead and
try to run this in the autograder, and this is my idea, is you’ll take this and
you’ll copy it, and you’ll go back to the autograder now,
and just paste this in, okay? And so it says use 35 hours,
and rate of 2.75, so let’s check the code 35 hours, OK,
75, no 2.75. And so it’s running, and
it’s running, and it works, and of course, now I’ve got my grade. So this idea where you work here to
get your assignment done correctly, and then you run it in the autograder,
is the way I intend for you to do it, but
again if you can’t do it that way, it’s a great way to get started to just
write your code it the autograder. You can change your code in
the autograder, and then run it again. Of course, this is going to fail,
35, and 2.75. And of course you get a mismatch, and
now it’s angry at you, and the mismatch here, of course, is because
I print Howdy Pay and Pay, and it’s real picky about it, and
you think I’ve got the 96.25 right. Well, it doesn’t really care so
much about that. So, let me go ahead and fix this, and
run it so we leave on a successful note 35 hours, and
2.75 is the rate per hour, kind of a lower rate per hour,
and we’re getting successful. And of course that means that you
now have a grade on assignment 2.3, look at that, I got a grade on
assignment 2.3, unless of course, you’re running these in some
other environment, okay? Thank you so much, and
I hope that this has been useful to you.

Bonus: Chapter 2


Video: Interview: Pooja Sankar – Building Piazza

Summary of Piazza’s Founder Story:

Motivation: Founder, Pooja Sastra, felt isolated as a woman in STEM during her undergrad and wanted to help others feel connected.

Idea: Create an online platform for Q&A and discussion to simulate in-person learning but online.

Development:

  • Built the first prototype during her MBA at Stanford.
  • Initially focused on creating value for users rather than seeking growth or publicity.
  • Gradually grew from one class to hundreds across top universities.

Challenges:

  • Scaled the platform initially with minimal resources and a volunteer developer.
  • Balanced motherhood with entrepreneurship with support from family.

Key Takeaways:

  • Importance of empathy and understanding user needs for product success.
  • Value of focus and slow growth over chasing numbers.
  • Prioritizing self-care and mental well-being for sustained productivity.

Ending Note:

  • Sastra highlights the importance of places like the Stanford Dish for providing focus and inspiration.

[MUSIC] >> Piazza’s an online question-and-answer
platform that I built out of my own inspiration, based on my
experiences from my undergrad. So, I did my undergrad when a very few
women in computer science in India. Top engineering school, IIT. And I had actually studied in an all-girls
high school till college, did not know how to speak to boys, was told,
never allowed to speak to boys. So when I went to college,
I didn’t know how to speak to boys, and all my
classmates were boys. Studied by myself, felt very isolated. And really felt a frustration
at doing assignments by myself and trying to study for exams
by myself. And I came to America to do my masters in computer science at
Maryland College Park. Came out to Bay Area, California,
worked as a software engineer at Oracle, at Facebook,
at Cosmix. And when I went to Stanford Business School
for my MBA, I realized today with technology, actually laptops
and high-speed Internet, everywhere, many students end up sitting by
themselves in their dorm rooms. And that feeling of isolation is actually pretty common among many
young students today. So really, Piazza’s meant to simulate the
sort of real face-to-face discussion that I witnessed in my undergrad, but could not
partake in, because too shy. >> Did you start working on it when you
were working on your master’s degree? >> My MBA, yes. I you know, it, midway through my first year, I took an entrepreneurship
class at Stanford. And the one thing that entrepreneurs here
in Silicon Valley that who came to speak in our class, the one thing they said is think about an idea you’re
passionate about. And for me that idea was how can
I help students, particularly women studying kind of
science and engineering subjects, feel less isolated. So that summer between first and
second year of business school I moved in with my brother
and his family, worked out of their garage,
built the first prototype of Piazza. I had not done any web development
until then. So I picked up a book on Ruby on Rails. Had never written a line of HTML or CSS,
because all I knew was kind of serve, server
technology, C, C++. I knew how to use GDB, and so I picked up a book on Rails, and learnt it all
and built a site in ten days, and launched it to one class
that fall of 2009. That grew to three classes in
January of 2010, and about ten classes at Stanford in 2010 Fall. That suddenly grew to 65 classes
in Spring of 2011, and many of the professors,
I did not even know. So that was indicating to me that, you
know, something was working. And students were liking it, and
professors were liking it. So suddenly I contacted professors at
Berkeley, and MIT, and Princeton, and Harvard, and within a month, we had over 20,000 students at these
five schools using Piazza. >> And were you still sort of
doing this with you as the main developer, with 20,000 accounts [LAUGH] and you as the main developer? And like were you using a credit card to
paying for a server or two? >> It’s just, it’s barely maybe $50 to
$100 a month to host or not even so I did find one developer who
had a daytime job. to pay his bills and, you know, his
family’s bills, and he had some server space, so we just hosted on
whatever server space he had. And it was at this point that we went
ahead and raised a seed round of, you know, a little over a
million dollars with Sequoia Capitol. >> Do you kind of have any philosophy of
the right way to approach being an entrepreneur, and what
sort of what, what’s your sort of >> Yeah, I definitely lean towards
the slow. I truly believe in creating value first,
not getting caught up in numbers, In fact, February of 2010 it turned out
that the founder of TechCrunch was seated next to me
on a plane, and when he did ask me, you know, I’d love to
write an article about you, my first kind of knee-jerk
reaction was no, because I knew that would bring lots of
people to want to use Piazza. Piazza was very, very in its nascent stages of product
development, you know. And it was a good call, I think,
because that whole year of 2010 I didn’t care about numbers, I didn’t care about how many students or how
many professors. All I cared about was I had a
hand full of professors and students that I could sit with and
learn and watch and observe. Today I believe that I have
very deep empathy. And, you know I think it’s really
important to build a product that adds value, that comes from
often just staying very small, because you can isolate the
types of users you want whose use cases matches the sort of
use cases you built a product for. >> You became a mom in the middle
of that whole story. >> Mmm hmm >> Talk a little bit about about how that all works

Sure >> And came together. >> Yeah, so about five months ago
I had a baby son, Arjun, and I’m very fortunate that I live with my husband’s parents, we all
live together and they, you know his parents understand
that they really, I need their support to be able to run a company while being a mother. And both
are very important, I want to be a mother, I want to raise children and bring them, you know, just want to raise them.
At the same time. I really believe in the company
that I’ve built and the impact it’s making on students
and teachers and continue to, continue to do what I have been doing. So with their support, I would say
it’s been actually pretty easy. One thing I really like to do is actually
be in another place, by myself, so whether that’s working out, or
whether that’s going on a long walk, that allows me to pull myself away from
the weeds either for Piazza or for my son. There’s a dish that’s the Stanford dish,
right behind Stanford. I hear, I hear Steve Jobs used to go there
and a couple other great people who I derive a lot of inspiration
from, that they go there a lot. So I like to walk there
a few times a week. I found that that very first
summer in 2009 when I had to build a prototype and find the first
few professors to use Piazza. I remember I used to walk the dish five times a week, and I would
only work four to six hours, or maybe eight hours, but it
was never, and I had a successful product by
the end of the summer. And I had a class using Piazza and
I know the dish, walking the dish, brought me focus and that allowed to
be very productive with my time [MUSIC]

Video: Office Hours: Mountain View, CA

This clip shows the excitement of a record-breaking Python for Informatics office hours session.

Key points:

  • Dr. Chuck and TA Sue are hosting the session.
  • It has the largest group of students ever seen at their office hours.
  • Dr. Chuck captures a selfie with the crowd and adds “theme music” for dramatic effect.
  • The students applaud the achievement of having the biggest office hours group.

Overall, the clip conveys a sense of community, enthusiasm, and accomplishment for the Python for Informatics course.

He’s doing a selfie. >> Selfie. >> Yeah, selfie. So here we are at Mountain View,
California. I’m Dr. Chuck, of course. And-

I’m Sue. >> This is, so that’s Sue,
our intrepid lead TA that’s helped so much over the years of Internet
history and Python for infomatics. And we have by far the largest group
of students that we’ve ever had at office hours. So I’m just going to
kind of show you everybody. Yeah. [LAUGH] Yeah, I will add some-
[LAUGH] >> I will add some theme music. So that is the world’s record for
office hours that we’ve ever had so far. >> [APPLAUSE]
We could upload that right away. >> [LAUGH]