An Introduction to Python For Undergraduate Engineers

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Contents

Authors

Matthew Johnson


Introduction

This wikibook is designed to act as an introductory course in Python aimed at non-programmers with a particular emphasis on the use of Python in solving and modelling engineering problems. It is written in such a way that it could form part of the teaching material used in a degree-level course in programming for engineers. It is meant to give non-programmers a fast, simple and straightforward route into creating Python programs to solve mathematical problems, but is not meant to be a comprehensive course in using the Python language. There are already some good wikibooks on Python, this is meant to be a quick start guide for engineers. Think of it as a springboard to bounce you straight into using Python quickly!


The key aims of this book are:

  • Expect no prior programming experience.
  • Be clear and straightforward to understand, keeping as non-technical as possible.
  • Get the reader programming as quickly as possible with plenty of examples.
  • Demonstrate that Python can be used to solve and model mathematical and engineering problems.


Installing Python

Python can be downloaded from the official Python website:

http://www.python.org/

If you are running Microsoft™ Windows™ then you can download a simple installation file from the downloads section of the official Python website and run that. If you are using a Linux distribution (such as Ubuntu, Debian, Red Hat etc.) you will most probably already have python installed.

Running Python

Windows™

In Microsoft™ Windows™ you can run IDLE which is a piece of software called a development environment, by clicking on Start Menu, Python, IDLE. This is a program in which you can write and run Python programs.

Linux Based Operating Systems

In a Linux operating system such as Ubuntu, you can simply use Python in the Terminal. You can write a python program using GEdit and saving the file with the ending '.py', for example:

filename.py

You can then run your program by typing the following in the terminal:

python filename.py

You must make sure your file is saved in the directory in which your terminal is in.

The rest of this wikibook shall assume that you are running Windows™ and using IDLE, everything is much the same in a Linux system or if you are running a Macintosh™.

Getting Started

Python can be run in two modes, the first is called interactive mode. This is where every command you type in is immediately interpreted by python and the result outputted onto your screen. For example type:

   print("Hello and welcome to python!!!")

This will immediately print 'Hello and welcome to python!' on your screen.

Alternatively you can use python in non-interactive (standard) mode. Write your lines of code into a file, save it and then run that file. This is convenient if your program starts to become large - otherwise you would have to type all the lines of your program every time you started using python.

When you first load IDLE, it is running in interactive mode. To write a program script (to save and run later), click on 'File; New Window'. Here you can write your program and save it. To run it you can either click on 'Run; Run Module' or press F5. Alternatively, you can run a python script by typing the following in a DOS Prompt (or in the Terminal on a Linux machine).

python myfilename.py

Python as a Calculator

Firstly, lets just quickly see how you can do simple arithmetic in Python. The table below list the basic mathematical operators and the associated code in python.


Function Code Example Result Function Code Example Result
Addition + 2+3 5 Multiplication * 5*6 30
Integer Division / 8/3 2 Floating Point Division / 8.0/3 2.666...
Remainder after division  % 8%3 2 Exponential ** 3**2 9


For more complex arithmetic, python contains a special module called math. This module contains an array of different functions (such as square root) and constants (such as pi). To use a module, we must first import it, like so:

   import math

We can then use for example:

   math.sqrt(16)    #to find the square root of 16.
   math.pi          #to get the value of pi.

Alternatively you can import modules in the following way:

   from math import *

This will import everything from the math module directly allowing us instead to call the functions as follows:

   sqrt(16) to find the square root of 16.
   pi to get the value of pi.

Numeric Data Types

In python, values can be saved as one of several different numeric data types. The main types that you will encounter to start with are integer values (whole numbers) and floating-point values. Note that python always rounds down to the nearest whole number when using integers. (This is due to be changed in python version 3). When you enter a value into python it will automatically decide what data type it is, so for example:

Typing 8 will create an integer value. Typing 8.0 will create a floating point value.

From thereon, python will treat that value as either an integer of floating (decimal) number.


You can convert between them using the int() and float() functions. For example:

   my_variable = 8    #Creates a variable and assigns it the integer value 8
my_variable_float = float(my_variabe) #Creates a new variable with a floating point value of 8.0

Notice that after a # symbol, the python interpreter ignores everything until the next line. This allows you to put comments in your code reminding you of what each line in your program is doing.

Rounding Numbers

The built in function round() will round a number up or down to the nearest whole number, for example:

   round(3.5) will return the answer 4.

Getting Inputs

If you want your program to get an input from the user (for example to enter some parameters for your program to use), we use the input("Message here") command, as follows:

   username = input("Enter your name: ")

When the program is run, this will show the user the message Enter your name: and will then save whatever the user inputs as the variable username. This can be very useful when writing a program to solve engineering type problems, as your program could ask the user to enter some parameters (such as mass, volume etc.) for your program to use.

Reading/Writing to Files

You may want your program to input/output data to/from a file. For example if your program calculates something repeatedly you may want it to store the value from each calculation in a file rather than let hem all print on screen. This can be done using the open() command. For example:

   datafile = open("data.txt",'w')

This creates a file called 'data.txt' and makes it available for writing (the w parameter). The file can then be accessed by your program using the reference 'datafile'. To write to the file we then use the write() command in the following way:

   datafile.write("Add this text to the file")

This will add the text in quotation marks to the end of the file. It is important that you use the following command to close the file when you are done. If you are using Windows™ and you don't do this, nothing will be written to the file!

   datafile.close()


Functions to read/write to files are shown in the list below:


Command Description
open("filename",'w') Opens a file and makes it available for writing to.
open("filename",'r') Opens a file and makes it available for reading from.
reference.write("text") Writes the text "text" to the file that is referenced to by 'reference'.
reference.readline() Returns the nex line of the file.
reference.read() Returns the entire file as a single string.
reference.readlines() Returns a list of strings. Each string is one line of the file.
reference.close() Closes the file.

Conditional Programming

If/else

Now that you have a few of the basic components under your belt, it is now the time to make some extra tools available to you. The most important part of a program is often the ability to get your program to do something if something is true (or false). For example if an inputted vaue is above a set value. For example:

   yourage = input(Please enter your age: )
   if yourage >= 18 
       print("You may continue...")
   else:
       print("You are too young..... go away!)

This little program will ask the user to input their age and then test whether it is greater than or equal to 18. If the user is old enough, a message saying continue is printed on screen, otherwise the user is told to go away!

The if statement will run a logical test and then run the commands after it if the test result is true. If the result is false, it will run the commands after the else: statement. If there is no else statement and the result is false, the program will do nothing.

You can add further tests before the else commands are run using the elif statement (stands for else if). It will act like another if statement after the first one until if all if test are false, then and only then will the else commands be run. For example:

   yourage = input("Enter your age: )
   if yourage >= 80:
      print("Hello gramps!")
   elif yourage >= 60:
      print("You can get your free buspass now!")
   elif yourage >= 40:
      print("Mid-life crisis due")
   elif yourage >= 18:
      print("Make the most of those looks whilst you still can!")
   else:
      print("Go back to school!")

If you are not quite sure what's going on try putting this into a script and running it in IDLE. See what message you get!

For Loops

For loops give you a way to repeatedly do something. This can be either a set number of times, or to repeat a part of your program several times, but each time with a different value of a variable each time.

   for i in [1,2,3,4,5]:
           print(i)

This will continually loop around, printing the value of i each time. This is a good time to quickly introduce you to two things, list and the range() command. As you have seen in the example, we can produce a list by using square brackets containing the values of our list, each one separated by a comma. For example, we can produce a variable and assign a list of values to it as follows:

   countlist = [1,2,3,4,5,6,7,8,9,10]

This variable is now of type 'list' and contains multiple entries. We can save ourselves the effort of writing out a long list just to count simply by using the range(startvalue,endvalue) command;

   countlist = range(1,11)

Note that the end value is 11, and not 10 as you might expect. This is because the range() does not include the end value. We can use this in our 'for' loop, as a quick way to repeat some part of our program with a list of values in a set range, for example:

   for i in range(1,20):
           answer = i**2
           print("The value of i squared is... " + str(answer))

This will tell you the value of i squared, starting with i=1, up to i=19. Note that we have had to use the str() command to get Python to print out the message and the value of 'answer'. This converts the integer value of 'answer' to a string, so that it can be added to the message (which itself is a string!). Give it a go and try playing around with different values and different calculations.

While Loops

While loops will repeat a section of code whilst a logical test is true.

Instead of repeating something with a defined list of values or a set number of times, a while loop will happily continue repeating its section of code until a logical test is satisfied. For example

   done = False             # Creates a variable and gives it the logical vlue 'False'
   count = 0                # Creates a variable and gives it integer value 0
   while done == False:     # Repeats following code until logical test no longer satisfied
       count = count + 1    # Adds 1 to value of count variable
       print("The value of count is... " + str(count))   # Prints value of count

The same code could also be written using != which means NOT EQUAL TO, for example:

   done = False             
   count = 0                
   while done != True:     
       count = count + 1    
       print("The value of count is... " + str(count))   

Boolean Logic

You can use simple boolean expressions in logical statements such as those that we used in the while loop. The avaiable expressions are:

Expression Example Decription of example
and while done==False and x<10: keep looping whilst both done equals false and x is less than 10
or if count=10 or value=5: do something if variable count=10 or the variable value=5
not while not done: keep looping while the done variable is not 'True'


Functions

Simple Graphics using EasyGui

Mathematics In Python

There are two main additional modules that enable us to use Python as a very sophisticated environment for dealing with algebra and numerical problems, these are the built in 'math' module and an additional module 'sympy', which can be downloaded from the internet (see the 'Getting Additional Modules' section at the end).

Remember that to use a module we must first import it using the import command, for example:

   from sympy import *

Symbolic Algebra

Before we can start any algebra, we must first tell Python what we want it to treat as symbols instead of numbers (x,y,z etc.). We do this in the following way, having imported the sympy module:

   x = Symbol('x')

Note that it is important to use the capital S otherwise this won't work. What we are doing here, is telling Python to create a new variable x and to assign the value 'x' to it. This way, it won't treat it as a numeric value, but just the symbol x. The module sympy.abc contains all the letters of the alphabet as premade symbols.

We can then create a variable that is a function of x. In this case I shall call the variable that will contain the function, myfunction;

   myfunction = x**2

If we ask python what the value of myfunction is (by typing just 'myfunction'), we get the equation that we put in. Now, we can substitute a value for x into the equation by using .subs(old value, new value), for example:

   myfunction.subs(x,5)

This will replace x with 5, making the value of myfunction 25.

Differentiation

Integration

Matrices

Matrices can be created in the following way:

   mymatrix = Matrix([[1,2],[3,4]])

In this example, [1,2] produces the first line of the matrix and [2,3] creates the second.

Quick Standard Matrices

The following built in functions can be used to quickly create some standard matrices of specified size.

Command Description Example
eye() Identity Matrix eye(4) creates a 4x4 identity matrix
zeros() Empty Matrix zeros(2,3) creates a 2x3 matrix of zeros
ones() Matrix of 1s ones(2) creates a 2x2 matrix of ones

Getting the Size of a Matrix

You can find out the size of a matrix using the .shape[] command, for example:

   mymatrix.shape[0]
Command Description
.shape[0] Gives number of rows
.shape[1] Gives number of columns



Getting Additional Modules

EasyGui Sympy

Recommended Reading

Wikibooks

Non-Programmer's Tutorial for Python

Textbooks

Computer Science: The Python Programming Language, Miller & Ranum, Jones & Bartlett Publishers, ISBN: 0-7637-4316-X

This is a good, quick way to get into the basics, but won't really give you much more detail than this wiki.

Python Programming: An Introduction to Computer Science, John Zelle, Franklin Beedle & Associates, ISBN: 1-887902-99-6

This is a more thorough book that covers more detail, however it is written as a way of learning computer science using Python as a starting language and so may not directly relate to programming in engineering. Nevertheless if software design is closer to your interests/needs then this might be the book for you.


References

The following references have helped the author(s) to learn python and are recommended for study if you wish to pursue python further. This wikibook is intended only as a short course to get you started with python. There is much more you can learn and a great deal more that you can do with it! Good luck!

http://www.python.org/