# Python Programming Language

#### By Mark Ciotola

First published on February 27, 2019

# Python Programming Language

### By Mark Ciotola

First published on February 27, 2019

## Course Objectives

• To gain a general understanding of how to use Python
• To learn about Python variables, operators, control structures and output.

## Course Objectives

• To gain a general understanding of how to use Python
• To learn about Python variables, operators, control structures and output.

## Introduction

Python is a programming language that is meant to be highly readable and relatively easy to learn. It is not quite easy as Ruby, but Python fit useful for many specific applications, such as image processing.

Guido van Rossum created Python in 1991 by.  Van Rossum was trained as mathematician,  and the Python language reflects his background. Python is useful for many applications, and has many libraries written for it, often making your task as a programmer easier. Python is a mathematically robust, versatile language, especially for applications that do not require extreme speed or high performance.

This course is being initially written for computers that use Linux or Unix. Other operating systems might be added in the future.

## Using Python

To use Python, you need way to create programs and then to run them. (You can also run pre-existing programs). You can write Python programs in most text editors. However, you will need Python installed on your computer to run those programs.

Your computer might already have Python. To find out, open a terminal window and type the following command.

python -v

If you have Python installed, the version and other information will be returned. If not, you will need to install Python. Get Python from this link:

Python.org

After installing Python, try out the above command to confirm that Python is installed and working. If not, follow the instructions on the Python.org site (or try web searching for any error messages that you receive).

## Hello World Program

If you have Python, you can try a Hello World program. Examine a simple Python program called HelloWorld.py

print 'Hello World!'

This is a simple program. There are no special structures, so no indentation spaces are required. The file name would end in .py

Create your program in a text editor and name it: HelloWorld.py

To run the program. type into your terminal:

python HelloWorld.py

The output should be:

Hello World

Congratulations if you can create this program and run it. You are now a Python programmer!

## Leveling Up

• Modify the program by writing additional lines of text.
• Ask yourself, how is a computer program different from a web page? (Keep this question in mind as you learn more.)

3. ## 3. A Simple Math Program in Python

Python was written with mathematics in mind, so let’s examine a simple math program. Several important new concepts will be introduced.

First, it is important to document your code. This will help you remember why you wrote things a certain way, and it can help other people better understand your program. In Python, lines that begin with “#” are treated as comments. Python won’t do anything with code after the # on a single line.

# This is a comment.

Second, is the concept of the variable. Unlike states text, such as “Hello World”, variables can change. However, they don’t change by themselves. Youhave to first assign them a variable. Then you can change them later. In the following program, “x” is variable.

# x is assigned a value
x = 1

Third, you can perform operations to change, combine or compare variables. In the program below, we use the “+” operator to combine the variable x with the constant 5.

# x is assigned a value
x = 3

# x and 5 are combined
y = x + 5.0

# Result is displayed
print('Y = ', y)

The above program assigns a value to x and then adds 5 to x. The result is displayed as y. When writing calculations in code, we often want the result to be a decimal. Writing the 5 as “5.0” will tell the program that we want a decimal calculation. Each language may handle this differently, but it is a good habit to get into the habit of adding the “.0” or else you will face many hours of grief in the future.

## Activity

• Write and run the above program. Save it as MyMathProgram.py
• Try out initial values for x. Your final result should change for each different value of x.

## Leveling Up

• Create additional variables and calculations, and display multiple values in the same line of results.

## Data Types and Variables

Programs manipulate and display data and information. Computers ultimately work with numbers, but words can be represented by numbers. High level computer programming languages translate words to and from numbers, so if you want to use words, you can usually do so without bothering with numbers. Most programmers will want to use both.

Some information does not change in a computer program. That information is called a constant. Words can be constants, but usually the term is applied to numbers, such as 7 (days in a week) or 12 (months in a year). Items that do change, such as days in a month or the current sum of a financial account, are called variables.

Variables are represented by names, such as MyDate or CurrentSum. There are rules about what names can be used.

In some programming languages, a variable must be declared and a type must be assigned before using it. In Python, variables are dynamically typed, which means that Python will guess what type is best based upon how you use it. You will often need to pay attention to this.

Python names must start with a letter or an underscore (“_”). Python variables should not start with a number, although they can contain numbers. Python variables are case sensitive, so “MyVariable” is not the same as “myvariable”.

5. ## 5. Python Operators

Operators allow a language to combine, change, and compare variables. Mathematical operators produce a numerical result. Below are several mathematical operators you might frequently use.

 Operator Function + Addition – Subtraction * Multiplication / Division ** Exponent

There are several comparison operators. Unlike math operators, the result of a comparison operator is “true” or “false”. Below are several comparison operators you might frequently use.

 Operator Function > Is the first value greater the second value? < Is the first value less the second value? == Are the two values equal? != Are the two values not equal?

Here is another Python program that uses several operators.

x = 10
y = 5

print 'Inputs: x =', x, 'y =', y

z = x + y

if (z < 20):

print 'Result:', z

print 'Done.'

The first few lines create the variables x and y, and assign values to those variables. Strings to be printed should be enclosed in single quotes. Variables to be printed are simply indicated by their variable names. All of the different elements to be printed should be separated by variables. Math operations are straightforward. The results of a calculation can be assigned of a new variable. They can be assigned to an old variable, but doing so changes the value of the old variable (this is useful for updating variables).

## White Space

One way that Python is readable is that it uses spaces (white space) for certain structures. This results in less jargon and well-organized program text. However, if you do not follow white space rules, your program will often not work. Some parts of control structures must be indented, such as parts of a control structure that are dependent upon the result of the condition. The result must be indented with four spaces (or one tab). Python is extremely particular about indenting. In the example above, a print statement is indented under the if statement.

6. ## 6. Control Structures

Control structures are used to make various things happen, typically depending on particular conditions. These are also called decision structures. The program examines one or more conditions, decides on a part of action to take, then executes that path. A control structure typically starts with a condition statement (which acts as a question). For example, the program might ask if a certain thing is true, such as if a variable is over 20. Then the control structure will state a course of action (path) if the condition is true. Sometimes there will be an alternate path if the condition is false. Some control structures allow for multiple conditions.

## White Space

One way that Python is readable is that it uses spaces (white space) for certain structures. This results in less jargon and well-organized program text. However, if you do not follow white space rules, your program will often not work. Some parts of control structures must be intended, Typically the indentation is four spaces or one tab.

### White Space Example

Below is an example of a simple control structure. It does something as long as x is in the range. This is useful where x does not merely increase iteratively, but rather represents some situational quantity encountered, such as the size of an image. Also notice the the action is intended to indicate that it is performed as part of that control structure. Without the indentation, the action would be executed regardless of the result of the control condition.

for x in range(0, 100):

# Do something.


7. ## 7. Loops in Python

Computers tend to be great at repetitive tasks. Further, repetitive tasks are relatively easy to program. You write code for the task once, then you place that task in a loop. A loop will try to repeat itself forever, but you usually don’t want that. So you write a control structure with a condition statement. Either the loop will run while the condition is true, or it will stop when the condition is true, depending on how the structure is written.

Below is a conditional loop statement. It will continue to increase the production until the step variable has reached the value of 10. The step +=1 increases the step variable by 1 each time this loop runs.

# Initialize variable
production = 1.0
step = 1

# Run loop
while(step < 10): # Condition statement
production = production * 2.5
print 'Production =', production
step += 1

## Activity

• Write and run the above program.
• Modify the program to run for exactly 30 steps.

## Leveling Up

• Write a loop within a loop. This is a common programming practice. For example, the top level loop might run a calculation that occurs for each country, while the second level loop might run a calculation that occurs for each province to state.

8. ## 8. Output

Formatting in Python is not simple. However, it is not so bad, once you get the hang of it. Further, the way to format Python output has changed in newer versions of Python, so some examples online might be out of date. (However, the old approach may still work for your purposes, and there are some reasons to still use the old approach). We will show the new approach here. (If it doesn’t work for you, web search the old approach).

## Simple Approach

The simplest approach to Python output is that which we have already used: the print statement. Remember that items must be separated by a comma, and text strings must be enclosed in single quotes.

print 'These are my result:', x, y, z

The old method is discouraged, but sometimes it is just too useful to pass up. It is useful for formatting short strings and numbers, especially for the rows and columns of scientific computations in a loop.

The approach is to state a string, with format expression for the variables, then stating the variables. You assign the formatted string to a new variable, then state the new variable.

Here is an example:

annualGrain = 500849.37865
mystring = 'Annual grain production is: ' % 6.2f (annualGrain)
mystring

Which will output:

Annual grain production is: 500849.38


## New Method

Sometimes the simple print method is insufficient for your output or display requirements. In that case, you will need Python’s more advanced output formatting features.

The formatting statement comprises two parts: placeholders for the content and the content itself. Placeholders are a {} for each content item, all of which are enclosed together in single quotes. The placeholders are followed by a “.format” followed by the content items separated by commas, all enclosed together in parentheses. Here is an example:

'{},{}'.format("Hello","World")