0% found this document useful (0 votes)
11 views11 pages

Python Programming Workshop Tasks

The workshop aims to introduce programming concepts using Python, focusing on structured instructions and practical exercises in Jupyter Notebook. Participants will complete various exercises to demonstrate their understanding of Python syntax, data types, and basic programming logic. The workshop encourages collaboration, feedback, and iterative submission of work for improvement.

Uploaded by

Kaeden Good
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views11 pages

Python Programming Workshop Tasks

The workshop aims to introduce programming concepts using Python, focusing on structured instructions and practical exercises in Jupyter Notebook. Participants will complete various exercises to demonstrate their understanding of Python syntax, data types, and basic programming logic. The workshop encourages collaboration, feedback, and iterative submission of work for improvement.

Uploaded by

Kaeden Good
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

workshop1tasks

September 24, 2024

1 Programming for AI & Data Science

2 Workshop 1
2.0.1 Aims of the workshop
The aim of this session is to introduce you to the concepts of programming by initially writing
structured sequences of instructions. After that we will quickly get on with using Python, first with
the Python Interpreter and then using the Jupyter Notebook environment, which we’ve briefly seen
this week. This workshop will serve as an introduction to programming and Python, putting into
practice all that we’ve covered this week. It is important to take time to understand these basic
concepts, and explore what they can do.
The concept behind this workshop is about discovery, and experimentation surrounding topics
covered so far.
Feel free to discuss the work with peers, or with any member of the teaching staff.
You should use this Jupyter Notebook to develop and store your solutions to the exercises. Once
you have completed this weeks tasks you should submit the workshop results to Canvas (not one at
a time), but you can resubmit each weeks results as many times as you need to perfect any points
that you may need to improve. You will get feedback from your teachers after each submission.
You can copy material from this page into Canvas either by copying text from the screen or using
the screen copy tool. On Microsoft Windows the “Windows Snipping Tool” can extract pieces of
your screen using CMD-SHIFT-S (�-SHIFT-S) together and it will change the cursor from an arrow
to a crosshair. On an Apple Mac the �+�+4 will copy an image of a section of the screen. Text
can be copied on Microsoft Windows using ctrl+c and pasted with ctrl+v (or by using the copy
and paste menus on the mouse cursor). On an Apple Mac use the � instead of ctrl, but otherwise
it works the same way.

2.1 Useful Information


Throughout this workshop you may find the following useful.
Python Documentation
[Link]
This allows you to lookup core language features of the latest versin of Python as well as tangential
information about the Python Language.

1
2.2 Exercise 1 : Using the Python Interpreter
The following seven exercises will be performed using the command line Python interpreter and
should not be done in Jupyter. You should paste the whole transaction from the Python command
line into the results box as a record of your code commands and the results. (The first task is a
repeat of an exercise from the welcome week workshop, but is repeated here to ensure all students
complete this essential task.)
Remember, you can launch the interpreter by opening a command prompt and typing
python
If you are not sure how to open the command prompt, try typing cmd into the search bar if you are
using a Windows machine in the DAIM lab. The next seven Exercises are designed to demonstrate
you familiarity with the Python shell and should not be done in Jupyter. Be sure you include
the lines that show which version of Python was used, the command and the output.
When prompted, type print(“Hello World!”) this should enter Hello World! On the line imme-
diately afterwards. This is the output of the expression:
C:\Users\Brian>python
Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (
AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World!")
Hello World!
>>>
Congratulations! You’ve just run your first Python command.
Paste the text showing results in the cell below as you should be keeping this Jupyter notebook as
a record of your work. You should also, when all the exercises are completed, copy these results
into the Canvas quiz, so they can be graded by your tutor. —- Paste the text of your command
prompt showing your results here
—-

2.2.1 Exercise 2:
We can use type() to check the type of any value. We simply provide the value to type, between
the parentheses.
E.g. type(932) Try this in the command line Python interpreter? What do you get out?
Hint: We don’t need print in this case with the interpreter, because it is outputting it for us. If we
executed this code in a .py file, this would not be the case. Any expressions which have a value
will be spit back to us.
Using your knowledge of the other basic types we introduced, check some examples of these values
with type().
Paste the entire transaction below from the python command prompt below. Be sure to show the
code and output: —- Paste the text of your command prompt showing your results here
—-

2
2.2.2 Exercise 3:
We covered casting a value from one type to another. An example of this might be treating the
integer 932 as a float.
1. Write an expression which casts 932 to the type string (shortened to str)
2. Verify the type output from the step above. Hint: We don’t need to use any variables yet.
Remember, type() can take any expression which provides a value.
Paste the entire transaction below from the python command prompt below. Be sure to show the
code and output: —- Paste the text of your command prompt showing your results here
—-

2.2.3 Exercise 4:
For the following expressions, what are the types of the two inputs values, and what is the type of
the result of executing the expression. Try to answer these first without writing code, then write
some Python to verify if you are correct.
1. 3+4
2. 3.0 + 4
3. 37 % 7 ** 2
4. ‘bob’ + ‘cat’
5. “bob” / “cat”
6. “banana” + “na” * 20
Do any of these combinations surprise you? Try other operators which you know, and some other
data types.
Paste the entire set of transactions from the command prompt below: —- Paste the text of your
command prompt showing your results here
—-

2.2.4 Exercise 5:
This question explores the difference between arithmetic in computer code and arithmetic taught
at school. You are given the following mathematical expression
12 + 28 / 7 * 2
Using your understanding of PEMDAS (or BODMAS):
1. What would be the result of such an expression? Which numbers are calculated together first
2. What would be the overall type of the result?
3. How might we use parentheses to make this expression less ambiguous? Remember, the
expression must still return the same value!
—- Write your answer here
—-

3
2.2.5 Exercise 6:
Create some variables (name of your choosing) to store the values 42.0 and 97.
1. Calculate addition, subtraction, divide, and multiply operators on these. (E.g. a * b)
2. Using the expressions from above, create a new variable which is assigned thatexpression.
(E.g. product = a * b). Do this for all your variants.
3. Print your new variables. (E.g. print( product ))
Paste the entire transaction from the python command prompt below showing both code and
results: —- Paste the text of your command prompt showing your results here
—-

2.2.6 Exercise 7:
Pick your favourite expression from Ex 5. Take any variable from a previous exercise which you
made (E.g product), and re-bind this to your favourite expression used previously (E.g = 37 %
7 ** 2). Print the new value of your cosen variable (E.g. print(product) again); observe the
change in value from when used previously.
Paste the entire transaction from the python command prompt below showing both code and
results: —- Paste the text of your command prompt showing your results here
—-

2.3 Using the Jupyter Notebook


2.3.1 Exercise 8:
For this exercise we require you to upload the actual Jupyter Notebook file [Link] to
demonstrate you know how to create Notebook files and can find them on your computer (not
everyone can)!
It is a good idea to make a sensibly named folder for your weekly exercises so locating your work
is easier (i.e. don’t just put everything on the Desktop!)

(𝑝𝑎𝑠𝑡𝑒 𝑡ℎ𝑒 𝑙𝑜𝑐𝑎𝑡𝑖𝑜𝑛 𝑜𝑓 𝑡ℎ𝑒 𝑛𝑜𝑡𝑒𝑏𝑜𝑜𝑘 𝑓𝑖𝑙𝑒 ℎ𝑒𝑟𝑒 𝑠𝑜 𝑦𝑜𝑢 𝑘𝑛𝑜𝑤 𝑤ℎ𝑒𝑟𝑒 𝑖𝑡 𝑖𝑠

2.4 Exercise 9:
Add a Markdown cell as the first cell at the top of the book to indicate your student information.
Enter the following, filling in your student ID in place of :
# Prog AI & DS Workshop 1
## Student ID: <StudentID>
Use Shift+Enter, to execute this markdown cell and force it to display. This exercise tests that
you know what you student ID actually is, and also that you can create and format Markdown
in addition to using code cells. There will be no more exercises on using Markdown but its usage

4
will enhance your final graded submission, so it is worth understanding this element of formatting
documentation in Jupyter.
Paste screen capture on the results below as a record of the task completion.

(𝑝𝑎𝑠𝑡𝑒 𝑦𝑜𝑢𝑟 𝑟𝑒𝑠𝑢𝑙𝑡𝑠 ℎ𝑒𝑟𝑒)

2.4.1 Exercise 10:


We can use comparison operators on strings, just as numbers. However, these have some different
behaviours. Comparing two strings “ada”, and “bill” will check the first letter of each and will use
alphabetical ordering to determine which one is ‘first’ (i.e. Lower than the latter).
• In the fresh cell below, try executing “ada” < “bill”
If the first letter is the same in both, it will then check the second letter to make the outcome. If
the second letter is also the same, it will keep progressing until out of letters.
• Compare “ada” with “adb”
If the two words have different lengths, but otherwise are identical as we go along, python will
favour the shorter of the two strings.
• E.g. “ada” < “adalovelace” -> True
Try out several string comparisons below. You can add more cells if you need to.
[ ]:

2.4.2 Exercise 11:


Using input() ask the user to input a name. Let’s check if the name is equal to your name using
an equality test!
E.g.
their_name = input("What is your name?: ")
if their_name == "Brian":
print("I’m called that too")
[ ]:

2.4.3 Exercise 12:


Remember that we can perform logical operations on entire boolean expressions themselves. Modify
the boolean expression in Ex12 to also accept if they enter your last name too!
E.g.
their_name = input("What is your name?: ")
if their_name == "Brian" or their_name == "Tompsett":
print("I'm called that too")

5
Test out providing other names, your first name, and your last name to see what the program
outputs. Remember you can re-run the same cell that you have selected. Notice how each side of
‘or’ is a boolean expression which evaluates to True/False in itself.

[ ]:

2.4.4 Exercise 13:


Given the following input table, complete the truth table for the following expression:
(a and b) or c

a b c a and b (a and b) or c
True True True
True False True
False True True
False False True
True True False
True False False
False True False
False False False

Copy the table to the answer box and fill in the results

(𝑝𝑎𝑠𝑡𝑒 𝑦𝑜𝑢𝑟 𝑟𝑒𝑠𝑢𝑙𝑡𝑠 ℎ𝑒𝑟𝑒)

2.4.5 Exercise 14:


You are then told that the expression is incorrect, and should be:
(a and b) or not c

How does this change the overall boolean expression. Add a column to your table, and fill in the
results of this new expression.

(𝑝𝑎𝑠𝑡𝑒 𝑦𝑜𝑢𝑟 𝑟𝑒𝑠𝑢𝑙𝑡𝑠 ℎ𝑒𝑟𝑒)

2.4.6 Exercise 15:


We can use the expression x % 2 == 0 to check if a variable is even. Write an if statement
to check if a given variable is even. It should print out “The variable is even!” if it passes this
condition. Remember, modulo provides a remainder. Even numbers can fit 2 into themselves
perfectly with nothing left over, hence why we check if the remainder is 0.
[ ]:

6
2.4.7 Exercise 16:
How could the previous exercise be modified to also print “The variable is odd!” when the variable
is odd? Can a variable be anything other than even or odd? The last part of the question tests your
understanding of the mathematics of numbers (which is important when handling data). Could
your python code handle this case? (You might have to write an explanation that demonstrates
your understanding.)

[ ]:

2.4.8 Exercise 17:


Produce some code which first checks if a variable is divisible by 2, then checks if it is divisible by
3, otherwise prints that it is “not divisible by 2 or 3”. Would we use two separate if statements,
or a single if, elif statement. In summary, it should show a number that divides only by two, and
number that divides only by three, a number that divides by both and a number that divides by
neither - four possible outcomes. The purpose of the exercise is show how more complex decisions
can be written in python.
To help you decide, consider what should be output if we tested the number 6 through this system.
[ ]:

2.4.9 Exercise 18:


You are given the following list of numbers:
A = [ 5, 2, 9, -1, 3, 12]
Using the counter method from lectures slides, create a while loop which will go over each item in
this list. 1. Print each item 2. Check if the item is -1, if so, immediately break out of the loop. 3.
Calculate the square of the element, and print it.
Your code should contain a single while loop which performs the above actions in the order shown
above. It is an exercise in writing loops containing many actions.
[ ]:

2.4.10 Exercise 19:


Replace the while loop counter method from the previous exercise with for loop and range(n).
Your code should contain a single for loop which performs the above actions in the order shown
above. It is an exercise in writing loops containing many actions.
[ ]:

2.4.11 Exercise 20:


Repeat the previous exercise, but using the direct iteration version. E.g. No indexing.

7
You code should contain a single loop which performs the above actions in the order shown above.
It is an exercise in writing loops containing many actions.
[ ]:

2.4.12 Exercise 21:


Using the list, A, from the previous looping exercises, write a loop which will sum all of the numbers
up,and print them.
[ ]:

2.4.13 Exercise 22:


The mean number can be calculated by taking the summation and dividing by how many elements
were there. Using the output of the last exercise (the summation), create a new variable for the
mean number of the list. (E.g. [1, 3, 5] # Sum is 9. Mean is 9 / 3 which is 3.)

[ ]:

2.4.14 Exercise 23:


You are asked to find the minimum, and maximum of a list of numbers. You are provided with
code to determine the minimum.
my_items = [ -5, 3, 72, 1, 9, 24, -3]

minimum_so_far = None
for elem in my_items:
if minimum_so_far == None or elem < minimum_so_far:
minimum_so_far = elem

print("Minimum Value: ", minimum)


Modify the above program to also calculate the maximum so far, outputting it in a similar way.
In this example we used None as an initial value as it’s not a number. If the value is None,then
we know we haven’t checked anything yet, so our first value is always going to be our highest and
lowest!
[ ]:

2.4.15 Exercise 24:


Execute the following:
A = 5
B = A
B = 10
print(A) => 5
print(B) => 10

8
When we rebind B to be 10, A is left completely unmodified. This behaviour is unique to basic
data primitives such as the basic types we have looked at. However, let’s see what happens if we
do something similar to a List.
A = [ 1, 6, 2, 7 ]
B = A
[Link]( 6 )
print( A ) => [ 1, 2, 7 ]
This behaviour will hold for Lists, Dicts, and most ‘objects’ in Python. B is a reference to A.
We only have one copy of our list floating around, but now we have multiple variables capable of
pointing to it. If we wanted to make a copy of the List, such that we can modify them independent
of each other we have to [:]. E.g.
A = [ 1, 6, 2, 7 ]
B = A[:]
[Link]( 6 )
print( A ) => [ 1, 6, 2, 7 ]
print( B ) => [ 1, 2, 7]
This is known as ‘slice’ notation. Effectively [:] says to take the entire list, and it makes a copy
of this.
[ ]:

2.4.16 Exercise 25:


Using B (your copy of A), append some of your favourite numbers to the list.

[ ]:

2.4.17 Exercise 26:


You are given the following to complete:
results = []
bought_cost = [ 10.0, 12.55, 17.99 ] # Price you pay to the manufacturer for an item
sale_price = [ 12.0, 11.50, 20.0 ] # Price you sell it for

for i in range( len(item_cost) ):


<Calculate the difference between sale_price and bought_cost>
<Add these to the empty list, results>

print(results)

<Calculate and print the total profit/loss overall>


Note: Take care when calculating whether we made a loss, or a profit on our sale!
Adv Hint: There is such a function called zip, which can help iterate over two lists at once, should
you wish to look this up. It is left out of here as to not overwhelm.

9
[ ]:

2.4.18 Exercise 27:


You are given the following dictionary:
student_records = {
"Ada": 98.0,
"Bill": 45.0,
"Charlie": 63.2
}
You are then given two separate lists, one with names, and another with grades. You are to go
through these lists, and insert the students correctly into the dictionary.
student_names= ["Neva","Kelley","Emerson"]
student_grades= [72.2,64.9,32.0 ]
1. Ensure both lists are the same length: How might we check for this?
2. Using a for loop, iterating in range sufficient for all the elements
a. Each iteration here represents an index. E.g. Index-0 is Neva and her grade.

b. Insert these into the dictionary.


Remember dictionary["theKey"] =value. “theKey” can be replaced with any expression which
evaluates as a string. It could be a variable, or another expression.
[ ]:

2.4.19 Exercise 28:


Using the for k, v ... code example from the lecture slides, iterate over your newly modified
dictionary, showing the new entries.
[ ]:

2.5 The Extended Exercises are optional, and are offered as an advanced sup-
plement for those who have completed the existing work and wish to expand
on their knowledge and challenge themselves further.
2.5.1 Extended Exercise 1 - Blame Rob:
Bubble sort is a naive sorting algorithm for taking an unordered list, and sorting them into ascending
order. This is achieved by stepping through the entire list, comparing the current element to the
next in the sequence. If the current element is greater than the following one, they are swapped
in-place. The loop then continues until all elements are exhausted. The effect of this is that the
largest number will bubble up through the list to the top. Once we’ve reached the top, we start
the comparison again for a second pass, third pass, fourthpass, etc. This is repeated until the list
is sorted. I.e. no swaps have occurred that pass.

10
L = [9, 2, 12, 7] Is 9 > 2 -> Yes. Swap them in-place. Move along by one.
L = [ 2,9, 12, 7] Is 9 > 12 -> No. Do nothing. Move along by one.
L = [ 2, 9,12, 7] Is 12 > 7 -> Yes. Swap them in-place. Move along by one.
L = [ 2, 9, 7 , 12] We have run out of elements, start iterating from the beginning.
L = [2, 9, 7, 12] L = [2,9, 7, 12] -> SWAP L = [2, 7,9, 12]
Another pass L = [2, 7, 9, 12] L = [2,7, 9, 12] L = [2, 7,9, 12]
No swaps have been made this pass -> terminate, the list should now be sorted.
Your task (should you wish this optional exercise) is for you to manually implement the above
Bubble sort algorithm for a given list. If you copy any Bubble sort code from the internet you will
have achieved nothing! It is not a test of your ability to copy and paste, but to write code from
a provided specification. Further, any code copied from elsewhere and pasted into your classwork
should cite the source where it originated from; to do otherwise would be an academic misconduct
offence as outlined in the course induction. Research is scholarly, but copying without citation is
not.
[ ]:

11

Common questions

Powered by AI

Jupyter Notebook provides interactive features like real-time code execution feedback, combining code with visualizations and markdown descriptions. This enhances learning by allowing instant testing of hypotheses and observing code effects, making it beneficial for understanding concepts and debugging. However, its challenges include the potential for students to become overly reliant on its interactive nature instead of understanding underlying code mechanics, and the complexity managing extensive notebooks when keeping versions or debugging .

Python's if-statements enable fine-grained control over decision-making processes by evaluating conditions and executing code based on boolean logic. This feature allows applications to respond dynamically to varying inputs and conditions, enhancing reliability by ensuring actions are performed under correct circumstances. It supports complex decision trees, allowing nested conditions and ensuring that applications can handle unexpected scenarios gracefully, such as checking even-odd or specific divisibility conditions .

Programming workshops that emphasize experimentation and peer discussion foster active learning, encouraging students to explore concepts, test their understanding, and solve problems collaboratively. This methodology helps students develop critical thinking and problem-solving skills by challenging them to not only comprehend programming concepts but apply them in various contexts. Peer discussion further enriches understanding by exposing students to diverse perspectives and potential solutions, consolidating learning through repetition and social interaction .

Jupyter Notebook provides a structured environment for developing and storing Python programming exercises, allowing students to easily organize their work into cells, which can handle code, markdown, and output. This makes reviewing, sharing, and updating work efficient, as seen in the workshop exercises where results are developed and stored in the notebook before submission .

Python's dynamic type checking, managed by functions like type() and isinstance(), allows variable types to be checked and determined at runtime. This flexibility enables various programming paradigms and rapid prototyping since type declarations are unnecessary. However, it requires careful design to handle type-related errors effectively and maintain code readability. Dynamic typing's ability to use types dynamically accommodates polymorphism and confident operation with diverse data inputs in software development .

In Python, primitive data types such as integers and strings are stored directly, meaning their values are independent when assigned to variables. In contrast, complex data types like lists are stored as objects referenced by variables. When a list is assigned to another variable, both variables point to the same list object in memory. Modifying one alters the original list, unlike primitives. To create independent list copies, Python uses slicing (e.g., A = [:]), avoiding unintended modifications through shared references .

Casting in Python allows conversion of data from one type to another, facilitating necessary operations between different types. Correct casting ensures compatibility between types and accurate program functionality. Improper casting can lead to runtime errors or inaccurate outputs, such as using incorrect operations on casted data types or failing to convert data properly before performing operations (e.g., adding numbers as strings instead of integers). Developers must rigorously check types and apply conversions to avoid logical errors affecting computations .

The type() function in Python is used to determine the data type of an expression or variable, which is fundamental for understanding how data is stored and manipulated. This is significant for ensuring that operations on variables are compatible and behave as expected. By checking data types, programmers can prevent errors that arise from performing invalid operations or type mismatches, which is essential for tasks in Python exercises like verifying casting results or understanding operation outcomes .

In Python, immutable objects like integers and strings are passed by value, which means when assigned to new variables, they result in independent copies. Mutable objects like lists or dictionaries, however, are passed by reference. Assigning or modifying these objects affects all references to them. This behavior enables efficient memory use but requires caution, as unintended changes to objects can propagate through variables sharing a reference. Understanding this distinction is crucial for managing states and debugging unexpected behavior in Python programs .

Understanding PEMDAS (Parentheses, Exponents, Multiplication, Division, Addition, and Subtraction) or BODMAS (Bracket, Order, Division/Multiplication, Addition/Subtraction) is crucial in programming to correctly evaluate arithmetic expressions. It dictates the order in which operations are performed, influencing the outcome of complex expressions. For example, in the expression 12 + 28 / 7 * 2, division and multiplication are performed before addition, affecting the result. Ensuring the correct order prevents logic errors and inaccuracies in mathematical evaluations .

You might also like