The Basics of Python Programming
Over the years I have tried to learn many programming languages. Most of the time I never got past the basics. But I have found learning Python to be different. The simplicity, and power of Python has helped me to get past the learning curve, and encouraged me to keep learning.
Python’s syntax is simple, and yet incredibly powerful. It’s also easy to read, which I love. If you have just decided to learn Python then you have made the right choice, so take a breath. Python is very easy to learn which means that you will be through the basics, and on to writing programs in a very short time.
Python is a one-stop shop. There’s a Python framework for pretty much anything, from web apps to data analysis. Over the last few years Python has risen in popularity due to Google’s investment in it (in fact, one recent study has shown Python to be the most commonly taught programming language in U.S. schools). Other applications built with Python include Pinterest and Instagram.
This article is a step-by-step guide through the basics of the Python 3 programming language. You’ll learn key Python concepts, such as syntax, variables, and data types. By the end of this article, you’ll have a high-level overview of Python programming.
This article assumes that you have Python 3 installed on your computer and running correctly. You should also have a code editor up and running. If you haven’t yet installed Python or a code editor you might find these previous articles useful:
- Running your first Python program
- The command line interface for beginners
- Choosing a Python IDE or code editor
How Python code is run
Before we get started writing Python, it’s important to understand what your computer does when you execute a Python program.
The Python programming language is interpreted and not compiled as its C or Java counterpart. What this means is that Python code is run or executed line-by-line. In other words, the order of each line of your Python program matters. Let’s take a look at an example.
Let’s ask Python to perform two calculations and then print the results to our screens:
Input:
Output:
As you can see, 2 gets printed before 4. Nothing earth shattering in that, but what does it mean below the surface? If you have a line of code that returns an error, but the following line of code does not, the Python interpreter returns an error for the first line of code and then stops, without ever getting to the second line of code. Let’s see another example:
Input:
Output:
Because x is not defined in the first line, it returns an error and breaks the program. The second line of code is never executed even though it has no errors. Now that you understand the basic flow of a Python program let’s take a look at its syntax.
The syntax of a Python program
First off, what does ‘syntax’ mean? Basically, it’s the rules that determine the structure of a language. Every language has its own syntax, even or should I say, especially, programming languages. It’s the syntax of a language that distinguishes it from other languages.
When writing Python there is a syntax or set of rules that you must understand, and follow to write error free code. Let’s take a look at some of the most important rules.
- The end of a line of code terminates a statement
When writing Python, the end of the line is used to indicate the end of a statement. You do not need to put in a semicolon (;) as in the case of C, Java, or Javascript. Once you are done with a statement, you let Python know by moving on to the next line.
There may be times however, where a statement gets too long to fit into a single line. When this happens it’s advisable to break it into two or more lines. In cases like this, where you’d like to continue a statement onto the next line, you add a backslash (\) at the end of the line. This tells Python that while you are moving to a new line, it’s a continuation of the last line. Here’s an example:
Input:
Output:
If the backslash was removed, the code would have thrown an error. Take a look and try it for yourself:
Input:
Output:
Another way of indicating a statement in two separate lines is to encapsulate the entire statement in a parenthesis (). This is in fact, a more Pythonic way of doing it than the backward slash method above. See the example below:
Input:
Output:
As expected, the code runs without any errors.
2. Indentation matters in Python
In Python, indentation matters, like really matters. Indentations are the whitespaces you insert before a piece of code. You can easily apply an indentation by pressing the tab button. The point of indentation in Python is to tell the interpreter that this piece or line of code is sub-code under a parent statement. Indentations are typically used in control flows. Take a look at the example below, and don’t forget to try it on your machine:
Input:
Output:
As you can see, the print statement is indented. This is because the variable i, is dependent on the for loop above it.
3. White spaces in a single line does not matter
While leading whitespaces, or indentation matters in Python, whitespaces in between a line of code does not. What this means is that you can add as many whitespaces as you like, and your code would still run as expected. It is, however, Pythonic to leave just one whitespace between words. In the example below, all three lines of code run perfectly with the expected results:
Input:
Output:
Comments are indicated by the hash (#) symbol
I love comments in Python. They’re a way for you to add a description to your code or to explain what a line of code does to other developers who may be using your code. Imagine three from now when you may have a reason to review the code you wrote today. Will you remember why you wrote it the way you did? Comments are a way for you to add helpful descriptions or insights to your Python code. In Python, comments are usually indicated by has symbol (#). When you using the hash symbol, any code following it ,and on the same line is viewed by the Python interpreter as a comment and will not be outputted to the screen or otherwise impact your program. Take a look:
Input:
In the code above, the Python interpreter sees the line ‘define a variable x’ as a comment and not code. Even if it were valid python code, adding a # prevents it from being executed. See the example below:
Input:
Output:
As you can see, the first and last lines were not printed because they were viewed as comments by the Python interpreter.
Another way of adding comments is by using three apostrophes (‘’’). This is typically used for multiline comments. If you ever find yourself needing to add a detailed explanation for a piece of code it’s advisable to use ‘’’ for your comments. Take a look at an example below.
Input:
Output:
As expected, everything inside ‘’’ is regarded as a comment and is not executed by the Python interpreter.
Parentheses are used to call a function
Functions are an integral part of Python and virtually every programming language. In a later article we’ll dive into functions. For this introduction to Python article it’s enough to know that parentheses () are used to call a function. The print statement that we have been using so far is a pre-built function in Python. To call this function, we type print() and not print.
In Python, parenthesis are also used to group mathematical operations. Just like the BODMAS rule we learned as kids, adding parentheses to a mathematical operation in Python tells Python that it should be given preference over other operations. Take a look at the example below.
Input:
Output:
As expected, 2–3 was computed first because of the parenthesis. Then the answer (-1) was multiplied by 2 to give -2.
Understanding Variables in Python
Variables are a way of representing data in Python. Every variable is connected to a value. Variables allow you to store, manipulate and reference data in Python. Variables can store different data types including numbers, texts, lists, and more. Think of variables as names that point to a piece of data.
In the code example below, x is a variable and as shown, can be used to represent different types of data.
Input:
Something to point out here is that Python is a dynamically-typed language. This means that variables can be changed within the code. As discussed earlier, Python code is run line by line. So, if you assign the same variable name to more than one piece of data, Python uses the most recent version of the variable. Take a look at the example below, to see how this works in code.
Input:
Output:
Now that you know the basics of a variable here are some conventions when naming them.
Variable Naming Conventions in Python
- When naming variables, try to use descriptive words. For example, rather than naming the price of a car as variable x, name it as car_price.
- If you have multiple words in your variable name, separate them with an underscore (_)
- Use uppercase only when you are naming a constant. Variable names are generally meant to be in lower case. By convention, you should only use uppercase only when you have a variable that will not change throughout your code. If you are building a deep learning model for instance, and you want the number of epochs to be 100 always. You can write EPOCH = 100 rather than epoch = 100.
The Various Data Types in Python
Data can come in different forms. In Python, there are five major built-in types.
- Integers: Integers are simply whole numbers (2)
- Float: Floats are numbers with a decimal point (4.56, 5.0)
- Boolean: Booleans are True or False values
- String: Strings are characters or text in Python. Strings are opened and closed with quotation marks, either single or double, not mixed. For example x = ‘5’ is considered a string, and not integer because it is placed inside single quotation marks.
- NoneType: None are objects for which the object has no value
Summary
In this article, you’ve hopefully gained a good basic understanding of how Python is written. You now understand Python syntax, variables, and data types. Hopefully this introduction helps you on your way to becoming a Python programmer.