Python Fundamentals

Recap

In the previous article we covered how to install and configure Python 3 and VSCode. After completing the installations we also learned how to download libraries for Python using the pip command. On completion of these tasks we are finally ready to address the code portion of the project.

Overview

In this article we will do an introduction to the Python language and go over the key concepts required for creating the ballistic calculator.

All programming languages allow a user to create a set of instructions for the computer to run. These instructions are similar to a baking recipe, a series of step by step instructions that guide you through a process. Let's continue this analogy, a baking recipe needs to be written in a specific manner as the baker has no ability to ask questions if anything in the recipe is unclear. Imagine a cookie recipe built like this:

Eggs
Flour
Milk
Baking Powder
Sugar
Vanilla

Combine ingredients in a bowl, portion onto a cookie sheet. Bake for 20 mins.

If you were to try and follow this recipe, you would quickly realize you are missing key information. The author never included how much of each ingredient is required, or what temperature they should be baked at. Let's re-write the recipe:

2 Eggs
3 cups Flour
2 cups Milk
2 tsp Baking Powder
1 cup Sugar
1 tsp Vanilla

Combine ingredients in a bowl, portion onto a cookie sheet. Bake at 375F for 20 mins.

In this recipe, you have all the information required to create the cookies, this is a complete set of instructions.

As a programmer, it is important to be specific with the code you write. A computer, like the baker in the analogy, doesn't have the ability to ask questions. If you do not write clear and complete instructions, the program will not run.

Python is one of the easiest programming languages to learn as the code is very readable. Fortunately, we do not require advanced Python knowledge to write the ballistic calculator. We will be covering the following fundamental Python topics:

  • Variables
  • Comments
  • If Statements
  • Loops
  • Functions

Python variables

A variable in a programming language is how we can store data. Let's use an example to illustrate:

x = 3 * 4

In this example, the variable x will be equal to 12. Let's extend this with some more complexity:

x = 3 * 4
y = 1 + 2

z = x + y

In this slightly more complicated example x will equal 12, y will equal 3, and z will equal 15.

The naming of variables is up to the programmer, however, it is best practice to make them descriptive of their function. Here is an example of a longer variable name:

sumOfNumbers = 2 + 2

divisionByTwo = sumOfNumbers / 2

In this example, we sum two numbers and hold that value in the sumOfNumbers variable. We then divide this sum by two and store it in the divisionByTwo variable.

A variable can also hold more than just numbers, it can also hold text (called strings), lists, etc. Here is a list of examples:

Numbers

In Python (and many programming languages) numbers are broken into categories. In Python, the two common categories are integers and floats.

An integer can only be a whole number, if the answer evaluates to a decimal it will be rounded to a whole number.

A float can represent numbers with decimals. In the version of Python we are using (Python 3) it defaults the outputs of calculations as floats so we do not need to worry about integer rounding of our answers. However, sometimes numbers are stored in a text format which we need to convert to a float format. This can be done with the float() function.

Text (Strings)

When text is stored in a variable, it is referred to as a string. To store text as a variable we use quotation marks like this:

x = "This is a how we store text"

Sometimes a number is stored as a string (common if we read numbers from a spreadsheet for example).

number = "9"

In this case, we need to convert the text number into a float:

number = float("9")

Comments

To make code readable, it is a good practice to include comments that explain what it does. A comment will be ignored by the computer when the program is run.

To create a comment, you put a # at the beginning of the line like this:

x = 3 * 4
y = 1 + 2

# Z takes the sum of x and y
z = x + y

Reading code is much harder than writing it, comments can help make complicated programs easier to understand.

Lists

A list in Python allows us to store a series of values. These are typically used in loops (we will discuss loops soon) to hold the history of the changing values. Here is an example of a list:

myPythonList = [1,2,4,8,16,32]

With a list, we can access any of its values by using the appropriate index. The common convention with programming languages is to start counting from 0. Appropriately, the first value in a list has the index of 0.

Our myPythonList holds six values, the indexes of this list would be [0,1,2,3,4,5]. Therefore, if we want to access the 5th value in the list we can use this code:

myPythonList = [1,2,4,8,16,32]

# Access the 5th value (start counting from 0! ie: 0,1,2,3,4)
fifthValue = myPythonList[4]

If we want to add a number to the end of the list, we use the append function like this:

myPythonList = [1,2,4,8,16,32]

myPythonList.append(64)

print(myPythonList)

OUTPUT: [1,2,4,8,16,32,64]

There are many more things we can do with Python lists, we will explain the functionality as we encounter it in our code.

Python If Statements

An if statement is a core concept of programming. An if statement is made of three parts: the condition, what to do if the condition is true, and optionally what to do if the condition is false (this third condition is not needed but is common).

Let's quickly look at how to apply an if statement. Imagine you are a teacher who needs to notify students if they passed or failed the exam. You have the list of the students test percentages, if they score 50 or above they pass, if they score less than 50 they fail. The code to for an if statement looks like this:

studentScore = 60

if studentScore >= 50:
    print("PASS")
else:
    print("FAIL")

OUTPUT: PASS

In this example, you set the studentScore variable to the score of the student (60 in this case). The code then checks if the score is greater than 50. In this case it is, so the program will print out PASS. The code under the else statement will be skipped.

The other thing to notice is the syntax of the if statement. You can see that the print statements are indented by four spaces. This is how the computer determines what code should be executed as part of the if statement, it also helps to organize the code visually.

It is also possible to chain together multiple conditions, imagine that instead of PASS/FAIL, you want to instead have the letter grade. When you have an if statement with multiple conditions, it will check the conditions in order until the first one is fulfilled. After the first condition is fulfilled, the rest of the code in the if statement will be skipped. Conditions after the first, and before the last, use the elif keyword. An if statement with multiple conditions will look like this:

studentScore = 60

if studentScore >= 80:
    print("A")
elif studentScore >= 70:
    print("B")
elif studentScore >= 60:
    print("C")
elif studentScore >= 50:
    print("D")
else:
    print("F")

OUTPUT: C

In our example, the student did not score greater than or equal to 80, so it moves to the next condition. They also did not score greater than or equal to 70, so it checks the next. They did score exactly 60, so it will print out C and then skip the rest of the code in this if statement.

Python Loops

In computer programming, loops allow us to do very powerful things. A loops tells the computer we want it to execute an instruction over and over until we tell it to stop. The loop we will be using is a for loop. This is only one of many different types of loops, however, we will only cover the for loop in this article.

The syntax for a for loop looks like this:

for i in range(0,100):
    print(i)

The way this for loop works is the variable i will be incremented after cycle. In this case, the variable i starts at 0. The code inside the loop will run and print the value of the variable i for this cycle (i = 0). The next cycle, the variable i is incremented to 1 and the number 1 will be printed. Our stop condition is the last value in the range(0,100) function. This loop will run 100 times.

Once again, you notice the syntax with the 4 spaces before the print statement. Any code we wanted executed on every run of the for loop needs to be indented like this.

Python Functions

In the above code examples, we have been using the print() Python function to print text or numbers out to the console. The range(0,100) is also an example of a function.

A Python function is used when you know that you will have to re-use the same piece of code multiple times. This prevents you from writing the same code over and over and also makes the code easier to read.

For example, let's create a function that will convert a distance in feet to meters.

def convertFeetToMeters (distanceInFeet):
    distanceInMeters = 0.3048 * distanceInFeet
    return distanceInMeters

We will breakdown each line of code here:

def convertFeetToMeters (distanceInFeet):

When we type def this lets the computer know that we are creating a function. Immediately following def is the name of our function, in this case, we chose to name it convertFeetToMeters. Inside the brackets is what we need to give the function as an input, in this case, we need to know the distance in feet that we want to convert.

    distanceInMeters = 0.3048 * distanceInFeet

This line of code creates a variable called distanceInMeters and sets it equal to the input distanceInFeet multiplied by the conversion factor. Notice it is indented to signify it is part of the function.

    return distanceInMeters

The return statement is how we let the computer know that we want to return a value back after the function is called. In this case, we want to return the number held within the distanceInMeters variable.

Now like the print() and range() functions, we can call our newly created function like this:

distanceMeters = convertFeetToMeters(15)
print(distanceMeters)

OUTPUT: 4.572

Since we wanted our function to return a value, we needed to create a variable to hold the value that is returned. We set this newly created variable distanceMeters equal to the returned value of the function.

To call our function, we provided the number 15 as the parameter. If we look back at the code for our function, we are essentially setting the value of distanceInFeet to 15.

Conclusion

The Python code for our ballistic calculator will not require much beyond the fundamentals that we covered in this article. Learning programming can be tricky and unintuitive. Do not worry if after reading this article the concepts do not make sense to you. There are plenty of resources dedicated to teaching Python and I encourage you to seek them out. This article is not intended to be a complete introductory course to Python, but rather introduce the concepts that are required to create the ballistic calculator so they will not be completely foreign when we review the code.

Next article: Calculating Trajectory: Programming a Ballistic Calculator