Python Week A

Welcome to the first homework for Python. It's more of a lesson so buckle up!

In the very first lesson, you learned how to print strings and math equations into the output window. Pretty nifty, eh? If you ever need a calculator that you can type fast into, just boot up the Python interpreter.

Let's expand upon that a bit: We're going to combine printing strings with printing answers to arithmetic questions.

If I try running the following line (you should do it too!):

print("2 plus 2 is " + 4)

I'll get an error. Huh, I thought that this would work.

Luckily the Python interpreter (the program that interprets and runs our commands) is a benevolent one and provides us with an error message, literally telling us verbatim what we did wrong. So what does it say?

TypeError: can only concatenate str (not "int") to str

Type error? What does that even mean?

In computer science there is this concept called "types".

Everything has a type. The string "2 plus 2 is " from above is a string type. The number 4 from above is an integer type. Even the print() function has a type! But we'll talk about that at a later time.

Anyways, let's go back to that error message:

TypeError: can only concatenate str (not "int") to str

The "str" refers to the string type and "int" refers to the integer type, so our error has something to do with those two types. If only I knew what this alien word "concatenate" meant!

Well, to concatenate basically means to combine strings. It even tells you in the book, but I'm just making sure.

So basically, the error message is telling us that strings can only concatenate with other strings and not with integers. To be even more basic, string no like integer, string only like other string. I think that's more your level.

So what do we do?

One solution is to "cast" our integer into a string, which basically forces it to change its type. We can do that by looking at our original line:

print("2 plus 2 is " + 4)

Wrap the 4 with the str() function, which converts things into strings:

print("2 plus 2 is " + str(4))

And now we're just concatenating two plane ol' strings, which Python shouldn't have a problem with. Run it just to make sure.

And we're done!

The thing is is that converting between types usually isn't a totally easy task. Python makes it easy in this case, but you'll learn about other cases in due time.