FIND A SOLUTION AT Academic Writers Bay

Practical Session 1 – SIMPLE PROGRAMS & OPERATIONSPlease work through this lab sheet before completing the short assessed questions at theend.You should be able to complete the lab sheet and answer the assessed questionswithin 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 yourmachine, open it, and then launch Spyder.Part A: Writing and Running a Python ProgramWe are going to start off with the all-time classic code, Hello World. This is an instruction thatwill print the statement “Hello World” on the screen. The instruction is:print(“Hello World”)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. Oncecompleted and saved, this script or code is then “run”. This way suits morecomplex/longer algothrm and code development.2. Use the console (or command line): This is where instructions or commands aretyped in directly at a command prompt, and then executed straight away when youhit “enter”. This way suits short commands and quick answers.Writing a Python ScriptOpen Spyder. On the left screen you will typically see a script file available for edit. Let’screate 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 typeshould be a Python file (.py)3. Type in the above code (remember – be precise. The smallest error could stop yourcode 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 andthe subsequent result of you running this script.Executing the Command in a Console Window1. In the console window on the right-hand side of Spyder, type in the above codedirectly and hit enter2. The same result/output should then appear.That’s it!Simple VariablesMore than most programming languages, Python offers a great deal of flexibility in how wecan define and use variables. By writing code or using the console, try the followingexamples (in order) of using the variable x:x=”Hello world”print(x) (note there are no inverted commas here!)x=5x=x+5print(x)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 equationAx 2 Bx C 0areAB B ACx2 2 4The 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 asroots.py). This program asks for the coefficients (A, B, C) and then outputs the real roots.import math #1

print(“Input A, B, C”)a=input(“A? “)b=input(“B? “)c=input(“C? “)a=float(a)b=float(b)

# request coefficients

#2

#3

c=float(c)discrim = b ** 2 – 4*a*c # calculate discriminant# Calculate rootsROOT1 = (-b + math.sqrt(discrim)) / ( 2.0 * a )ROOT2 = (-b – math.sqrt(discrim )) / ( 2.0 * a )print(ROOT1, ROOT2)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 anumber. To use the value and do calculations with it, we have to convert it into anumber using float().Running the ProgramUse 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 (seeconsole window).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 combinationsA = 1, B = –5, C = 6A = 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 breaksdown 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 onthis next week). However, the simplest solution in this case is to import python’s complexmathematical function library cmath, rather than math, to allow the functions used in thecode 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 complexmath library rather than the standard)2. Replace math.sqrt( ) with cmath.sqrt( ), the complex equivalent to the standardsqrt function.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 complexversions of common and important maths functions like sqrt, sin, cos etc.PART C: ARITHMETIC OPERATIONSWithout importing libraries, Python has the usual arithmetic operations (+, -, *, **) and someother basic and unique intrinsic functions built-in. Try the examples below.Exercise: Using the console, test the following operations in Python and try to determinewhat each operation does (so that you could work it out yourself, without Python software, ifneeded):

(i)(ii)(iii)(iv)(v)(vi)

19 / 5 – 1.819 // 5 – 1.819 % 519 / 5 ** 1.8(19 / 5) ** 1.8abs(min(-2, 100, round(-2.51)))

……2.0…………….……1.2…………….……4……………….…1.0485945………..….11.05631679.…….………3…….……….

By importing the cmath library (type in import cmath), definex=((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 LISTSStringsAs indicated previously, strings (computing programming jargon for sentences and lettersetc) can be treated flexibly within Python. Strings are usually indicated between doublequotes, eg:print(“Hello world”) or perhapsx=”Hello world”print(x)In a string, n means take a new line, t inserts a tab space, \ is a single backslash.For example:x = “This sentence contains a tab t and a single backslash: \”print(x)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 theassessed question below. Remember, Python counts the characters in a string (includingspaces) starting from 0.ListsLists 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[0] returns value 1, x[2] 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 ofLab 1 Assessed Questions will help you learn about how a few of the list functions work.Lab 1 Assessed Questions1. In your head (before checking with Python), try to work out / determine the output Pythonwill give you for the following arithmetic operations. State if any operations are not possible.(i) 17 // 3 – 5(ii) 17 / 3 – 5(iii) 5**2**3(iv) 5**3**2(v) abs(max(-23,-5,-2))(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 useful3. For the string variables x=”Welcome ” and y=”to Manchester, friends”, determine theoutputs of the following operations, and briefly summarise what each operation does.(i) x+y(ii) x.upper()(iii) y.title()(iv) x + y.replace(“friends”, x)(v) x.find(“c”)4. For the lists x = [2, 4, “Polly”, 8, [3, 2]], y=[7, 9], determine theoutput/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):(i) x+y(ii) len(x)(iii) x.reverse()(iv) x.append(y)(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 1stNovember 2021.

- 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**

QUALITY: 100% ORIGINAL PAPER – **NO PLAGIARISM** – CUSTOM PAPER