PYTHON BASICS
Topics Covered:
- Python overview
- Download Python
- Creating our first program
- Saving and running a program
“I use Python almost regularly at my job. I have used it for forecasting time series data to estimate staffing requirements and various other business metrics. I have also used it to automate an ETL process by using Pandas to break contents of a large excel file into smaller excel files by categories. This was a huge time saver.”
– Ali Murad, Financial Analyst, University of North Alabama Graduate
Python Overview
In this book we use Python as the introductory programming language. One of the primary reasons we chose Python is because it is considered an easy to learn language. The designer of the language emphasized code readability. This is an important feature of a language since it makes the code easier to understand.
In addition to being a great language for beginners, Python is also a very powerful language. It is used in a broad range of applications, including Geographic Information Systems (GIS), artificial intelligence (AI), visualization, machine learning, and robotics.
Python is an object-oriented language, which means your program data is stored as objects that have properties and functions. Most modern programming languages, such as C++, Java, and Visual Basic, are object-oriented.
Finally, as we saw in the chapter one, Python is one of the most popular programming languages today according to the TIOBE index. Knowing a language that is popular is helpful, since an employer is more apt to value someone having that skill. Also, the resources to learn Python, including books, web sites, tutorials, and videos, are plentiful.
Python uses an interpreter to translate your high-level code into a form that the CPU can understand and execute. Python is an open source language. This means that you can not only download it for free but can even view and modify the code used to create the Python interpreter. The language is also portable, which means the code that you write in one operating system (Windows, Mac, Linux) will work in another. This is a major advantage of using an interpreter rather than a compiler, since interpreted languages don’t need to be translated into a specific computer’s machine code.
There are two versions of Python, 2.X and 3.X, that are common in use today. These versions are not backward compatible. That is, if you are using version 3 of Python and try to run a program that works in version 2, it may not work. In this book, we will be using the version 3. This is an unusual circumstance; historically, most programming languages tried to maintain backward compatibility so that existing programs would not need to be modified when updates were made to the language features.
Download Python
As mentioned earlier, Python is free. To download Python to your own computer, you must first visit the official website at http://python.org. The top of the Python main web page looks like this (at least until the next language update arrives!):
If you scroll over the “Downloads” tab, a smaller window will appear looking like that seen below. The web site will recognize your computer’s operating system so you won’t have to make any difficult decisions. Just click on the button with the current version number (i.e., “Python 3.9.2”). Once you download the file, simply run it and follow any instructions that pop up along the way. It should take a couple of minutes and you’ll be ready to start coding.
You should notice a “Documentation” tab on this initial web page, as well. This is where the official documentation for the Python language resides. This page will be a good resource throughout your programming adventures so make a note of it.
Once you have Python successfully downloaded, there are several ways that you can write and run your Python programs. Idle is an integrated development environment (IDE) for Python. An IDE allows you to create, edit, run, troubleshoot, save, and open your code all in the same easy-to-use program.
When you open Idle for the first time, a window similar to the one above will appear. The Python version number (In this case, 3.8.0, since the author was too lazy to update his computer to version 3.9.2) is shown in the window title and the first line inside the window. The Idle environment has two modes. Initially, the environment is in interactive mode, which allows you to evaluate expressions and individual instructions. When you want to develop a larger program, however, you will want to switch to script mode.
The string “>>>” is the screen prompt which tells you that the environment is waiting for you to type a Python expression or instruction. The interactive mode can be used to play around and just experiment with different commands. Try typing the four expressions shown below following the prompt. You will notice that Python uses different colors for syntax highlighting. The syntax are the rules of the language. More about that later.
When you type 3+2 and press the Enter key, the result of 5 is returned. Of course, this comes as no surprise. In the interactive mode, the expression you enter is executed immediately. You will notice that all of the program output is displayed by Idle as blue. Obviously, 4*5 resulted in 20. Why did 2**5 return 32? If it isn’t obvious, see if you can research (i.e., Google) the answer.
Whenever you want to display something in Python, you use a special function called print. All of the built-in Python functions appear as purple in Idle. Also note how the word “hello” appeared in double quotes. This means it is a string, or sequence of characters. Idle displays strings using green. The last example had a string, followed by *, followed by a whole number. How did Python evaluate that expression?
Creating our First Program
Most of the time, we want to write larger programs, which are sometimes called scripts. You do not want to write a full-fledged script using the interactive mode. Instead, go into script mode by clicking on “File” and then “New File.” A convenient way to program in this mode is to resize this new script window and put it in the right side of your screen. Resize the interactive window and place it on the left side of your screen:
Now, let’s get back to tackling the electricity problem from the chapter one. In your new script window, type the following program, replace the X’s with your name and the current date. We will break each instruction down, line by line, afterwards.
Note: It is important that you actually type in this program to get used to this environment of creating, editing, troubleshooting, saving, and running programs.
The lines at the top of this programming that begin with the pound sign (#) are called comments. When the interpreter goes to translate and run your code, it will ignore comments. These lines are added to document your program. That is, the comments will describe your program and various aspects of it. As a minimum, you should include the 4-line comment block illustrated in this example.
As mentioned earlier, the print function is used to display information to the screen. Each print statement will send an output to a new line. With the print function, you include what you want displayed inside parentheses. Anything inside the parentheses of a function is called a parameter. With no parameter, the print function simply outputs a blank line.
The input function is used to get information from the user via the keyboard. The program will pause until the user types information followed by the Enter key. Data will be read in as a string and stored as a variable, which is simply a named memory location. The parameter for the input function is a prompt that is displayed as a hint to the user indicating what should be entered at the keyboard.
You should notice in the program the same input statements for wattage, hours, and price that we saw in the algorithm and flowchart in chapter one. Since the input function returns the user’s input as a string, we need to use the float function to convert that string to a floating-point number. Data types will be discussed in more detail in the upcoming chapters.
After the input instructions, we use our formula to compute the cost of the electricity based on the values entered by the user. The final step is to output the cost using a print statement. The print statement uses two parameters – a string literal that functions as a label, and the variable cost. Notice that the label has quotes around it and the variable does not. When printing a variable, the contents of the variable will be output, not the actual name of the variable.
Saving and Running a Program
Finally, we are ready to run the program. In Idle, click “Run” on the menu and then “Run Module” to execute your program. Alternatively, the “F5” function key is treated as a shortcut to trigger this same action. When you run the program, the output and interaction will occur in your interactive screen.
Note: Idle will force you to save your program before you run it. All of your Python programs will end with a “.py” file extension. You should save all of your programs to a common location that you can access conveniently. Also, you should save using a meaningful file name like “electricity.py”.
Now, let’s find out how much that lamp is costing the family. Suppose your lamp uses a 75-watt bulb. A month is approximately 720 hours (24 hours per day x 30 days) so we will input 720 for the second input. Finally, the price of electricity varies depending on many things, including the state you live in. Suppose your electric company charges 12.7 cents per kilowatt hour. The interaction would like that shown:
The program shows us that it will cost $4.25 to leave that lamp on for a month straight. Of course, we have a lot more decimal places than we need, but we will worry about formatting our output later. We have a working program that solves our problem!
It is possible that your program did not run successfully. If you mistype one or more instructions, you may have created a syntax error, which is when one of your instructions breaks the rules of the language. For example, suppose you forget the closing right parenthesis at the end of the first print instruction. As shown below, Idle will display a pop-up screen with an error message. The position of that error will be highlighted in red in your program code.
Now that you’ve successfully created, saved, and run your first Python program, it’s time to start digging deeper. In the chapter three, we will discuss the most common numeric data types used in Python programs, as well as the operations and functions associated with each.
INTERACTIVE – Do I really need to download Python?
It is highly recommend that you follow the instructions provided in this chapter to download Python to your computer. It is possible to create and run Python programs using your web browser. A website called http://trinket.io provides a full Python interpreter. We provide this plug-in along with some instructions in our Try Python page. You can give it a spin right now in the screen below. After you successfully run the “hello world” program, add another print statement to display your full name, and then run the program again.
Chapter Review Exercises:
2.1. Define the following terms:
a) Comment b) Float c) IDE d) Input function
e) Object-oriented f) Open source g) Parameter h) Portable
i) Print function j) Prompt k) String l) Syntax error
Programming Projects:
2.1. Many athletes are concerned with reaching their ideal training heart rate during their workouts.
- The maximum heart rate (MHR) can be found by subtracting your age from 220. It is recommended that the ideal training heart rate for exercise is between 55 and 85 percent of this MHR.
- Think about designing a solution that would ask a user to enter her age. Your program will compute and display her maximum heart rate, as well as the lower and upper range of the ideal training heart rate.
- 1) Write an algorithm to solve the problem. Save it as a Word document.
- 2) Draw a flowchart to model the solution to the problem. Save it as a PDF document.
- 3) Implement the solution to your problem as a Python program. Add 4 lines of comments at the top.
2.2. Suppose we wanted to know the average temperature on a recent 4-day vacation.
- Think about designing a solution that would ask a user to input four daily outdoor temperatures (in Fahrenheit), then compute and display the average of those four numbers..
- 1) Write an algorithm to solve the problem. Save it as a Word document.
- 2) Draw a flowchart to model the solution to the problem. Save it as a PDF document.
- 3) Implement the solution to your problem as a Python program. Add 4 lines of comments at the top.