ENGI E1006: Introduction to Computing for Engineers and Applied Scientists


Lecture 1: Introduction; programs as files

Reading: Punch and Enbody Chapter 1 (Chapter 0 is recommended)

Objectives

This course provides an introduction to computing in the context of engineering and applied science. We will use a Python programming environment to solve problems drawn from a variety of science and engineering disciplines. You will learn the basics of computer programming using Python but more importantly you will learn about the nature and power of algorithmic problem solving. The ultimate goal of this course is to teach you where to look for and how to acquire new tools for solving problems in your area of interest.

Course Materials

Textbook: The Practice of Computing Using Python by William Punch and Richard Enbody, Second Edition. it is available in the campus bookstore.

We will use courseworks to disseminate other course materials including assignments, handouts, examples, and notes.

Assessment

Homework:The course has five assignments. The first two involve multiple projects that are modest in size. The last three involve larger projects derived from the in-class case studies. It is very important to attend lectures for these since the appropriate solution approaches to these projects will be discussed in lecture.

Late Policy: All students are allocated 50 hours of grace time. You may use this time any way you choose. For example you can hand in one assignment 50 hours late, five assignments 10 hours late each, or you can not use the grace time at all. Any part of an hour late costs one hour of grace time. So an assignment submitted 61 minutes late will reduce your allotted grace time by two hours. This grace time is to be used for sickness, religious holidays, athletic events, hungry dogs, …, whatever. Serious family or medical emergencies that are communicated to me with supporting documentation will not count against your grace time. There are no other exceptions so use this time wisely. Any work submitted beyond the scheduled deadline + your grace time balance will not be accepted. The courseworks gradebook has an entry that lists your remaining balance. This will be updated after each assignment is submitted.

Exams: There will be one midterm exam on June 14 and a final exam on June 30.

Grading: Grades will be assigned using the following guideline:

  • 35% Homework
  • 25% Midterm Exam
  • 40% Final Exam

Academic Honesty: Please familiarize yourself with the below policies on academic integrity. For this course you must complete your homework on your own. These are NOT team projects and you must not submit solutions or partial solutions that you have found online or anywhere else. All academic honesty infractions will result in severe academic penalty and immediate reporting to the Office of Judicial Affairs.

Preliminary Definitions

Algorithm: A well-ordered sequence of operations that produce a result and halt in a finite amount of time.

Computing: The activity of using or creating algorithmic processes to complete some task.

Computer Science: The study of algorithms including their mathematical properties, their linguistic realizations, their physical realizations, and their applications.

A programming language is tool for precisely articulating an algorithmic solution to a problem so that it may be executed on a computer. Python is a powerful and widely used programming language. It is open source and has an active community of contributors. Because of this it is free, it is widely available, and there are many associated tools that are constantly being added and improved. A large number of these may be used for a variety of scientific applications. It is an excellent choice for a first language to learn.

Programming Environment

In this class we will use the Python (version 3.4) programming language. There are many freely available tools and other extras available for Python. The Anaconda scientific Python distribution is free and includes everything we will need for the semester. It will work on Mac, Windows, and Linux machines. You can download Anaconda here:

https://store.continuum.io/cshop/anaconda/

You should do this as soon as possible. Once you have installed Anaconda, begin familiarizing yourself with the interactive IPython QtConsole and with Spyder. To start we will use the IPython QTConsole for in-class demonstrations. As the semester progresses we will also use the Spyder development environment. Remember, all of these things come free with the Anaconda distribution of Python so don't pay for anything.

So let's get started!

One good way to start thinking about the activity of computing is as a manipulation of symbolic input that yeilds some symbolic output. Of course the devil is in the details. How do we represent information with symbols? How do we keep track of it? Let's start with some simple variable assignments and basic arithmetic. A variable is just a name for a container that can store variable values. What kind of values? They could be integers, floating point numbers (numbers with a fractional part), sequences of characters, booleans, and that's just for starters. Let's start with integers:

In [5]:
a=3
b=4
a+b
Out[5]:
7

Notice that when we write an expression the interactive Ipython console evaluates it.

In [6]:
a*b
Out[6]:
12
In [7]:
a/b
Out[7]:
0.75
In [8]:
(a+2)*(8/b)
Out[8]:
10.0

Question: Why is output [4] equal to 10.0 and output [2] is just plain 12 (and not 12.0)? What's the difference?

int: The Python data-type used to represent integers is int. When we add or multiply two integers we always get an integer back. Not necessarily so when we divide.

float: The Python data-tpye used to represent numbers with a fractional part is called float. This term comes from the scientific standard floating point notation which is a method used to represent numbers like these. When either operand in an addition, subtraction, or multiplication is a float, the result is a float.

In [9]:
 3.0*2
Out[9]:
6.0

The result of floating point division is always a float.

In [10]:
5/1
Out[10]:
5.0

str: A string is a sequence of characters. The Python data-type that represents strings is str. In Python we represent string literals as characters with single or double quotes around them. We can store strings in variables just like we do with numbers.

In [11]:
s="Happy happy joy joy!"
s
Out[11]:
'Happy happy joy joy!'

In many of these examples we have used the = symbol as an assignment operator. It's not the equal symbol you know from math class. This is different. It's an operator that assigns the stuff on the RHS to the variable on the LHS. Before we go on, it's time for some more formal definitins.

Language Elements

Data-type: Set of values and operations that may be used on those values.

Class: A computer representation of a data-type.

Object: A computer representation of a data-type value. Three parts: identity, type, value

Object reference: The location of an object in computer memory.

Literals: Symbolic representation of built-in number and string data-type values. Examples: _3, "happy".

Identifier: Symbolic representation of a name. In Python this is a sequence of letters, digits, or underscores. May not begin with a digit.

Variable: Conceptually this is just a name associated with a data-type value. So an Identifier is the Python symbolic representation of that name. More formally, in Python it is a location in memory that stores a reference to an object.

Operators: Symbolic representation of a data-type operation. Examples: +, /, //

Keywords: Reserved words that may not be used to name. These are the vocabulary of a programming language. Python has only a few dozen.

Delimiters (punctuators): Symbols used to separate language elements.

Statement: A logical line of code that performs some task.

Expression: A sequence of literals, operators, variables, and delimiters that evaluate to some value.

More built-in data types in Python

bool: The Python data-type used to represent Boolean values with values True or False (also 1 and 0). We may use use the boolean operators not, and, or in the usual way.

Other operators for integers and floats: |
// integer quotient

In [12]:
5//2
Out[12]:
2

% integer remainder

In [13]:
5%2
Out[13]:
1

** exponentiation

In [14]:
2**3
Out[14]:
8

list: The Python data-type used to represent a sequence of data-type values. A list is just an ordered set of objects. We can refer to elements of the list using common mathematical array notation but with the first index being zero.

In [15]:
l=[3,6.4,'happy', True]
l[0]
Out[15]:
3
In [ ]:
l[2]
Out[ ]:
'happy'

Files or Interactive?

Last time you were introduced to the Ipython interactive console. This is an extremely useful tool for observing features of the Python language and getting answers to short questions. A computer program is a list of the statements you have been using stored and organized in one or more plain text files.

file : A computer file is simply a self-contained unit of information on your computer. You can think of it as a chunk of memory if you like.

plain text file: A plain text file is a computer file that uses a very simple encoding to store basic characters. Usually plain text files that are meant for humans to read will be given the file extension .txt

We can store a sequence of commands in a plain text file. To denote that this is a Python computer program we use the file extension .py. You can edit a Python program in any plain text editor but some are more friendly than others.

What is Spyder?

Spyder is an integrated development environment for developing Python programs. What's that mean? For now we can think of Spyder as a really useful editor for our Python program files that has a built in Python interpreter to run our programs. It's important to remember that Spyder is not Python, it's just a nice tool for developing our software. There are many different IDEs to choose from. We will use Spyder since it's freely avilable and comes with the Anaconda distribution.

A word about built-in functions

Last time we mentioned that the Python language has only a few dozen keywords. So how are we able to accomplish so much with the language? Part of the answer is that Python comes with a huge library of stuff that other people of already coded for you. Some of that stuff comes in the form of functions. The built-in functions that we will use may seem so basic that you think of them in the same way as the keywords, but they are different.

In [ ]:
# *************************************
# Your name
# date
# file: input-output
#
# This program demonstrates basic input output operations
#***************************************


# first let's get some input from the user

name=input("What's your name dude? ")#I'm a happy in-line comment
fav_color=input("What's your favorite color? ")
fav_number=int(input("What's your favorite number? "))
fav_float=float(input("And like, what's your favorite non-integral number?"))

# now let's print what we have learned


print("What's up, ",name,"?")
print(fav_color, " is an awesome color!")
print("I hate the number ",fav_number,".")
print("What's so special about ",fav_float,"?")

# even better use outpout formatting
print()
print('Now using the format method')
print ("What's so special about {:.2f}?".format(fav_float))

What just happened?

input(): A built-in function that pauses the program to obtain user input from the console. It returns this input as a string. We call functions that return something, value-returning functions.

int(): A built-in function that returns an int. This function converts numeric strings (among other things) into integers.

float(): A built-in function that returns a float. This functiion convertis numric strings (among other things) into floating point numbers.

format(): A method for formatting strings. Notice the usage of format() is different than any of the built-in functions we have seen so far. That's because format() is a method. What's the difference between functions and methods? Methods are for use on sertain kinds of objects. Remember the definition of data-type involved a set of operations? methods are those operations as represented in Python. More on this difference later.

In [ ]:
# *************************************
# Your name
# date
# file: babyPiggybank.py
#
# This program determines the value of set of coins
#***************************************


# first let's get some input from the user

pennies=int(input("How many pennies you got mister?  "))
nickles=int(input("and nickles?  "))
dimes=int(input("and dimes  "))
quarters=int(input("and how many quarters you got misters?"))

# now let's compute the total

total = .01 * pennies + .05 * nickles + .1 * dimes + .25 * quarters


# even better use outpout formatting
print("pennies:{}, nickles:{}, total: ${:.2f}".format(pennies, nickles, total))

What just happened?
Nothing new here. Same as the previous example but this time we did a simple computation before outputing our result.

The math module

Recap:

  • Our Python programs are just plain text files that store our code.
  • There are very few keywords in python but we also have built-in functions.
  • Certain data-types also come with function-like things called methods. Methods and functions have important differences. We'll learn more about those later.

In addition to the built-in functions there is lots of other code that has been already written for us, just ready for us to use. This code is organized into modules. Think of a module as a single file with a bunch of related Python code in it (not necessarily true but a good way to think about it for now). One such module is the math module. This is a collection of useful math functions and constants. In order to use the math module we need to import it into our program. We can import in Ipython like this:

In [ ]:
import math
a=math.pi
math.sin(a/2)

Here is a link to documentation concerning the math module. Below is an example using some of the functions available in the module.

In [ ]:
# *************************************
# Cannon
# 2014
# file: math_stuff.py
#
# This program demonstrates the use of the math module
#***************************************

import math #this imports the math module

#constants in the math module
print('some constants')
print('pi: {:.4f}'.format(math.pi))
print('e: {:.4f}'.format(math.pi))

#some common functions
print()
print('some comon fuctions')
print('square root of 3: {:.4f}'.format(math.sqrt(3)))
# or we can use the pow function
print('square root of 4: {:.4f}'.format(math.pow(4,.5)))

#all of the usual suspects are here
print()
print('sin of pi / 2: {:.4f}'.format(math.sin(math.pi/2)))

print('to convert degrees to radians use degrees()')
print('pi is {:.4f} degrees'.format(math.degrees(math.pi)))

print('read more in the Python documentation!')
In [ ]: