In this article, we will cover python basics. We will discuss what is python, where you can download python from, the basic syntax of python, how to input and output information in and out of your python scripts, how to do loops, conditional operators (if/else/elif), and how to write basic functions.
What is Python?
Python is a cross platform interpreted programming language that was introduced in 1989. The great thing about Python is that it is cross platform. You can run your basic Python applications on any platform that you can install the Python runtime environment. This somewhat fills the need that Java programming was meant to solve. An Object Oriented Cross-Platform programming language.
In this section we will discuss how to install python for each of the major platforms. There are 3 versions of Python:
- Python 2
- Python 3
No one really uses the first version of Python anymore. The most common version is Python 2. And most development is now around Python 3. For that reason, I would recommend you focus on Python 3 instead of python 2. However, for the purposes of this article, either one will work for you.
Run the following command from a terminal window to install Python 2.x:
apt-get update sudo apt-get install python
Run the following commands from a terminal window to install Python 3.x
sudo apt-get update sudo apt-get install python3
If you want Python 2.x, you are in luck. Python 2.7 ships on OSX. That said, Python 2.7 is only supported until 2020. There is a nice looking countdown clock here. Given that, I recommend you switch to Python 3.x, it is easy enough to install.
If you have homebrew installed, you simply run:
brew install python3
If you do not have homebrew installed, I would recommend you install homebrew as it will make your life much easier. For information on how to install homebrew, see my article on getting OSX ready for tensorflow.
If you are on windows, you can download the latest builds here. Simply download the appropriate build for your version of windows and you can select whether you want to download python 2.x or 3.x. After it is downloaded, double-click on the installer, click through the installation wizard, and you will have python installed.
If you install Python and select current user, the Python installation folder will be somewhere in your %appdata%\local\Programs folder. If you select to install for all users on the computer, the python installtion will default to the root of your C:\ drive. If you installed Python 2.7, it will be installed to: C:\python27
If you install Python 3.6, it will be installed to C:\python36
If you are using Chocolatey, my favorite way to install programs, you can install the latest version of python 3 by running: choco install python . For information about how to install chocolatey, click here.
Pip is a package manager for python, and I would highly recommend that you install pip at this stage. Once you have the basics of python down, there are a lot of modules that extend Python’s functionality. Pip allows you to easily install these modules and then use them as you write your python scripts/applications.
To install pip, you have a few options. You can follow the instructions here. Which basically say the following:
- Download the get-pip script from here.
- After you have download the script, you can run: python get-pip.py to install pip.
Alternatively, if you are running on OSX, and you have homebrew installed, you an run:
brew install pip
**Note, homebrew now include pip3 when you run brew install python
Or, on OSX or Linux, you can install pip with this one line command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
For information on installing homebrew, check out the article on getting OSX ready for Tensorflow.
Finally, if you are on Windows, Linux, or MacOS, you can install using easy install, an alternative package manager for Python. To install using easy install, just run: easy_install pip
Basic Python Programming
Now that you have Python installed, you can start writing scripts. Here are a few things you might find useful.
In some languages, you use the concept of curly braces for defining what code goes together. For example, in C syntax, you might create an if statement that looks something like this:
In the above example, you see that I have put in an opening and closing curly brace around “do something”. This is how I define the blocks of code. If what I put in the parentheses is true, it runs whatever is in the curly braces.
Python is different in that there are no curly braces for code blocks. Rather, Python uses indentation to define blocks of code. This forces you to create more readable code. And it also means you no longer have to spend hours troubleshooting your un-balanced curly braces. Here is an example of some python code:
If a > b: do something
The above code does the same thing as my C syntax example. If A is greater than B, then it will do something. However, I did not use any curly braces. Rather, I indented the second line to tell the python interpreter that “do something” was in the code block for the if statement.
This brings us to the next question…how do you indent your code? This is more of a philosophical argument. There are some programmers who feel that you should use a tab to indent your code. Others feel strongly that you should use two spaces to indent your code. There is no “right way” to do it. You just need to make sure that you use whatever the standard is for the project you are currently working on and stick with it. Mixing the two within a project will cause confusion and headaches.
All of that said, spaces are more common to use in Python than tabs. Here is a good article talking about tabs vs spaces and they have it broken down by language.
There are a few ways to input into your python script. You can input via the console. You can input via a file. There are many other ways as well, but lets stick with these two for today.To prompt for user input, you would run the following:name = input(“What is your name?”)
The above code will prompt the user to enter their name, and save whatever they type into the name variable.
Next lets look at how to read in a file:
myfile = open(‘myfile.txt’,'r') text = myfile.read()
The above code declares a file variable called my file. We then populate the text variable by using the read function attached to the myfile object. The result is we have read the contents of myfile.txt into the text variable.
What if we want to read the file one line at a time? We can accomplish that by using the readline function as demonstrated below:
myfile = open(‘myfile.txt’,'r') text = myfile.readline()
The above code block will result in the variable called text being equal to the first line of myfile.txt. When we get to the section on loops we will come back to this example.
In the previous section we discussed how to input into your python script via the console and by reading in a file. Next we will look at how we can output from our python script.
First, how do we output to the console? That one is easy.
Print “hello world"
Or, if we want to use the example from the previous section, we can read in the first line from a text file, and then print it to the console:
myfile = open(‘myfile.txt’,'r') text = myfile.readline() print text
Next, lets read in something from the console, and write it to a file. There are two ways we can write to a file. We can write in a manner that we overwrite the existing file. Or, we can simply append to the existing file.
In this example, we will overwrite an existing file:
name = input(“What is your name?") myfile = open(‘myfile.txt’,’w') myfile.write(name) myfile.close()
In this example we will append to an existing file:
name = input(“What is your name?") myfile = open(‘myfile.txt’,’a') myfile.write(name) myfile.close()
The only difference between the two examples above is the second argument I passed. To write to a file, I pass a w, to append to a file, I passed an a. And in the previous examples, I passed an r to open the file as read only. The other thing to note about the two examples above, is I called the myfile.close() function. You really should call this any time you are finished working with a file. This closes out any open file handles. It is especially important when you open the file to write or append to the file. If you don’t close the file handles, you risk leaving the file locked, preventing others or even yourself from being able to continue using the file.
The most common logic operators are else, if, and else if. Lets start with an example:
x = 10 If x < 5: print “less than 5” elif x > 15: print “Greater than 15” else: print “greater than 5, less than 15"
The above example demonstrates all three operators I mentioned. First we declared the variable x and set the value to 15. We then checked to see if it was less than 5 using the if statement. If it was less than 5, we would have printed the text “less than 5”.
Next, we used the elseif operator to do a second check. If x was greater than 15, it would have printed “Greater than 15” to the console.
Finally we used the else operator. This is the default state if none of the other conditions are true. In this case it printed “greater than 5, less than 15” because none of the other two conditions were met.
You are not limited to 3 operations in this case, you could put 100 elseif statements together if you wanted to. However, that would be somewhat difficult to read. And you are probably better off doing a lookup. For more on that, check out my article on switch statements.
You could also do the whole thing without the elseif by using a bunch of if statements. However, there are some differences. Lets examine those differences.
x=10 if x > 5: print “greater” if x<15: print “less"
x=10 if x > 5: print “greater” elif x<15: print “less"
The two blocks of code are the same except one uses the elif statement. The other is two if statements. The first block of code will evaluate if x is greater than 5, then print greater. It will then do a second evaluation to see if x is less than 15, and print less.
The second block of code will check to see if x is greater than 5 and the print greater. It will not evaluate the second conditional statement because it only runs if the first conditional statement is false. That is what the else means in an else if statement.
Loops are important as they allow you to run the same block of code many times without having to re-type the same code over and over again. There are two main kinds of loops:
- For loops
- While loops
The difference being with for loops you declare all the variables at the time that you declare the loop. With while loops you declare the variables separately. This will become more obvious when we look at the examples. Lets start with a for loop:
myfile = open(‘myfile.txt’,'r') For line in myfile: print line
The above loop declares the line variable, then prints each line in myfile. In this case, myfile is a collection of lines from myfile.txt.
Next we will look at a while loop. I was having trouble re-creating the above code using a while loop without making it too complicated. So we will look at a while loop from a different perspective.Lets say we want to run a block of code 10 times:
x=0 While x < 10: print “hello" x = x + 1
The above code will print the word help 10 times. Each iteration it will increment the value of x by one. Once x reaches 10, it is no longer less than 10 and it will break out of the loop. There is also the option of manually breaking out of a loop. Here is an example of that:
x=0 while true: print hello x=x+1 if x > 10: break
In the above example, I said “while true” which starts an infinite loop. Meaning it will run forever without intervention. I then added an if statement to say if x is greater than 10, break out of the loop. The other thing I did was added a nested block of code. Notice under the while, there are 2 spaces. Then under the if there are 4 spaces.
Functions allow you to group bits of code together that you wish to call many times. It lets you have cleaner code, fewer errors, and fewer headaches. Given that python is an interpreted language, you put all of your functions at the top of your python files. As opposed to a compiled language like C where you can declare your functions at the top or bottom of your file…does not really matter.
First, lets declare our first function:
def myfunction(): print "hello" print "hello" print "hello"
The above code declares a function called myfunction. All the function does is print the word “hello” three times on the console. When we want to call the function, we just have to type:myfunction()
Each time you type the above function name, it will print “hello” three times.
Next, lets look at passing variables to a function:
def myfunction(name): print “hello “ + name print “hello "+ name print “hello "+ name
In the above function, we declared a variable of name. When the function is called, it will print hello followed by the name you passed to the function. To call the function now, you must pass a variable to it:Myfunction(“bob”)
When you run the above, it will print:
“hello bobhello bobhello bob”
I hope this article on python basics has been helpful. We have covered how to input and output information in and out of your python scripts, how to do loops, conditional operators of if/else/elif, and how to write basic functions.