Practical Session 1 – SIMPLE PROGRAMS & OPERATIONS
Please work through this lab sheet before completing the short assessed questions at the
You should be able to complete the lab sheet and answer the assessed questions
within the allotted lab time (and are strongly encouraged to do so).
We will be using the Spyder IDE within the Anaconda Python distribution in labs:
available on cluster machines and at home by downloading Anaconda
(https://www.anaconda.com/products/individual). Look for Anaconda Navigator on your
machine, open it, and then launch Spyder.
Part A: Writing and Running a Python Program
We are going to start off with the all-time classic code, Hello World. This is an instruction that
will print the statement “Hello World” on the screen. The instruction is:
There are two ways to do this in python:
1. Write a script (or code) to run: This creates a python file (.py – like the MATLAB
.m) in which you write your instructions and commands for later execution. Once
completed and saved, this script or code is then “run”. This way suits more
complex/longer algothrm and code development.
2. Use the console (or command line): This is where instructions or commands are
typed in directly at a command prompt, and then executed straight away when you
hit “enter”. This way suits short commands and quick answers.
Writing a Python Script
Open Spyder. On the left screen you will typically see a script file available for edit. Let’s
create and save a new one:
1. Click (towards top left) to create a new file.
2. Click file, then save as… to save this script somewhere – remember the file type
should be a Python file (.py)
3. Type in the above code (remember – be precise. The smallest error could stop your
code from running).
4. Once you are sure you have input your code correctly, click “Run File” (green arrow).
5. Within the console window, you should see the equivalent console commands and
the subsequent result of you running this script.
Executing the Command in a Console Window
1. In the console window on the right-hand side of Spyder, type in the above code
directly and hit enter
2. The same result/output should then appear.
More than most programming languages, Python offers a great deal of flexibility in how we
can define and use variables. By writing code or using the console, try the following
examples (in order) of using the variable x:
print(x) (note there are no inverted commas here!)
What happens if you do these again, but skip the middle operation (i.e. skip setting x=5)?
We get an error because x is a string, and we can’t add 5 (integer) to a string.
Part B: A SIMPLE PROGRAM: Quadratic-equation solver (real roots)
The well-known solutions of the quadratic equation
Ax 2 Bx C 0
B B AC
The roots are real if and only if the discriminant, B2 4AC , is greater than or equal to zero.
A Python code to calculate the above is given below (also downloadable from Blackboard as
roots.py). This program asks for the coefficients (A, B, C) and then outputs the real roots.
import math #1
|print(“Input A, B, C”)
|# request coefficients|
discrim = b ** 2 – 4*a*c # calculate discriminant
# Calculate roots
ROOT1 = (-b + math.sqrt(discrim)) / ( 2.0 * a )
ROOT2 = (-b – math.sqrt(discrim )) / ( 2.0 * a )
Exercise: At the numbered hashtags (eg #1 etc), try and identify what is going on and why.
#1: The math library is imported to allow us to use intrinsic functions like sqrt
#2: The input command prompting the user to input a value for coefficient B.
#3: The input command reads in the keyboard entry as a string (character), not a
number. To use the value and do calculations with it, we have to convert it into a
number using float().
Running the Program
Use the green arrow to run the program.
When you run the code, it will ask you for the three coefficients in turn: A, B and C (see
Try A=1, B=3, C=2 (i.e. x2 3x 2 0 ). The roots should be –1 and –2 – check this now.
(Type the numbers into the console window on the right when prompted, followed by enter).
Now try the combinations
A = 1, B = –5, C = 6
A = 1, B = –5, C = 10 (What are the roots of the quadratic equation in this case?)
You will have noticed we have used an intrinsic python function “math.sqrt”. This breaks
down and gives an error for the case above as we will have complex roots.
There are a couple of solutions here. An if statement is possible (see notes – and more on
this next week). However, the simplest solution in this case is to import python’s complex
mathematical function library cmath, rather than math, to allow the functions used in the
code to deal with complex numbers.
To extend use to complex numbers, modify the roots.py code in the following way:
1. Replace import math with import cmath (tell python you want to use the complex
math library rather than the standard)
2. Replace math.sqrt( ) with cmath.sqrt( ), the complex equivalent to the standard
Try the above combination of A, B, C again. What do you get?.. (2.5+1.9364916731037085j)
(2.5-1.9364916731037085j)..in the complex case………………………………….
Both the math and cmath libraries are very popular and provide the real and complex
versions of common and important maths functions like sqrt, sin, cos etc.
PART C: ARITHMETIC OPERATIONS
Without importing libraries, Python has the usual arithmetic operations (+, -, *, **) and some
other basic and unique intrinsic functions built-in. Try the examples below.
Exercise: Using the console, test the following operations in Python and try to determine
what each operation does (so that you could work it out yourself, without Python software, if
|19 / 5 – 1.8
19 // 5 – 1.8
19 % 5
19 / 5 ** 1.8
(19 / 5) ** 1.8
abs(min(-2, 100, round(-2.51)))
By importing the cmath library (type in import cmath), define
x=((1+2j) * (3+4j)) and determine the following:
(vii) 1j*1j ……-1+0j…………………….
(viii) x.real ……-5.0…………………….
(ix) x.imag …………10……………….
PART D: STRINGS AND LISTS
As indicated previously, strings (computing programming jargon for sentences and letters
etc) can be treated flexibly within Python. Strings are usually indicated between double
print(“Hello world”) or perhaps
In a string, n means take a new line, t inserts a tab space, \ is a single backslash.
x = “This sentence contains a tab t and a single backslash: \”
Note, if you want quotes to appear in your string use: ”
There are plenty of intrinsic functions for manipulating strings – some of these are part of the
assessed question below. Remember, Python counts the characters in a string (including
spaces) starting from 0.
Lists are a useful data type that can contain a range of other types, eg numbers, strings,
even other lists. For example, a list x might be defined as:
x = [1, 2, “Steve”, 4, [1, 2]]
The first element is labelled 0, so entering x returns value 1, x returns ‘Steve’,
etc. One can also count back from the end of the list, with -1 labelling the last element, eg,
x[-1] contains [1,2], x[-3] contains ‘Steve’.
As with strings there are a number of intrinsic functions for list manipulation. Below, Q4 of
Lab 1 Assessed Questions will help you learn about how a few of the list functions work.
Lab 1 Assessed Questions
1. In your head (before checking with Python), try to work out / determine the output Python
will give you for the following arithmetic operations. State if any operations are not possible.
(i) 17 // 3 – 5
(ii) 17 / 3 – 5
(vi) 24 % 5 % 5 / 4
(vii) len(“good day”) % len(“afternoon!”)
2. Write the single Python command that prints the following string (note the new line)
This unit is “great”,
coding with Python is so useful
3. For the string variables x=”Welcome ” and y=”to Manchester, friends”, determine the
outputs of the following operations, and briefly summarise what each operation does.
(iv) x + y.replace(“friends”, x)
4. For the lists x = [2, 4, “Polly”, 8, [3, 2]], y=[7, 9], determine the
output/results of the following operations, and briefly summarise what each operation does
(note for parts (iii)-(v), you have to print the list after the operation to see the result):
(v) y.insert(1, 5)
Submit your answers to the “Python Lab 1 Assessed Questions” link on Blackboard.
Note: the questions require you to enter values or statements into a Blackboard test. In total,
the Lab 1 assessed questions are worth 5% of the unit mark.
All answers must be submitted by the final python coursework deadline: 6pm 1st
- Assignment status: Already Solved By Our Experts
- (USA, AUS, UK & CA PhD. Writers)
- CLICK HERE TO GET A PROFESSIONAL WRITER TO WORK ON THIS PAPER AND OTHER SIMILAR PAPERS, GET A NON PLAGIARIZED PAPER FROM OUR EXPERTS