Let’s take it from the top. Alphabetically speaking, here are the first three keywords in Python:
Shocker! This pretty much has the same meaning as the English word and, aside from the all the Boolean logic stuff we discussed before. Bottom line: If you tell your program that it must have, let’s say, both a poncho and an umbrella before it takes some action, then it’ll take you very literally. Don’t expect it to do what you want without both of them. The code below uses and. Go ahead and run it your text editor. If that works, change the dog assignment to False and see what happens:
dog = True cat = True if dog and cat: print ("yep, you have a dog and a cat in your house")
The popular writer Stephen King has been known to pen books using the alias of Richard Bachman. Sometimes you’ll see this phrase: “Stephen King writing as Richard Bachman.” That’s pretty much the same way Python uses the word as. It creates aliases, especially for modules that you “import” into your code so you can use them without writing them from scratch.
Let’s take the example of the “turtle” module, which you can use it to draw pictures using, well, turtles. If you wanted to just use it, you could write “import turtle” to get started (we’ll talk more about import a little later ). But you could also give the turtle module an alias. Let’s say you want to give it the alias “slowOne” and then use the renamed “slowOne” module. Here’s how you might go about that.
import turtle as slowOne # allows us to use the turtles library wn = slowOne.Screen() # creates a graphics window alex = slowOne.Turtle() # creates a turtle named alex alex.forward(150) # tells alex to move forward by 150 units alex.left(90) # turns by 90 degrees alex.forward(75) # completes the second side of a rectangle
Feel free to play around with the module for a bit. For a tutorial on how to use it, I recommend the chapter “Python Turtle Graphics” in the interactive version of the book How to Think Like a Computer Scientist.
This handy, dandy keyword helps you discover whether or not you’ve written buggy code. You assert that something is true. If it is, nothing happens. No news is good news. If it’s not true, however, it gives you an “AssertionError.” What’s more, you can add your own verbiage to the assertion error. Run the following code in your text editor and you’ll see what I mean:
#this code uses "assert" and produces an AssertionError x = 100 assert x < 2, "the value of x is just too big, dude"
Featured image: Stephanie Lawton - https://www.flickr.com/photos/steph_lawton/7634622516/ https://en.wikipedia.org/wiki/Stephen_King#/media/File:Stephen_King_-_2011.jpg
2 thoughts on “The ABCs of Python: “and,” “as,” “assert” and Stephen King”