Salvatore Lopiparo

Software Engineer

Super Simple Python #4 – Defining Simple Functions and Using The return Statement

One of the many cool things about Python is the really easy way to define functions. But before we can define any functions, we first need to define “function”! A function is a grouped bit of code that does some task. The print function in the last lesson is a function that outputs stuff to the console.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

Here’s how we define a function of our own:

>>> def greeting():
...     print('Hello World!')
...     

To define a function, we use the tag def followed by the name of our function. The code that the function performs comes after the line with the colon (:). All following lines must be indented by 4 spaces (if you’re using the PyCharm Console, you can press the Tab key instead).

Make sure you hit enter a couple of times until the “>>>” shows up again. The lines with “…” mean you are continuing a command on the next line, you should not type them. You’ve now defined a function! To use it, type:

>>> greeting()
Hello World!

We can also pass it an argument by adding it in the parentheses. This allows the function to get data from outside of itself:

>>> def greeting(name):
...     print("Hello " + name + "!")
...     
>>> greeting("Frank")
Hello Frank!

Most often you will want to have multi-line functions. At the beginning of each line after the function name, it must start with a 4 space indentation.

>>> def greeting(name):
...     print("Hello " + name + "!")  # Note the 4 spaces
...     print("How are you today?")  # 4 spaces here too!
...     
>>> greeting("Frank")
Hello Frank!
How are you today?

You will often need your function to have more than one variable available from outside. You can include more by separating them with commas. Remember that order matters!

>>> def greeting(first_name, last_name):
...     print("Hello " + first_name + " " + last_name + "!")
...     print("How are you today?")
...     
>>> greeting("Frank", "Morgan")
Hello Frank Morgan!
How are you today?

Most good functions have a return statement at the end. It does exactly that: returns what’s after the return to whatever called it. Like so:

>>> def adder(x, y):
...     new_number = x + y
...     return new_number
...     
>>> adder(2, 3)
5

The good thing about return statements is that they allow functions to put their result into a variable!

>>> eight = adder(3, 5)
>>> eight
8

A good function definition describes what the function does. Here’s our greeting function with a good description. We use 3 double-quotes in a row (which is just a string that can span more than one line) to describe the function.

def greeting(first_name, last_name):
    """Prints a greeting for the given first
    and last name."""
    print("Hello " + first_name + " " + last_name + "!")
    print("How are you today?")

Now the next person to look at this function won’t be confused about what it does!

Super Simple Python #3 – The print Statement

You don’t have to worry about filling your printer with reams of paper yet. That’s a different kind of printing than we’re talking about. With the print function, you can do lots of cool things! Like sending strings to the console output! Exciting AND useful!

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

>>> bob_string = 'Hi, my name is Bob.'
>>> print(bob_string)
Hi, my name is Bob.

It’s that simple. You may notice that it doesn’t have quotation marks around it in the output. The quotation marks are a side effect of not using the print statement.

>>> bob_string
'Hi, my name is Bob.'

Use the print function to display the value of something to the console (the interactive PyCharm Python Console, for example). Strings by themselves won’t print to the console inside of a function definition.

You can also print numbers!

>>> print(42)
42

You can even print print!!

>>> print(print)

Using print is the simplest way to get feedback from your program. Use it liberally. It’s your quickest way to figure out how your program is working.

Facebook Destroys a Gaming Platform

facebook-oculus

So in recent news, Facebook purchased Oculus, the people who make the VR headset called the “Rift”, for $2 billion. In so doing, Facebook has in effect destroyed a future gaming platform.

The Oculus Rift VR technology had a huge potential for creating amazingly immersive gaming experiences. Once Facebook puts its fingers all over the Rift, we will instead be given a partially immersive, ad-ridden, farmville-notification-driven experience filled with the avatars of your family.

Virtual reality will change from being an escapist’s dream to their anti-social nightmare. Get ready to awkwardly talk to the avatar of that one high school friend you haven’t talked to in 10 years, or walk to your aunt’s virtual farm to water her virtual carrots. “It looks like you’re about to fight a dragon, would you like to share this with your friends?”

No thanks. I will hope, for now, that Sony can keep away from the social game.

What do you think? Leave a comment!

Super Simple Python #2 – Intro to Strings

While it is quite fun to use strings to play with kittens, it’s even more fun to use strings to play with Python! (Although far less cute.) A string in programming speak is an ordered series of characters, which is a fancy way of saying “words”. Let’s play with some strings!

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

To write a string, take any set of characters and put either double or single quotation marks around it:

>>> 'hi'
'hi'
>>> "howdy"
'howdy'

To Python, there is no difference between using single quotes (') and double quotes (" or Shift+'), as long as you use the same one for that string. Nobody likes mismatched bookends. (Not sure that’s a good example, as nobody uses bookends to begin with.)

We can also assign strings to a variable, just like numbers!

>>> hi_string = 'hi'
>>> hi_string
'hi'

and even add them!

>>> hi_string + 'howdy'
'hihowdy'

Let’s add a space between those two:

>>> hi_string + ' ' + 'howdy'
'hi howdy'

We can even type whole sentences, punctuation and all:

>>> taunt = "Your mother was a hamster and your father smelt of elderberries!"
>>> taunt
'Your mother was a hamster and your father smelt of elderberries!'

If we need to use an apostrophe (also known as the single quotation mark, ') in the middle of our sentence, we can either use the double quotation marks:

>>> "It's a wonderful day in the neighborhood."
"It's a wonderful day in the neighborhood."

or we can escape the apostrophe with a backslash (\). This tells the Python interpreter to ignore the special character following it. In this example, we use It\'s:

>>> 'It\'s a wonderful day in the neighborhood.'
"It's a wonderful day in the neighborhood."

You can also include numbers inside your strings:

>>> box_message = "I have 3 boxes."
>>> box_message
'I have 3 boxes.'

You can’t, however, add a number to a string. First you must convert the number to a string using the str function.

>>> '1' + '1'  # Adding strings
'11'
>>> 1 + 1  # Adding numbers
2
>>> 'hello' + str(1)  # Adding numbers to strings
'hello1'

See? Just as fun as kittens!

Super Simple Python #1 – Doing Math and Assigning Variables

Wait, wait! Don’t groan yet! It’s really simple math! Like, pluses and minuses and stuff! No long division, and no integrating differential equations, I promise! That’s a later chapter!

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

Open up the PyCharm Python Console (see SSP#0). You’ll notice that the lines you type on start with “>>>”. That’s normal. You’ll also notice that I’ll start things I want you to type with “>>>”. That’s also normal. You should not, however, type extra “>>>”. That’s not normal. The line after the “>>>” is the output line. That’s also also normal. You’ll also notice that I say also too much. That’s also not normal.

Now some math! Type:

>>> 1 + 1
2

Yay! Math! See? Easy stuff. Now try:

>>> 1 - 1
0

And it works like that with all the numbers, including negatives!

>>> 3 + 5 - 10
-2
>>> 111 * 7777
863247

Now a variable! A variable is a name for a piece of data, like a number.

>>> bananas = 3

We call that “assigning 3 to bananas.” You may have noticed that it didn’t have any output. That’s because the number 3 went “into” the variable bananas. Now if we type:

>>> bananas
3

There’s our 3!

We can also do:

>>> apples = 10 - 6
>>> apples
4

There, we subtracted 6 from 10, then assigned that (4) to apples! It will always completely figure out the right side of the = before assigning the value (in this case 10 - 6).

You can also do math on variables that contain numbers:

>>> apples + 10
14
>>> apples  # Notice here how apples did not change!
4
>>> apples = apples + 10  # Now it will change, because we assigned it again!
>>> apples
14

In addition to adding numbers to variables, you can add variables to other variables:

>>> apples + apples
28
>>> apples
14
>>> fruits = bananas + apples
>>>fruits
17

Whew! Math is done. That wasn’t so bad, was it?

Questions or comments? Let me know below!

Super Simple Python #0 – Installing and Rules

I have always been meaning to flush out this Python tutorial, so here it is. It’ll be really easy, designed for someone who doesn’t know any programming. Also, it shouldn’t take more than about 5 minutes for each lesson! I don’t like long intros, so let’s start!

First, some ground rules.

  1. Type things yourself – Don’t just copy what I type and paste it into your own window. You won’t learn anything that way. They’ll be short, I promise.

  2. Ask questions – Please. Let me know if you don’t understand something. I’ll probably miss something that I take for granted but probably looks like voodoo to others. It’s not magic, I promise.

  3. Have fun – Programming is fun when you get the hang of it. I won’t post anything that I won’t laugh at myself*, I promise.

*and trust me, I laugh at myself all the time.

Install Python!

First things first: Go to http://www.python.org/download.

If you’re on Windows, download Python 3.3 Windows X86 MSI Installer. (We’re installing the 32-bit because there are a few libraries that do not support 64-bit.) Double click on the install file and use the default for everything (keep hitting Next, OK and Finish until the box goes away).

If you’re on a Mac, download the Python 3.3 Installer based on if you have a Puma or a Tabby. Double click (or whatever Mac people do) on the install file and use the default for everything.

If you’re on Linux, and you don’t know how to download Python, you need to set down your older sibling’s computer and go shout profanities on Modern Duty 2 (or whatever you kids play now-a-days). But if you’re insistent, it’s probably something like apt-get install python.

Install PyCharm!

PyCharm is a piece of software called an Integrated Development Environment or IDE. That’s fancy speak for “a feature-rich program to write code.” This step isn’t necessary, but is strongly suggested. Please download their Community Edition (it’s free). It will take us a minute to set up, but it will be worth it!

  1. After you install PyCharm and you get to the first configure window, choose whatever color scheme you like. (I like Darcula!)
  2. On the Welcome screen, choose “Configure”, then “Settings”.

  3. Find “Python Interpreter>Python Interpreters” on the left, then click the “+” on the right. Choose your Python 3.3 install listed, then click “OK” to go back to the Welcome screen.

  4. Click “Create New Project” and name it something like “super_simple_tutorial”.

  5. Finally, go to “Tools>Run Python Console…” on the menu bar.

This Python Console window will be your primary tool through most of the lessons. It will evaluate what you type on the line after the “>>>” and print it back to you below it. For example, type print("hello world") after the “>>>” and you will get something like this:

>>> print("hello world")
hello world

Congratulations! You can now program!

Unity 3D vs. UDK 3 vs. CryEngine

It has recently become a very competitive business to supply indie game developers with a good working toolset to develop games. The three major contenders are Unity3d, UDK 3, and CryEngine. All have their strengths and weaknesses.

Unity 3D

I have the most experience using Unity, and I quite like it. The built in features are customizable enough to quickly create gameplay (assuming you know some programming), but are structured enough to prevent you from hurting yourself too easily. This does of the downside in that you are a bit more restricted with what you can accomplish. You do not have access to the source code (without a lot of money), which means you’re stuck with their rendering structure and static objects. Not to mention that Unity falls short of the other two in terms of graphics quality by a lot. They have made quite a few improvements, but they have a long way to go.

UDK 3

I am specifically saying UDK 3 here because UDK 4 is on the horizon, and I don’t want it to be confused. UDK 3 is a very good engine. It’s relatively easy to use while being extremely powerful in what you can accomplish. Again, you do not have access to the source code, but communicating with C++ libraries using TCP connections is possible. It is not as easy to use as Unity (one of my teams issues with it turned into the phrase “Getting the Unreal out of the Unreal Development Kit”) as it was designed with an FPS in mind. The Kismet scripting engine is surprisingly powerful, especially if you have people on your team who do not know how to program. The graphics of UDK 3 are impressive if put into the hands of a talented modeler and texture artist, but more still can be achieved by CryEngine.

Another good thing about UDK 3 is that UDK 4 is almost out. It’s odd to phrase it like that, but if you are not experienced with UDK yet, starting with  UDK 3 so you are familiar with it by the time UDK 4 comes out is probably a good idea.

CryEngine

CryEngine is pretty. VERY pretty. Seriously ridiculously pretty. Unfortunately that’s really all it has going for it. The world builder toolbox is fairly good, and getting things to look pretty in the first place is very easy, but it comes at the cost of a very small community, very few platforms it runs on, and requiring specialized talents (a programmer, a modeler, a texture artist, etc.). You can make a AAA game from CryEngine, but that is where you have to put your resources: into making a AAA game. It’s not really a prime choice for indie developers without significant ease-of-use tools, like a Kismet clone. I really like CryEngine (no really, it’s phenomenally pretty, I love those weather effects) but the amount of resources to get the full extent of it’s use is too much for a couple guys in a basement.

Profanity and Video Games – Xbox One Privilege Restrictions

TechCrunch released an article yesterday about Microsoft removing privileges from users Xbox Live accounts. The offenders had shared game videos involving “excessive profanity as well as other Code of Conduct violations”, which apparently is something Microsoft is finally cracking down on. In the article, the author writes that he disapproves of the policy enforcement, saying in essence that games and foul language go hand-in-hand.

My opinion is quite different. I am glad that Microsoft is removing the foul-languaged content. It can be argued that for free speech that you can say whatever you like while playing your video games, which is true. However, sharing a video of you sniping someone as you insult their mother in 19 different ways is hardly good entertainment for a large part of the gaming community.

It is commonly thought that Xbox users are all 8-year-olds with a large foul-language vocabulary, and it seems like Microsoft just wants to break that stigma. I primarily play PC games online, and excessive foul language is rarely a problem. And I like that. Maybe if they continue their crack-downs, I may actually consider getting an Xbox.

Python – try-finally and return statements

So I ran into an interesting issue today with try-finally and a return statement in Python.

I was creating a simple if-else on a library that was prone to erroring, so I needed to put it in a try-finally to make sure clean up always happened:

def get_error_prone_choice(value):
    try:
        if is_a_good_choice(value):
            return error_prone_function(True)
        else:
            return another_error_prone_function(False)
    finally:
        clean_up()

Here’s where the multiple exits from a function that Python allows adds some confusion. When does clean_up() happen? I needed to make sure that clean_up happened before it returned the value or bad things would happen (specifically a non-garbage collected object would start to accumulate from the inspect module).

It turns out the finally clause is called at the last possible moment when leaving the try-finally section even when leaving the function, which means I’m fine to use it as it is. However, returning from a finally AND from the main try statement can get confusing quickly:

def get_error_prone_choice(value):
    try:
        return error_prone_function(True)
    finally:
        return clean_up()

This will result in error_prone_function to be evaluated, then the result of clean_up() to be returned! The finally is always called at the last possible moment, meaning the return value is first set to the result from error_prone_function and then overwritten to the result from clean_up().

Image size: digital vs. physical

This is a confusing subject to a lot of people, and can be difficult to explain, but I will try my best.

There are a few concept that must be made clear first. Digital images refer to anything on your computer: Photoshop files, jpegs, pngs, etc.; and physical images refer to photographs or prints that you can touch in the real world.

The size of an image is usually indicated by Width x Height, for example 1920×1080 pixels or 11″x17″.

DPI stands for Dots Per Inch. This is called the “resolution” of a photograph or print and reflects how good the print looks up close. (PPI stands for Pixels Per Inch and is used to describe the resolution of monitors. This has no effect on the size or resolution of a printed image.)

The biggest and most important thing to note is that digital images do not have a resolution. When an application says “resolution” when referencing pixels, they really mean “size in pixels”. Digital images ONLY have width and height indicating how many pixels wide and tall it is.

When a digital .png image is printed, the printer is given the width and height of the .png and the desired width and height of the print. The computer does math and adjusts the DPI to match the digital image to the physical image.

When this size conversion occurs, the DPI will indicate how “clear” or “pixilated” the printed image will be. The higher the DPI, the clearer the image.

For most hand-held prints, 300dpi is a common resolution and 600dpi is for fancy magazines. Increasing the DPI too much would be lost due to the resolution that our eyes can interpret. For prints that will be seen at a distance, the DPI can be lowered. Large billboard prints seen at a distance, for example, are commonly printed at 72dpi without loss of quality.