You are on page 1of 16

Lab 2

Programming Fundamentals with Python and


Problem-Solving for the IoT

Part A
Create a Process Flowchart

Learning Objectives
1. Part A1: Recognize Symbols Used in a Flowchart and List Logical Process to Solve
a Problem
2. Part A2: Draw the Flowchart to Illustrate the Problem Solving Process

Background
Flowcharts are diagrams used to represent processes or workflows. Using different
shapes, boxes, and connecting arrows, a flowchart represents the solution flow to a
given problem. Flowcharts are commonly used to represent programs, algorithms, or
any ordered process in various disciplines. Flowcharts are typically created prior to
starting a process or writing an application in order to verify and catch potential logic
flows toward the solution before it is developed and implemented.
Flowcharts can be hand drawn or created using a number of packages including
Microsoft Office products, LibreOffice, GoogleDocs, and various web applications such
as https://www.draw.io/. These tools offer flexibility in designing and sharing
flowcharts efficiently.
A popular free alternative to draw.io is Lucidchart. Lucidchart offers similar features
for creating flowcharts, diagrams, and other visual representations. You can access it at
www.lucidchart.com.
Some of the most common flowchart symbols that used for programming are shown in
the diagram along with their intended purpose for the symbol. Lines with arrows
indicate the flow of the problem solving process.
Scenario
You are required to develop a systematic process to find a predetermined number. The
process developed is represented in a flowchart. Using the flowchart, we can check and
verify the logical process toward the problem.

Required Resources
This lab can be done with paper and pencil or a PC with internet access (or office
productivity applications, such as Microsoft Office, LibreOffice, and GoogleDocs).
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

A1 - Create a Process Flowchart


The problem is to develop a process to find a predetermined number. The process can
be programmed as a simple computer game. A player is asked to think about an integer
number between 0 and 128, The program will use the bisection method to find the
number.
Step 1: List the steps needed to solve the problem.

1. Ask the player to think about an integer number between 0 and 128.
2. Set a as the lower end, b as the high end, and t as the time of calculation
3. Set initial values, a = 0, b = 128, t = 0
4. Calculate the average number between a and b. Set it as M.
5. Set t = t + 1
6. Ask the player if M is the correct number:
If yes, print “The number you thought of is M and I guessed it t tries.” End the
process.
Else
If t = 6
If yes, print “I am sorry that I cannot guess it after 6 attempts.” End the
process.
Else
Ask the player if M is larger than the correct number:
If yes, set a = M, jump to Step 4.
Else

2
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

Set b = M, jump to Step 4.


Answer the following Questions in your Logbook:
1. Can the process catch if the number the player has chosen is 0 or 128? Why or
why not?
2. If 0 or 128 cannot be caught, what should be done to correct it?

A2 – Draw the Flowchart


Step 1: Use appropriate flowchart symbols for each functions.
Because the list of process steps is identified, we can use flowchart symbols to represent
each step.

1. Use an oval symbol as Start and a Display symbol to ask questions. Use a line to
link them:

2. Use a preparation symbol to make initial assignment:

3. Use a predefined process symbol to define a process function or routine:

4. Use a decision symbol to represent a condition test:

3
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

5. Use a process symbol to represent an operation:

Step 2: Draw the complete flowchart.


Now we can use symbols to draw a complete flowchart. We will use the Off Page
Connector and Connector to extend the flowchart to next page:

4
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

Reflection (Answer the following questions in your Logbook)


1. What is the significance of testing if t = 6?
2. Where should the test for the numbers 0 and 128 be placed?

5
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

Part B
Basic Python Programming
Learning Objectives
1. Part 1 - Choose Your Working Environment: Either use Python in Windows
10 OS or Launch VirtualBox or use Python from your installed Linux distro or
use your own standalone Linux distro or alternative environments like online
tools or web-based IDEs such as Google Colab, Replit, pythonanywhere or
Microsoft Visual Studio Code Online. The choice is yours as you have the
knowledge and experience from Lab 0 to choose the environment that best suits
your preferences and therefore to select your favourite working environment.
Remember, there's no single "best" environment. Choose the one that feels most
comfortable and familiar to you!
2. Part 2: Python Basics
3. Part 3: IDLE for Python
Background
Python, a programming language, allows for simpler statements. Python is very easy to
use, powerful, and versatile. It has become the language of choice for many IoT
developers. One of the main reasons for the popularity of Python is the developer
community. Python developers have created and made available many specific modules
that can be imported into any program to immediately lend added functionality.

Scenario
In this lab, you will learn and practice some basic Python programming. More
specifically, we will use Python version 3 in the lab. As already mentioned, there are
several ways to get your own copy of Python 3, depending on the operating system you
use. Linux users most probably have Python already installed - this is the most
likely scenario, as Python's infrastructure is intensively used by many Linux OS
components. If you're a macOS user, a version of Python 2 may already have been
preinstalled on your computer, but since we will be working with Python 3, you will
still need to download and install the relevant .pkg file from the Python site. Now, begin
your Python journey!

Required Resources
• A Laptop/desktop with internet access and enough memory (RAM).
• Windows 10, Linux, VirtualBox or else.
Guidelines for Comprehensive Logbook Documentation
Document each task step-by-step in your electronic logbook with screenshots and
explanations. Confirm completion of all tasks, reflect on challenges faced, and maintain
clarity and professionalism in your documentation.

6
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

B1 – Launch Python from Windows 10 or else

B2 – Python Basics
In Part B2, you will learn and practice some basic Python programming.
Step 1: Python programming in the interactive interpreter.
As an interpreted language, which means direct execution without compilation, Python
commands can be issued in an interactive interpreter.
Now that you have Python 3 installed, it's time to check if it works and make the very
first use of it. This will be a very simple procedure, but it should be enough to convince
you that the Python environment is complete and functional. There are many ways of
utilizing Python, especially if you're going to be a Python developer.
1. Start Python interpreter.
2. Perform calculations.

3. Print a text string.

4. Use the type() command to determine the basic data type: int, float, string, Boolean.

5. Create a variable.

7
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

6. Combine multiple strings together and print as one string.

7. Convert data type from a numeric number to a string.

8. Note that integers are not rounded up when converting from float. The decimal is
ignored.

9. Convert an integer to a float.

8
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

10. Obtain user input.

11. Exit interactive interpreter.

B3 – IDLE for Python


IDLE stands for Integrated Development and Learning Environment. It is supported and
included in the Python package. A few key features of IDLE for Python include these:
• A Python shell window (interactive interpreter) with colorizing of code input,
output, and error messages
• A multiwindow text editor with multiple undo, Python colorizing, smart indent,
call tips, auto completion, and other features
• The ability to search within any window, replace within editor windows, and
search through multiple files (grep)
• A debugger with persistent breakpoints, stepping, and viewing of global and
local namespaces
• Configuration, browsers, and other dialogs
To start your work, you need the following tools:
• an editor which will support you in writing the code (it should have some special
features, not available in simple tools); this dedicated editor will give you more
than the standard OS equipment;
• a console in which you can launch your newly written code and stop it forcibly
when it gets out of control;
• a tool named a debugger, able to launch your code step-by-step, which will
allow you to inspect it at each moment of execution.
Besides its many useful components, the Python 3 standard installation contains a very
simple but extremely useful application named IDLE. Navigate through your OS
menus, find IDLE somewhere under Python 3.x and launch it.

In Part B3, you will launch IDLE and create a simple script.
Step 1: Launch IDLE.
1. Use the idle3 command to launch IDLE. By default, it starts in Python Shell, or
interactive interpreter, window. You are already familiar with the interactive
interpreter. Enter the command idle3 to launch IDLE.
$ idle3

9
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

2. Click File -> New File to open a new (untitled) Python script.
3. Type the code in the script print(“Hello World!”), note the codes are colored, and
open and close parentheses are matched.
4. Click File -> Save, save the current script as 1.py in the current directory. Click
Save button.
5. Click Run -> Run Module (or press F5). The shell window will display the result.

Part C
More Python Programming

Learning Objectives
1. Core foundations of Python code
2. Your First Code – Saving and executing your code.
3. Execute code from the Command Line
4. Numbers and expressions; use of comments.
5. Working with Variables
6. User Input
All your command should use Python code and should be included in your Logbook.
Your First Code
1. Start Python 3 interpreter. This opens the Python 3 shell. The shell is where you can
enter code and see the responses and output of code you have programmed into
Python. This is a kind of sandbox, where you are able to try out some simple code
and processes.

2. The Python 3 IDLE is a configurable environment. If you don't like the way the
colours are represented, then you can always change them via Options>Configure
IDLE and clicking on the highlighting tab.
3. Type a command that prints Hello World. When you complete that, the word hello
world appears in the Shell as blue text indicating output from a string. Also, use
the print() function to print the line Hello Python! to the screen. Use double quotes
around the string.
10
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

4. Now try: print("2+2") - you can see that instead of the number 4, the output is the
2+2 you asked to be printed to the screen. The quotation marks are defining what’s
being outputted to the IDLE shell; to print the total of 2 + 2 you need to remove the
quotes: print(2+2)
5. You can continue as such printing 4+4, 8+8 and so on to the shell. An easier way is
to use of variable. Enter the variables a, b (a=2, b=2). Try print(a), print(b) and
print(a+b).
6. Write Python code that assigns variables to your first name and then print your
name. Repeat this for your surname and then type a command that prints both your
name and surname in the same line. You now have two variables containing a first
name and a surname and you can print them independently. Try,
print(name+surname). You need a space between the two, defining them as two
separate values (concatenation) and not a mathematical operation.
In Python 3 you can separate the two variables with the space using a comma:
print(name, surname). Alternatively, you can add the space yourself:
print(name+" "+surname)
The use of the comma is much neater, as you can see.
Saving and Executing your code
7. Editing Code: You will eventually reach a point where you must move on from
imputing single lines of code into the Shell. Instead, the IDLE Editor will allow you
to save and execute your Python code.
8. Click on the File > New File and this will open a new window with untitled as its
name. This is the Python IDLE editor and within it you can enter the code needed to
create your future programmes. The IDLE Editor is, for all intents and purposes, a
simple text editor with Python features, colour coding and so on. You enter code as
you would within the Shell, so taking an example from the previous steps, enter:
print("Hello World!").
9. You can see that the same colour coding is in place in the IDLE Editor as it is in the
Shell, enabling you to better understand what's going on with your code. However,
to execute the code you need to first save it. Press F5 and you get a Save… Check
box open.
Click on the OK button in the Save box and select a destination where you will save
all your Python code. The destination can be a dedicated folder called Python or
you can just dump it whatever you like. Remember to keep a tidy drive though, to
help you out in the future.
10. Enter a name for your code, ‘print hello’ for example and click on the Save button.
Once the Python code is saved it's executed, and the output will be detailed in the
IDLE Shell. In this case, the words Hello World!. This is how most of your Python
code will be conducted. Enter it into the Editor, hit F5, save the code and look at the

11
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

output in the Shell. Sometimes things will defer, depending on whether you have
requested a separate window, but essentially that's the process.
11. If you open the file location of the saved Python code, you can see that it ends in a
.py extension. This is the default Python file name. Any code you create will be
whatever.py and any code downloaded from the many Internet Python resource sites
will be .py. Just ensure that the code is written for Python 3.
12. Let's extend the code and enter a few examples from the previous steps.
a=2
b=2
name="Stavros"
surname="Dimitriou"
print(name, surname)
print(a+b)
If you press F5 now you will be asked to save the file, again, as it's been modified
from before.

13. If you click the OK button, the file will be overwritten with the new code entries,
and executed, with the output in the Shell. It's not a problem with just these few
lines but if you were to edit a larger file, overwriting can become an issue. Instead,
use File > Save As from within the Editor to create a backup.
14. Now create a new file. Close the Editor, and open a new instance (File > New File
from the Shell). Enter the following code and save it as hello.py:
a="Python"
b="is"
c="cool!"
print(a, b, c)
Executing code from the Command Line
15. Using the code you created on the previous steps, the one you named hello.py, let's
see how you can run code that was made in the GUI at the command line level.
Windows 10 users will need to click the Start button and search for CMD or search
for python and then click on the version you have installed, e.g. Python 3.8.1.

12
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

From here you're able to enter Python code.


16. Now enter: exit() to leave the command line Python session and return you back to
the command prompt. Enter the folder where you saved the code from the previous
steps and list the available files within; hopefully you should see the hello.py file.
From within the same folder as the code you are going to run, enter the following
into the command line: python hello.py

This will execute the code you created, which to remind you is the same as that on
step 14 above.
17. Since this is Python 3 code, using the syntax and layout that is unique to Python 3, it
only works when you use the Python 3command.
Numbers and Expressions
18. You can get some impressive results with the mathematical powers of Python; as
with most, if not all, programming languages, maths is the driving force behind the
code. In the Shell enter the following to see that Python can handle some quite large
numbers:
8+8
49573+84096293
38567394*964273894725
19. You can use all the usual mathematical operations: divide, multiply, brackets ans so
on. Perform the following examples to demonstrate the basic mathematical
operations.
8/2
2+3*4
(1+4)+(4*5)
20. You have noticed that division produces a decimal number. In Python these are
called floats or floating points arithmetic. However, if you need an integer as
opposed to a decimal output, then you can use a double slash:
8//2
6//2

13
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

21. You can also use an operation to see the remainder left over from division. E.g.:
10//3
10%3
22. Next up we have the power operator or exponentiation. To work out the power of
something you can use a double multiplication symbol or double-star on the
keyboard. Python has also numerous build-in functions to work out sets of numbers,
absolute values, complex numbers and a host of mathematical expressions and
Pythagorean tongue-twisters. Show and explain the output of the following code:
2**4
10**10
bin(3)
format(3, 'b')
23. The Boolean expression is a logical statement that will either be true or false.
Compare data and test to see if it's equal to, less than or greater than. Try this in a
New File, then execute the code and show the output.
a=6
b=7
print(1, a == 6)
print(2, a == 7)
print(3, a == 6 and b == 7)
print(4, a == 7 and b == 7)
print(5, not a == 7 and b == 7)
print(6, a == 7 or b == 7)
print(7, a == 7 or b == 6)
print(8, not (a == 7 and b == 6))
print(9, not a == 7 and b == 6)
Using Comments
24. Programmers keep their code readable by commenting on certain sections. It is just
good practise. The hash symbol (#) is used for comments. The comment, the hash
symbol, can also be used to comment out sections of code you don't want to be
executed in your program. You can also use three single quotes (‘’’) to comment out
a Block Comment or multi-line section of comments. Place them before and after
the areas you want to comment for them to work.
25. Working with Variable – For example, in the Shell enter: name="Name Surname"
and then use print(name)
What the following coding does?
type(name)
title="I am learning Python"
print (name + ": " + title)
character=name + ": " + title

14
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

print(character)
26. Numbers are stored as different variables. You can't combine both strings and
integer type variables in the same command. You need to either turn one into the
other or vice versa. When you do try to combine both, you get an error message.
age=33
type (age)
print (name + age)
27. This is a process known as TypeCasting. The Python code is:
print (character + " and I am " + str(age) + " years old. ")
or you can use
print (character, " and I am ", age, " years old. ")
Note that in the last example, you don't need the spaces between the words in quotes as
the commas treat each argument to print separately.
28. Another example of TypeCasting is when you ask for input from the user, such as a
name. For example enter:
age=input (" How old are you? ")
All data stored from the input command is stored as a string variable.
29. You may also enter:
int(age)+ 10
This will TypeCast the age string into an integer that can be worked with. The use of
TypeCasting is also important when dealing with floating point arithmetic (numbers
that have a decimal point in them). For example, enter shirt=19.99 and then enter
type(shirt) and you will see that Python has allocated the numbers as a float,
because the value contains a decimal point.
30. When combining integers and floats Python usually converts the integer to a float,
but should the reverse ever be applied it’s worth remembering that Python doesn't
return the exact value. When converting a float to and integer, Python will always
round down to the nearest integer, called truncating; in our case instead of 19.19 it
becomes 19 (when you enter int(shirt).
31. User Input – The type of input you want from the user will depend greatly on the
type of program your coding. For example, a game may ask for a character's name,
whereas a database can ask for personal details.
32. Create an execute the following file:
print ("Hello")
firstname=input("What is your first name? ")
print ("Thanks.")
surname=input("And what is your surname? ")

15
Lab Workshop/Lab 2 Embedded Systems and the Internet of Things EEE_6_ESI

33. You now have the users name stored in a couple of variables and hence you can call
them up whenever you want:
print ("Welcome", firstname, surname, ". I hope you are well today. " )
Run the code and you can see a slight issue, the full stop after the surname follows a
blank space. To eliminate that you can add the plus sign instead of the comma in the
code:
print ("Welcome", firstname, surname+ ". I hope you are well today. " )
34. You don't always have to include quoted text within the input command. For
example, you can ask the user their name and have the input in the line below:
print ("Hello. What is your first name? ")
name=input()
Try also this:
print ("Halt! Who goes there? ")
name=input()
35. It's a good start to a text adventure game, perhaps? Now you can expand on it and
use the raw input from the user to flesh out the game a little:
If name=="Name"):
print ("Welcome, good sir. You may pass." )
else
print ("I know you not. Prepare for battle!." )
36. Any input from user is automatically a string, so you need to apply a Typecast in
order to turn it into something else. This creates some interesting additions to the
input command. For example:
# Code to calculate rate and distance
print ("Input a rate and a distance")
rate = float(input("Rate: "))
37. To finalise the rate and distance code, you can add:
Distance = float(input("Distance: "))
print ("Time: ", (distance / rate))

Save and execute the code and enter some numbers.

16

You might also like