Python Lesson 4 – If Statements
[This is part of a series of posts on learning and teaching Python with my 10-year old son. Read the back story.]
Go back to Python Lesson 3 – Lists
Because pythonanywhere.com doesn’t play nicely with graphics programming we skipped Chapter 4 in the Python for Kids book and moved on to Chapter 5 entitled, “Asking Questions with If and Else”. For people who have done some programming before you know that If Statements are a common building block.
My son didn’t seem to have any trouble grasping If Statements and scooted through the exercises just fine. However, I had a couple hang ups and I’ll use this post to get them off my chest.
So far I’ve been very impressed with the simplicity and sensibility of Python. This chapter introduced me to two conventions that I don’t really care for. In Python you are expected to indent your code consistently to designate blocks of code relevant to an If Statement. It’s certainly good practice to indent consistently for readability but I think I would prefer some sort of “end if” designation for the same reason. Maybe this will be introduced further down the road (I’m not reading ahead) and maybe it’s because I’m more accustomed to seeing code blocks end with a character or set of characters. In any case to me it looks like the If Statement is incomplete when there’s no End If. The other thing I don’t like much is Python’s Elif abbreviation for Else If. I’m all for brevity but abbreviating a 6 character string with a 4 character string seems sort of unnecessarily fussy.
Here’s what an If Statement looks like in Visual Basic:
If count = 0 Then MsgBox("There are no items.") ElseIf count = 1 Then MsgBox("There is 1 item.") Else MsgBox("There are " & count & " items." End If
Here’s what the same If Statement looks like in Java:
if (count = 0) { System.out.print("There are no items."); } else if (count = 1) { System.out.print("There is 1 item."); { else { System.out.print("There are " + count + "items."); }
And, here’s what this If Statement looks like in Python:
if count = 0: print("There are no items.") elif count = 1: print("There is 1 item.") else print("There are " + count + "items.")
See how Python’s If Statement sort of leaves you hanging? I’d prefer an “end if” to bring things to a tidy resolution. I guess I’m just a guy who prefers closure. I also would rather read “else if” instead of “elif” which makes me think “Elf” and then I get a picture of Will Farrell dressed in a ridiculous elf costume in my head and it’s all downhill from there…
See, I just left you hanging, sort of like a Python If Statement….but I just couldn’t allow it so I wrote a final sentence to bring closure to this blog post. Ahh. Now I feel better.