Comments

Commenting in Python is also quite different than other languages, but it is pretty easy to get used to. In Python there are basically two ways to comment: single line and multiple line. Single line commenting is good for a short, quick comment (or for debugging), while the block comment is often used to describe something much more in detail or to block out an entire chunk of code.

One Line Comments

Typically, you just use the # (pound) sign to comment out everything that follows it on that line.

Example
print("Not a comment")
#print("Am a comment")
Result

Not a comment

Multiple Line Comments

Multiple line comments are slightly different. Simply use 3 single quotes before and after the part you want commented.

Example
'''
print("We are in a comment")
print ("We are still in a comment")
'''
print("We are out of the comment")
Result

We are out of the comment

Alright, we are done with comments, but don’t forget them. They are your best friend in debugging complex Python code. Now onto the actual programming stuff.

Classes

Well, I’m not going to lie to you. The next few tutorials are going to be rather complicated if you have never had any experience with object oriented programming (OOP). Classes are awesome because of a few reasons. First, they help you reuse code instead of duplicating the code in other places all over your program. Classes will save your life when you realize you want to change a function. You will only change it in one spot instead of 10 different spots with slightly different code. Another important part of Classes is that they allow you to create more flexible functions. First, we need to get our hands dirty and start figuring out how to make a class.

Creating Classes in Python

Example
#ClassOne.py
class Calculator(object):
    #define class to simulate a simple calculator
    def __init__ (self):
        #start with zero
        self.current = 0
    def add(self, amount):
        #add number to current
        self.current += amount
    def getCurrent(self):
        return self.current

Now, I’m not going to be like everyone else and start bombing terminology at you. Quite frankly, object oriented programming is rather difficult for a beginner and throwing these abstract concepts at you is just going to make you learn slower and hate OOP. So, a class is kind of like a function. We just establish it using the class keyword and following it up with whatever we want to name our class. In our case, we are making a calculator, so that’s what I called it. How original! Next, we throw in the argument of object. This is just simply a class above this class. Don’t worry much about it. It involves some serious terminology to explain. So, just type it and we will talk about it later.

Next, we get into this little guy def __init__ (self):. Abstract concept time! Objects are made from classes. So, if we had a class named cake. We could make cake objects. However, whenever you make a cake it’s not the same as the previous cake you made. Sure, it may look like it and taste like it, but it’s not that identical cake. So, in our class we have instances so that we know that they are two different cakes. Why do we need this you ask? Well, let’s make two cakes from the same class. Now, I take a big bite out of one of the cakes. Now, you definitely want to know which cake is which right? That’s why instances are so important! So, def __init__ (self): just says let’s create an instance of this class. But, why do we pass in a parameter of self, you might ask. Well, it is pretty related to what we just discussed. Classes make objects and the functions in a class become the object’s methods. However, we do need to know which class function belongs to which instance of the class, so we just implicitly pass in the objects property of self (discussed further in later example). Finally, we get down into the heart of the initialize function. Where we use self.current to create an instance variable equal to zero. Woo! We are done with the toughest part.

Next stop is the add function. We just pass in self and another parameter called amount. Again, self is so we know which instance. The amount is hopefully some number that was passed in. Using our previous knowledge, we understand that we are just adding whatever the amount is to the current variable.

Last, but certainly not least, we move onto this idea of “getting” variables from a class. To get the value of our self.current variable, we should use the best practice of putting it in a function and then calling the function to get the value so that we don’t mix up our instances. We set up the function and pass in the instance, and just tell Python to return the value.

Using Classes in Python

Example
from ClassOne import * #get classes from ClassOne file
myBuddy = Calculator() # make myBuddy into a Calculator object
myBuddy.add(2) #use myBuddy's new add method derived from the Calculator class
print(myBuddy.getCurrent()) #print myBuddy's current instance variable

In another file, we put in this code. Once we run it, we see it prints 2 to our screen. All of that work just to get the result of 2! Anyways, let’s break this guy down. First, I have assumed that both of your classes are in the Python directory. Next, we use from ClassOne, which basically gives Python a reference to which file we are talking about. Then, we polish the statement off with import *. It just means that we want all of the classes in the file. In our case, we only have one class, the Calculator class. Next, we create an Calculator object called myBuddy by assigning it to the Calculator class with myBuddy = Calculator() . Now, this gives myBuddy all of the functions and variables in the Calculator class. (Note: once myBuddy gets those variables and functions, we call them properties and methods). Since we already initialized myBuddy, it has a property of current, and we see that property as a variable called self.current in the Calculator class that is set to 0. So, now we just call myBuddy.add(2) method, which is the add function in our Calculator class. Put simply, this is just 0 + 2. Finally, we output our instance class variable self.current by using the myBuddy.getCurrent() that returns our variable.

Well done! That was a long one. Take a breather. That’s one of the toughest concepts in programming to wrap your mind around. Believe it or not, when you use strings, lists, dictionaries, etc., they all are made from classes. From here, you should take some time and study object oriented programming and attempt to apply it in Python.

Variables

In the heart of every good programming language, including Python, are the variables. Variables are an awesome asset to the dynamic world of the web. Variables alone are dynamic by nature. However, Python is pretty smart when it comes to variables, but it is sometimes quite a pain. Python interprets and declares variables for you when you set them equal to a value. Example:

Example
a = 0
b = 2
print(a  + b)
Result

2

Isn’t that cool how Python figured out how a and b were both numbers. Now, let’s try it with the mindset of wanting the 0 to be a string and the 2 to also be a string to create a new string “02”.

Example
a = "0"
b = "2"
print(a  + b)
Result

02

Ah, see! Now, it thinks they are both strings simply because we put them in quotations. Don’t worry if you don’t understand strings yet, just note that they are not numbers or integers. This is really awesome, but as with any element or practice in a programming language there is always the flip side, especially with this auto declaration thing. Suppose we started off with “0” being a string, but we change our mind and want it to be a number. Finally, we decide that we want to add it to the number 2. Python bites us with an error. This brings us to the idea of casting the variable into a certain type.

Example
a = "0"
b = 2
print(int(a)  + b)
Result

2

Whoa, what is that int() thing? This is how you cast one variable type into another. In this example, we cast the string 0 to an integer 0. Let’s take a quick peak at a few of the important variable types in Python:

  • int(variable) – casts variable to integer
  • str(variable) – casts variable to string
  • float(variable) – casts variable to float (number with decimal)

Like I said, those are just the most commonly used types of casting. Most of the other variable types you typically wouldn’t want to cast to.

Operators

With every programming language we have our operators, and Python is no different. Operators in a programming language are used to vaguely describe 5 different areas: arithmetic, assignment, increment/decrement, comparison, logical. There isn’t really much need to explain all of them as I have previously in the other categories, which means we will only cover a few of them.

Arithmetic Operators

Example
print (3 + 4)
print (3 - 4)
print (3 * 4)
print (3 / 4)
print (3 % 2)
print (3 ** 4) # 3 to the fourth power
print (3 // 4) #floor division
Result 7
-1
12
0.75
1
81
0

See, they are pretty standard. I included how to do exponents because it’s a little funky, but other than that, they are fairly normal and work as expected. Don’t forget that you can use the + sign to concatenate strings. The addition, subtraction, multiplication, and division work just like expected. You might have not seen the modulus operator before (%). All the modulus operator does is to divide the left side by the right side and get the remainder. So, that remainder is what is returned and not the number of times the right number went into the left number The double * is just an easy way to provide exponents to Python. Finally, the floor division operator (//) just divides the number and rounds down.

Assignment Operators

These are pretty identical to the previous languages also, but a refresher never hurt anyone. Example please!

Example
a = 0
a+=2
print (a)
Result 2

Of course, you can do this with any of the previous arithmetic operators as an assignment operator followed by the = We just told Python to add 2 to the value of a without having to say something like a = a + 2. We are programmers, and we are proud to be called lazy!

Functions

Functions in Python are super useful in separating your code, but they don’t stop there. Any code that you think you will ever use anywhere else, you should probably put in a function. You can also add arguments to your functions to have more flexible functions, but we will get to that in a little bit. You can define a function by using the keyword def before your function name. Let’s use our first Python function.

Example
def someFunction():
    print("boo")
someFunction()
Result boo

It is necessary to define functions before they are called. Even though we have to skip over the function while reading to see the first statement, someFunction(). This throws us back up into the def someFunction():, again with a colon following it. Then after we acknowledge that the function is being called, we create a new line with four spaces for our simple print statement.

Functions with Arguments

Simple functions like the one above are great and can be used quite often. However, there usually comes a time where we want to have the function act on data that the user inputs. We can do this with arguments inside of the () the follows the function name.

Example
def someFunction(a, b):
    print(a+b)
someFunction(12,451)
Result 463

Using the statement someFunction(12,451), we pass in 12, which becomes a in our function, and 451, which becomes b. Then, we just have a little print statement that adds them and prints them out.

Function Scope

Python does support global variables without you having to explicitly express that they are global variables. It’s much easier just to show rather than explain:

Example
def someFunction():
    a = 10
someFunction()
print (a)

This will cause an error because our variable, a, is in the local scope of someFunction. So, when we try to print a, Python will bite and say a isn’t defined. Technically, it is defined, but just not in the global scope. Now, let’s look at an example that works.

Example
a = 10 
def someFunction():
    print (a)
someFunction()

In this example, we defined a in the global scope. This means that we can call it or edit it from anywhere, including inside functions. However, you cannot declare a variable inside a function, local scope, to be used outside in a global scope.