Вы находитесь на странице: 1из 7

7/6/2019 Introduction to Python

Introduction to Programming in Python


The goal of these notes is to help you to learn how to program. We will be using the programming language
Python, but you will be able to use the skills you learn here with other programming systems such as Matlab or
R.

Programming is a very important and useful skill for an engineer. Almost any job these days requires interaction
with computer systems and many will require some level of programming. Engineering companies increasingly
want to employ people with programming abilities and the ability to automate tasks with program scripts.

The skills you learn here can be used in automation of processes, computation of complex problems, control of
equipment, instrumentation for making measurements, data analysis and producing figures of results.
Additionally it can vastly speed up processing batches of text documents, accessing online data sources and any
other task that would take unreasonably long times by hand.

Why Use Python?


Python is good to learn how to program because it has a clear structure and syntax compared to many
programming languages.
It is easy to use it to get started with basic programming and from there it is possible to gradually teach yourself
how to do much more advanced programming.

How To Use These Notes


To make the most of these notes it is important that you read through each section,
enter and actually do all the examples and attempt the problems in the Problem Sets.

You will have to return to earlier section as you work your way through.
Make your own notes, especially when you get stuck or something is not clear.
This will be helpful when you return to a problem later and also when you have questions.

Some tips:

Try to predict what the output will be before running the examples. You should try to think through the
steps of how the computer works through your programs.
It is often useful to work out some ideas with pen and paper before you start entering code.
Test your code. Always try a simple version of your program on examples where you know what the
coutcome should be.
Ask questions to yourself such as:
"What would happen if I tried this?"
"Are there any input values for which the program does not work or gives the wrong answer?"
"Will someone else be able to understand the code I have just written?"
"Will I be able to understand this code in a few weeks time?"
Finally experiment! Instead of asking "what will happen if...?" or "will this work?", just try it and see
what happens. You are unlikely to break the computer by trying something out!

https://people.bath.ac.uk/nm268/progpy.bho/Introduction+to+Python.html 1/7
7/6/2019 Introduction to Python

Installing Python
Some computer systems come with a basic Python setup already installed. However, you should make sure you
have your own version of Python which includes some useful extra packages and an editor or Integrated
Development Environment (IDE) to write and run (execute) your Python scripts.

The quickest way to obtain a complete Python system is to install a Python distribution such as Anaconda
Python.

Download Python Version 3 here:


https://www.anaconda.com/distribution/#download-section (https://www.anaconda.com/distribution/#download-
section)

Python Versions
In these notes we use Python 3.7.

Python 3 was developed to clean up the design of the language.


Python 2 and Python 3 are mostly the same, but there are some important incompatibilities, which means some
code downloaded from the internet may need editing.

Running Python
Python is a text-based programming language where you give the computer lines of *instructions* (or *"code"*)
that are interpreted and run (or "executed") by the Python interpreter. These can be entered one line at a time on
a *commandline* interface, or as a sequence of instructions written as a *programme* or *"script"*. In these
notes we will concentrate on writing scripts, as these are more useful in the long run.

https://people.bath.ac.uk/nm268/progpy.bho/Introduction+to+Python.html 2/7
7/6/2019 Introduction to Python

Spyder
This is an Integrated Development Environment (IDE) specifically designed for Python programming combines a
programming text editor with a command line interface. We can write and run a code using the same program as
well as see the output including any graphs directly. The interface looks and functions a lot like Matlab, making it
easier to transfer between the two.

See this guide for instructions on how to get this working: http://tinyurl.com/bathspyder
(http://tinyurl.com/bathspyder)

After the program loads (it may take a few moments) the following should appear:

On the left you see an editing window for writing program scripts.

On the right are two panes:

the top one shows various information and


the bottom one shows any output from running the Python script, and can also be used to enter single-
line commands.

You may want to drag the bar in between the panes to resize them.

https://people.bath.ac.uk/nm268/progpy.bho/Introduction+to+Python.html 3/7
7/6/2019 Introduction to Python

Jupyter Notebook
Jupyter Notebook is another interactive environment for running blocks of Python code. It runs in a web browser
and output is displayed inline for ease of use and visibility. Individual parts of the code can be put into their own
blocks and run separately or all in sequence. The complete code can be saved as a python script .py file to be
run by other people or as a web-pahe (html) or a pdf for a report.

The instructions for this are included on the same link as above.

First Exercise
Click on the bottom right hand console and type the following in front of the command prompt and press return:

In [1]: print("Hello World!")

Hello World!

The output should appear as above.

next type the following and look at the output after hitting return:

In [2]: 7*6

Out[2]: 42

https://people.bath.ac.uk/nm268/progpy.bho/Introduction+to+Python.html 4/7
7/6/2019 Introduction to Python

Typing commands this way is a quick way of doing calculations and running commands, but if you want to do
many in a row or repeat a task then it's better to save them in a file and run then from there. This is called a
script or program.

Writing a Script
A script file is a text file containing lines of code to be executed. The Python *“interpreter”* reads through the
script line by line and executes the instructions in order, unless an error is encountered. An example is given
below. The result of executing the script is shown underneath the code. In this case, the sentence “Hello World!”
will be displayed. We will use the terms script file and program interchangeably.

#hello_world.py

print(42)

print("Hello World!")

42
Hello World!

The first line, starting with #, is a comment. All comments are ignored by the Python system, but they are
nevertheless a very important part of a program. They can help you and others understand the program. The
comment in the example gives the name of the file containing the script, but this is not neccessary, just helpful
information.

https://people.bath.ac.uk/nm268/progpy.bho/Introduction+to+Python.html 5/7
7/6/2019 Introduction to Python

Exercise:
Create a new python script file using the instructions in http://tinyurl.com/bathspyder
(http://tinyurl.com/bathspyder) and the video lecture and type in all the three lines of the above code. Save the
file using the name hello_world.py. Note the underscore _ is used not a space,

Never use spaces in program filenames!!!

Run this example by pressing F5 or the green run button (if you added it).

As you may have already noticed, it is important to type in exactly the right commands. This is a good point to
investigate what happens when something goes wrong when entering a program. Make a note of your
observations.

Exercise:
Remove the hash symbol (#) in the first line of the program and run the program again.
Remove one or both of the double quotes (").
Replace the print function by pint.

You will see that the Python system tries to provide helpful error messages to help you figure out what went
wrong. Interpreting error messages and finding and fixing errors in programs is a crucial part of programming.

https://people.bath.ac.uk/nm268/progpy.bho/Introduction+to+Python.html 6/7
7/6/2019 Introduction to Python

Types of Errors
There are three main types of errors:

Syntax errors: these will be detected when a program is read in by the Python system. An example of
a syntax error is the use of pint instead of the print command in the example program. Syntax errors
are reported by error messages.
Runtime errors: these will be detected when the program is run. An example of a runtime error would
be attempting to divide by zero or attempting to read from a file that does not exist. Add a line
print(1/0) add the end of the example program and run it again. Note that the symbol / denotes
division. Runtime errors are reported by error messages.
Logical errors: these are errors that cause the program to run but give the wrong result. Logical errors
will not necessarily cause the program to stop with an error message. A very basic logical error in the
example program would be any typo in the string Hello World. The program would still run, but it
would give the wrong result. Try replacing the line ~print “Hello World!”~ with ~print “Hello Word!”~.
Many logical errors can be detected by careful testing of a program.

An error message will usually contain an indication of where in the program the error occurred. Sometimes the
real error may be on a earlier line than the one indicated in the error message.

To tackle errors when they happen try to look at the error message and identify the line where the first error
occurs. Read the message carefully and compare it to your code to try to identify the problem. If you cannot
figure out what it means then try typing the error message into google and looking at the suggested answers on
web forums such as *stackexchange*.

Another way to debug code is to comment out lines using # a the beginning of a line, so that the interpreter
ignores them. Then you can identify which line is giving the problem.

If there is no error message but your code does not work properly it can be a good idea to insert print()
functions in different places to see if the code is performing calculation steps as expected.

https://people.bath.ac.uk/nm268/progpy.bho/Introduction+to+Python.html 7/7

Вам также может понравиться