You are on page 1of 351

Click to edit Master title style

Installing visual studio


code (the Python IDE)

1 1
Introductions
Click to edit Master title style
What is IDE?

• An integrated development environment (IDE) is a software suite that


consolidates basic tools required to write and test software.
• Developers use numerous tools throughout software code creation, building
and testing.
• Without an IDE, a developer must select, deploy, integrate and manage all
of these tools separately.
• An IDE brings many of those development-related tools together as a single
framework, application or service.
• The IDE is designed to simplify software development and can identify and
minimize coding mistakes and typos.
2 2
Introductions
Click to edit Master title style
Why IDEs are important?
The following are some reasons why developers use IDEs:

• Code editing automation


• Syntax highlighting
• Intelligent code completion
• Refactoring support
• Compilation
• Version control
• Visual programming
• Testing
• Debugging
3 3
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

4 4
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

5 5
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

6 6
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

7 7
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

8 8
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

9 9
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

1010
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

1111
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

1212
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code: 2
• https://code.visualstudio.com/

Adding python extension 1


For visual studio code.
Click on the Install button
In the editor..

1313
Introductions
Click to edit Master title style
Visual studio code downloads
2
• Download visual studio code:
• https://code.visualstudio.com/
3
1
Adding code runner to display
the code runner icon on top right.

We use it to run our python


programs .

1414
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

The code runner icon


is shown on the top right.

1515
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

Now, let’s write a python program


And run it !

First, go to File then select


New File..

1616
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

Select Python File…

1717
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

Start typing your Python code…


Then click the runner icon..

1818
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

In the next page:


Name the file with the extension
.py , then click Save..

• You can choose where you


want to save your python
files on your computer
(e.g. Desktop).

1919
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/

Next, run the code by clicking on the


runner icon, the output is displayed
In the TERMINAL as shown in the screen.

2020
Click to edit Master title style

Problem Solving and Python

Instructor: Megha Patel

1
Introductions
Click to edit Master title style
Designing a program

1. The first step in programming is designing – flowcharts and pseudocode help


with this process.
2. Next, the code is written.
3. All code must be cleared of all syntax errors.
4. After the executable is created, it can be checked for logic errors.
5. If logic errors exist, the program must be debugged.

2 2
Introductions
Click to edit Master title style
Designing a program

• The purpose of Programming Logic and Design is to focus on Flowcharts and


Pseudocode.
• The design is the foundation of a good program.
The program development cycle

3 3
Introductions
Click to edit Master title style
Designing a program

Two steps in designing a program:


• Understand the tasks that the program is to perform.
§ Learning what the customer wants.

• Determine the steps that must be taken to perform the task.


§ Create an algorithm, or step-by-step directions to solve the problem.
§ Use flow charts and/or pseudocode to solve.

4 4
Introductions
Click to edit Master title style
Designing a program

Pseudocode
• Fake code used as a model for programs
• No syntax rules
• Well written pseudocode can be easily translated to actual code
Display "Enter the number of hours"
Input hours
Display "Enter the hourly pay rate"
Input payRate
Set grossPay = hours * payRate
Display "The gross pay is $", grossPay
5 5
Introductions
Click to edit Master title style
Designing a program Flowchart for the pay calculating program

Flowcharts
• A diagram that graphically
depicts the steps that take
place in a program

6 6
Introductions
Click to edit Master title style
Designing a program
• Flowchart Connector Symbol
• Use connectors to break a flowchart
into two or more smaller flowcharts
and placing them side-by-side on
the page.

7 7
Introductions
Click to edit Master title style
Designing a program

• Off-Page Connector Symbol


• To connect flowcharts on different pages

8 8
Introductions
Click to edit Master title style
Designing a program

Output – data that is generated and displayed


Input – data that a program receives
Variables – storage locations in memory for data
Computer programs typically follow 3 steps
1. Input is received
2. Some process is performed on the input
3. Output is produced

9 9
Introductions
Click to edit Master title style
Designing a program
Input, Processing, and Output of a Pay Calculating program:

1010
Click to edit Master title style

Thank You

11
References
Click to edit Master title style
Material has been taken from (can be accessed through Sheridan's Library Services) :

• Starting Out with Python (ISBN-13: 9780136912330 ):


• https://www.pearson.com/en-ca/subject-catalog/p/starting-out-with-
python/P200000003356/9780136912330

• Murach’s Python 2nd Edition programming, 2nd Edition :


• https://bookshelf.vitalsource.com/reader/books/9781943872756/pages/recent

• Introducing Python, Lubanovic, B., O'Reily Media, 2nd Edition, 2019


• https://www.oreilly.com/library/view/introducing-python-
2nd/9781492051374/
1212
PROG12583
Programming Foundations -
Python

Computer Programs

Megha Patel, Sheridan College


Acknowledgement
• These slides are inspired by the original
slides created by Prof. Magdin Stoica and Prof.
Jigisha Patel

Megha Patel @ Sheridan College 2


Agenda
• Identify the parts of a computer and the role each
part plays in a computer program.
• Define what are computer programs.
• Describe how programs are executed by computers.
• Analyze the process of creating a computer
program. How do we create a computer program?
• Define what is a programming language.
• Describe the two fundamental states of a
program: design time and runtime.
• Explain what is an Integrated Development
Environment (IDE)
Megha Patel @ Sheridan College 3
How do we function?

Memory BrainCells

Our senses send


information to our brain

Our Brain

Once we think, we
Only Vulcans can
open our mouth or
mind-meld, we
so it’s supposed to
work. tweet

Megha Patel @ Sheridan College 4


The Computer - Hardware

Memory
(RAM)
Input
Devices
(Keyboard & Mouse)

Storage Devices
CPU (HDD)

Output
Devices Computer’s
(Monitor, Printer) Brain Communication
Devices
(Network)

Megha Patel @ Sheridan College 5


Computer Hardware Parts
The CPU is the brain of the computer, in charge of
executing things
RAM is the memory is where the computer
remembers things
Storage devices is where the computer REALLY
remembers things (even after a restart)
Communication devices is what computers use to
talk to each other
Input devices like the keyboard, mouse, touch
surfaces send information for processing
Output devices are used to present information to
the user, the result of what the computer did

Megha Patel @ Sheridan College 6


Hardware
=
Electronic computer
devices

(hard to change)
Megha Patel @ Sheridan College 7
Computer Programs – Software

Computer
Program

From our
brain to the
computer’s
brain
Megha Patel @ Sheridan College 8
Software
=
Computer Programs

(easier to change)
Megha Patel @ Sheridan College 9
How software uses hardware
Programs tell the CPU what to do using commands or
instructions

Programs store temporary information in memory

Programs store permanent information on storage


devices

Programs use communication devices to “talk” to


other programs

Programs get information by reading or scanning it


from input devices (from users)

Programs present their results by writing or


printing to output devices (to the user)

Megha Patel @ Sheridan College 1


0
How are programs executed ?

Electronic devices are made of transistors, one of


the greatest inventions of the 20th century

Through their transistors, electronic devices,


hardware components can store only two states:
on (1) and off (0)

Machine Language – language computers


understand

Megha Patel @ Sheridan College 11


Machine Language
• Language computers understand: if you “speak” it to them they will do
as you ask
• Very simple“alphabet”: only two symbols:
1 (one) and 0 (zero).
• These symbols are called “bits” or binary digits
• A “word” in machine language is called an “instruction”.
• They are meant to tell the computer (CPU) to do something.
• Very few “words” called an instruction set.

• Very simple “words”: combinations of 1 and zero (e.g. 100111110001)


• Very simple syntax: only one word at a time, words are only allowed to
have a fixed number of symbols (1s and 0s): 8, 16, 32, 64

1
Megha Patel @ Sheridan College
2
Computer Programs - What we Run
• Computer programs are a collection of machine
language instructions, machine code (1s and 0s)
• Stored (saved) in executable files or binary files
onto storage devices.
• Who writes computer programs?
• Programmers
• Software Developers
• Software Engineers
• Sometimes program can write other programs

Megha Patel @ Sheridan College 13


An executable is a file
containing a computer
program of 1s and 0s

Megha Patel @ Sheridan College 14


Do we speak 1s and 0s ?
• We speak a natural language, like English, French, Hindi,
Spanish
• Ambiguous
• Redundant
• Metaphors and idioms
• Complex rules
• Complex vocabulary

• Too hard to write a compiler that translates natural


language commands
• We need a simpler language, as close to natural as we can
make it but simpler, unambiguous, literal, precise
• We need a programming language
1
Megha Patel @ Sheridan College
5
Programs
are written in a
programming language
(Not 1s and 0s)

Megha Patel @ Sheridan College 16


The compiler creates 1s and 0s
• Something else has to “translate” the commands
we can write with a keyboard to the 1s and 0s that
computers understand
THE COMPILER
• The compiler is a computer program itself that
knows how to translate commands that we give
into 1s and 0s that computers can run
• In the end, only executable code made of 1s and 0s
can be executed, run by the computer.

1
Megha Patel @ Sheridan College
7
The compiler translates
Programming
________Language
into
Machine Language
__________.

Megha Patel @ Sheridan College 18


Source Code
• What we write, in a programming language, and
what the compiler translates.
• Source code is stored (saved) into source files.
• These are text files with special extensions and of
course special content.
• If stored only in the memory of the computer, it
would disappear as soon as the computer restarts.
• Source files are stored (saved) onto storage devices
such as the hard-drive.

Megha Patel @ Sheridan College 19


Source Code cont…
• Source code is a set of sentences (i.e. commands or
instructions) written in a programming language.
• A compiler reads source files, processes all the
commands and translates them into an executable
file that contains machine code.
• The process of transforming a source file into binary
file is called compilation or compiling a source file.

Megha Patel @ Sheridan College 20


Compiler

Print(“Hello
World”)
Compiler

Megha Patel @ Sheridan College 21


Computer programs - what we create
• Computer programs, when we create them, are a
collection of source files
• Simple ones may consist of only one source file
• Large programs have thousands of source files

• Remember: source files contain programming


language “sentences” called commands,
instructions or statements

• Remember: computer programs are written in


programming languages

2
Megha Patel @ Sheridan College
2
Programming Languages
• There are many programming languages with
different characteristics, strengths and weaknesses
• Classified as “generations” of languages: 1st, 2nd,
3rd and 4th generation depending on when they
were created and what they can do

• Python is a 3rd generation language, just like Java,


C#, C++ and C and many others

2
Megha Patel @ Sheridan College
3
A program is also
collection of sourcefiles

Megha Patel @ Sheridan College 24


Design-Time
• A program is said to be “at design-time” when we are creating/writing
it.
• At design time we …
• THINK
• Create and write source files
• Write commands in a programming language
• Compile source files and build executable files
•A program whose programming language
“sentences”, the commands are incorrect is said to have syntax errors.
• Syntax errors are detected by the compiler when it tries to translate
them into executable code.
• So what else do we do at design time? We fix errors.
• A program that has syntax errors cannot be executed because it
cannot be translated into 1s and 0s, it cannot be compiled.

2
Megha Patel @ Sheridan College
5
Runtime
• A program is said to be “at runtime” when it is
running/executing.
• At runtime we …
• Test the program by using its functionality in
every way possible. If the program terminates
unexpectedly is said to have runtime errors.
• Verify the output of the program to be correct. If
the output is incorrect the program is said to
have logical errors.

2
Megha Patel @ Sheridan College
6
Errors
• To fix any errors, we note any error message that is
displayed and than stop the program to go back to
design time.
• We fix errors in design time.
• We will learn more, a lot more about testing later
• Use the program and enjoy the functionality it
provides

• A program at runtime cannot have syntax errors but


can have other types of errors: runtime errors or
logical errors.

2
Megha Patel @ Sheridan College
7
Design-Time Runtime
• We are creating the • We are running the program
program • Machine code
• Source code • Executable files
• Source files • Machine language is
• Programming language is made of 1s and 0s or
high-level, English-like similar
• Find syntax errors • Find runtime and
logical errors
• We think, code, fix syntax,
runtime or logical errors • We test different input,
verify the output, use
• We compile the program
• We have fun creating • We debug (more on
something great this later)
• We have fun using what we
have created with our
mind
Megha Patel @ Sheridan College 28
Programming

Run Program

Think Test

Design
Fix Errors
Time Code Use Runtime Verify

Compile Debug

Stop Running
2
Megha Patel @ Sheridan College
9
Integrate Development Environments (IDEs)
• Programs that help us create … computer programs
• They are called “integrated” because they integrate multiple types
of tools necessary when programming
• They are more like a toolbox than a tool
• What kind of tools are integrated in an IDE?
• A text editor for creating source files and writing source code
• An easy-to-use interface for running the compiler and running
the program
• A debugger used for interactive execution of the code. Useful
in creating reliable, professional programs
• A help system that provides access to information that helps us
program.
• Advanced coding tools like automatic code-completion,
refactoring etc.
• Advanced code generation tools for building graphical user
interfaces, database code
• Tools to create diagrams that help us think about a program

Megha Patel @ Sheridan College 30


I only have two symbols in my alphabet, 1
and 0
All my words have the same number of
symbols, for example 32
Computers speak it fluently no matter how
old or how new
Who am I If you want to tell a computer to do
? something you must use it, somehow.
My two symbols, 1 and 0 are called bits

I am a language

I am a language that machines (computers)


speak.

Megha Patel @ Sheridan College 31


Machine
Language

Megha Patel @Sheridan College 32


I can do anything, from saving lives to landing space
robots on Mars

I keep jumping between design-time and run-time

I am created in text files but when I run, I am made of


cool unreadable stuff: 1s and 0s.
Who am I
? I require a mind and a computer to exist

I am easy to make as long as whoever makes me


practices and practices… and practices. Like any great
thing it requires hard work.
I am almost made with simple English.

Megha Patel @ Sheridan College 33


Programs

Megha Patel @ Sheridan College 34


I am a program

I am a program that translates

I make 1s and 0s (or something like it)

Who am I I read source files and create binary files (or


? something like it)
I can almost read English and I can create no
human can create
If I don’t understand what you tell me I will
give you syntax errors
I compile source code into machine code

Megha Patel @ Sheridan College 35


Compiler

Megha Patel @ Sheridan College 36


I am something you need.

When you use me well, it’s almost like you are


writing an essay in English

I am a foreign language, I will be almost like a native


language once you get enough practice
Who am I
? I am used to write, create programs

I am compiled into machine code the computer


understands

I am something you will learn the rest of the


semester (and for the rest of your time at Sheridan)

Megha Patel @ Sheridan College 37


Programming
Language

Megha Patel @ Sheridan College 38


Prog12583
Programming Foundations-
Pythons

Python Fundamentals

Megha Patel , Sheridan College


Megha Patel @ Sheridan College 1
Acknowledgement
• These slides are inspired by the original slides
created by Prof. Magdin Stoica and Prof. Jigisha
Patel.

Megha Patel @ Sheridan College 2


Agenda
1. Identify different implementation of the Python language
2. Classify the Python programming language based on
principal characteristics of programming languages.
3. Describe the role of the Python Interpreter, Python
Virtual Machine (PVM) and Python Modules in Python
programming
4. Explain the role of bytecode in Python programs and
their execution
5. Explain the role of frozen binaries and their relationship
to Python source code and bytecode. Contrast frozen
binaries with optimization mechanisms
6. Explore the IDLE, the standard Python IDE
7. Use the Python interpreter and IDLE to run Python
commands, create and run programs
Megha Patel @ Sheridan College 3
Why Python is great programming language?
• Python is a multi-paradigm programming language
which makes it a great tool to study the paradigms
such as :
• object-oriented,
• procedural,
• functional and
• plain scripting.

• Python is portable since Python interpreters exist


for most operating systems.

Megha Patel @ Sheridan College 4


Why Python is great programming language?
• Interoperability with many languages such as C/C++,
Java and C#.
• Extremely versatile due to its large and well
developed ecosystem.

• Dynamically typed but strongly typed which allows


us to postpone the type discussions to our second
programming course.

• Language focus on code quality and productivity.

Megha Patel @ Sheridan College 5


Why Python is great programming language?
• Rich platform / ecosystem, not just a programming
language.
• Various Python implementations with specific
purposes
• Rich set of predefined Python libraries allowing
anything from game development to scientific
computing to web development.

• Object-oriented language in which everything is an


object including the program and its elements.

Megha Patel @ Sheridan College 6


Python is an interpreted
language

Megha Patel @ Sheridan College 7


Python is dynamically
typed language

Megha Patel @ Sheridan College 8


Python is strongly typed
and therefore (mostly)
type-safe

Megha Patel @ Sheridan College 9


Everything in Python is
an object

Megha Patel @ Sheridan College 10


Platform Independence vs. Portability
• How is platform independence achieved?
• Virtual Machines
• Hides the operating system and the underlying
machine
• Programs are compiled to run on the virtual
machine which in turns is implemented for each
particular platform (Windows, Linux, Unix etc.)

Megha Patel @ Sheridan College 11


Platform Independence vs. Portability
• Portability. Another way to achieve platform
independence.
• Python programs can be interpreted on any OS.
The libraries used may make an OS platform
dependent.
• C / C++ write once compile everywhere. A
compiler exists for every OS
• Platform independent frameworks: Qt
Megha Patel @ Sheridan College 12
Python programs are
portable

Megha Patel @ Sheridan College 13


Python Concepts
• Python source code is interpreted (executed) by the
Python interpreter, the python.exe program:
• Python source files have the extension *.py
• Pythonw.exe interpreter runs silently without a
terminal window. *.pyw files will be executed by
Pythonw.exe and are meant for GUI programs

Megha Patel @ Sheridan College 14


Python Concepts
• Python modules are compiled into Python Byte
code  the intermediate language
• Imported modules are compiled in byte code as
an optimization
• Python byte code is saved in files with the
extension *.pyc (compiled python)
• Python byte code files are stored in __pycache__
folder (version 3.2 and up)
• Not a machine language / binary code

Megha Patel @ Sheridan College 15


The Python Interpreter
translates Python source
code into bytecode not
1s and 0s

Megha Patel @ Sheridan College 16


Bytecode is NOT
executable by the
computer directly.
You need another program
to interpret the bytecode,
Python.exe
Megha Patel @ Sheridan College 17
Python Concepts
• Python Virtual Machine (PVM) interprets Python
instructions one at a time by translating it into
bytecode instructions
• Not a separate program but a component of the
Python interpreter
• The runtime engine of Python that performs the
python interpretation

• Just-In-Time Compiler (JIT) converts Python byte


code into native machine code causing it to execute
much faster. Only present in specialized Python
implementations such as PyPy.
Megha Patel @ Sheridan College 18
Python Concepts
• Frozen Binaries are executable packages that
bundle the program files along with the Python
interpreter and any required support files
• Created with 3rd party application such as py2exe,
PyInstaller, py2app, freeze

Megha Patel @ Sheridan College 19


The Just in Time Compiler (JIT),
available in some Python
implementations (e.g. PyPy),
can translate
bytecode
into
machine code
(1s and 0s)
Megha Patel @ Sheridan College 20
Python Implementation
• CPython
• Standard implementation of Python using the C
programming language
• Comes in two flavours 2.x and 3.x. The former has a larger
ecosystem and install base but it is end of life.
• Jython
• Python implementation using Java programming language
and the Java Runtime Environment. Can interact
seamlessly with Java libraries.
• IronPython
• Python implementation using C# programming language
and the .NET platform. Can interact seamlessly with any
.NET compliant language.
Megha Patel @ Sheridan College 21
Python Implementation cont…
• PyPy
• Python implementation optimized for speed. Has
a Just-In-Time compiler to compile Python
bytecode into native code before execution.
Creates type-specific machine code
• NumPy
• Python extension of CPython for scientific
computing used at Los Alamos and NASA
• SciPy is a scientific computing environment which
includes NumPy and other tools and libraries
• Stackless
• Python re-implementation of CPython
• Built for concurrency, microthreads
Megha Patel @ Sheridan College 22
Python Standard Library
• Python is not just a programming language
 Python comes with a large standard library, predefined,

ready-to-use python libraries


(https://docs.python.org/3/library/)
• Built-in types, functions, constants, data types
• Text processing, binary data, numerical and math modules, functional
modules, mark-up language processing
• File and directory access, file formats, security, cryptography,
concurrent execution, operating system services
• Data persistence, compression, serialisation
• Communication, inter-process, networking, internet
• Multimedia, gaming, graphical user interfaces
• Development tools, debugging, profiling, packaging and
distribution
• Python runtime services, language services,
metaprogramming Megha Patel @ Sheridan College 23
Python Source vs. Bytecode
Source Code Bytecode
class HelloMessage:
def show(self):
helloMsg = 'Hello
programming world'
print(helloMsg)

courseMsg =
'Programming
Principles with
Python’
print(courseMsg)
courseNo = 10004
print('#prog',
courseNo, sep="")

Megha Patel @ Sheridan College 24


Many Source files to one executable
Stored for imported
Python Python modules in *.pyc files
Interpreter Bytecode
Source File

Python Python Python


Interpreter Bytecode
Source File Interpreter
(executable)
Python Python
Interpreter Bytecode
Source File

Python Standard Library / 3rd Party Libraries


The Python Virtual
Machine (PVM) interprets
byte-code to execute the
program
Megha Patel @ Sheridan College 25
Rewind

HelloWorld-V1
print('Hello Programming World')
print('Programming Foundations- Python')
print('#prog12583')

Megha Patel @ Sheridan College 26


Exercise: Breaking down Hello World
 Analyze the version of Hello World shown in the
previous slide
 Break down the program into elements and identify:
 Keywords: what are the Python keywords used
 Symbols: what are the Python symbols used
 Declarations: how many and what is being declared
 Predefined Python “words” – words defined by Python using
the Python keywords. These are used without being explicitly
declared
 Statements: how many statements and what do they do
 Blocks of statements: how many and what do they contain

 Are there any remaining words that you’ve used /


typed?

Megha Patel @ Sheridan College 27


Python Programming Absolute Basics
• Python source files are text files saved with the
extension *.py
• The file name of the source files are independent of
what is in the source file but become module
names when imported
• Location of file relative to the main file has to be
searchable by the Python interpreter. Must be
listed in PYTHONPATH environment variable if not
in the same folder
• Wrong name or location will generate syntax or
runtime errors

Megha Patel @ Sheridan College 28


Python Programming Absolute Basics
• Python programming language is case sensitive:
name, Name, NAME and nAmE are four different
things
• The statement separator in Python is the end of the
line. If multiple statements exist on the same line
they must be separated by semicolon ;
• The statement block (or suite) is delimited using
indentation
• Simply indent the statements that are part of the
block / suite

Megha Patel @ Sheridan College 29


Statements and Blocks in Python
__________ __________
__________ __________
__________ __________
__________

__________ __________
__________ __________
__________ __________
__________ __________
__________ __________
__________ __________
__________
__________
Sequential lines with __________
the same indentation __________
designate a block

Megha Patel @ Sheridan College 30


Comments
• Single line comments
• Start with “#”
• End at the end of the line. It doesn’t matter what is in the
comment, the rest of the text until the end of the line is
considered a comment
• Examples: #This is a comment on one line
• Block comments can span multiple lines
• Python doesn’t have a separate block comment symbol
and requires that each line starts with #
• Documentation Strings
• Doc Strings which are meant to provide documentation
that can be extracted by documentation of modules,
classes and functions/methods
• Text enclosed in triple double quotes: """This is a doc
string"""
• Can be used as block comments
Megha Patel @ Sheridan College 31
Hands-On

HelloWorld-V2
””” This is a Hello World Program ”””
print('Hello Programming World')
print('Programming Foundations-Python’)

#The following line prints the Course Code


print('#prog12583')

Megha Patel @ Sheridan College 32


Exercise: Breaking down Hello World
 Analyze the version of Hello World shown in the
previous slide
 Break down the program into elements and identify:
 Keywords: what are the Python keywords used
 Symbols: what are the Python symbols used
 Declarations: how many and what is being declared
 Predefined Python “words” – words defined by Python using
the Python keywords. These are used without being explicitly
declared
 Statements: how many statements and what do they do
 Blocks of statements: how many and what do they contain

 Are there any remaining words that you’ve used /


typed?

Megha Patel @ Sheridan College 33


Declaring New “Words” in Python
• Variables are declared with the syntax <name> = < value>
• <name> starts with a lower case letter
• <value> can a be a number, letters / text, True/False

• Modules are declared by saving a Python program into a file.


The file names becomes the module name

• Packages are declared by placing modules into folders. The


folder name becomes the package name

Megha Patel @ Sheridan College 34


Hands-On

HelloWorld-V3
helloMsg = 'Hello programming world'
print(helloMsg)
courseMsg = 'Programming Foundations Python'
print(courseMsg)
courseNo = 12583
print('#prog', courseNo, sep="")

Megha Patel @ Sheridan College 35


Exercise: Breaking down Hello World
 Analyze the version of Hello World shown in the
previous slide
 Break down the program into elements and identify:
 Keywords: what are the Python keywords used
 Symbols: what are the Python symbols used
 Declarations: how many and what is being declared
 Predefined Python “words” – words defined by Python using
the Python keywords. These are used without being explicitly
declared
 Statements: how many statements and what do they do
 Blocks of statements: how many and what do they contain

 Are there any remaining words that you’ve used /


typed?

Megha Patel @ Sheridan College 36


Using Blocks
• Defining classes functions / methods
declaration : Declaration

---> statement 1
---> statement 2 Definition
---> statement 3

• Controlling the execution of the statements


Control statement (branch or repetition) : Header

---> statement 1
Compound
---> statement 2 Statement

---> statement 3

Megha Patel @ Sheridan College 37


Declaring New functions in Python
• Functions are declared with the keyword def and the
symbols ( ) : and ,
• def <function name>(list, of, arguments):
• Must be followed by the definition of the function which
is a block and therefore indented

Megha Patel @ Sheridan College 38


Hands-On

HelloWorld-V4

def sayHello():
helloMsg = 'Hello programming world'
print(helloMsg)
courseMsg = 'Programming Foundations
Python'
print(courseMsg)
courseNo = 12583
print('#prog', courseNo, sep="")

sayHello()

Megha Patel @ Sheridan College 39


Exercise: Breaking down Hello World
 Analyze the version of Hello World shown in the
previous slide
 Break down the program into elements and identify:
 Keywords: what are the Python keywords used
 Symbols: what are the Python symbols used
 Declarations: how many and what is being declared
 Predefined Python “words” – words defined by Python using
the Python keywords. These are used without being explicitly
declared
 Statements: how many statements and what do they do
 Blocks of statements: how many and what do they contain

 Are there any remaining words that you’ve used /


typed?

Megha Patel @ Sheridan College 40


Declaring New classes in Python
• Classes are declared with the keyword class and the : symbol
• Must be followed by the definition of the class which is a
block

Megha Patel @ Sheridan College 41


Hands-On

HelloWorld-V5
class HelloMessage:
def show(self):
helloMsg = 'Hello programming world’
print(helloMsg)
courseMsg = 'Programming Foundations
Python’
print(courseMsg)
courseNo = 12583
print('#prog', courseNo, sep="")

msg = HelloMessage()
msg.show()
Megha Patel @ Sheridan College 42
Exercise: Breaking down Hello World
 Analyze the version of Hello World shown in the
previous slide
 Break down the program into elements and identify:
 Keywords: what are the Python keywords used
 Symbols: what are the Python symbols used
 Declarations: how many and what is being declared
 Predefined Python “words” – words defined by Python using
the Python keywords. These are used without being explicitly
declared
 Statements: how many statements and what do they do
 Blocks of statements: how many and what do they contain

 Are there any remaining words that you’ve used /


typed?

Megha Patel @ Sheridan College 43


import Statement
• Makes existing modules available to your program
• For example, makes the HelloModule available to the
HelloWorldv6 program
• The way programs are “stitched” together out of multiple
files / modules
• How we get access to the Python Standard Library modules
and other predefined Python code
• Makes program elements such as variables, functions and
classes, defined in other modules available to a program, we
must use the import statement
import <module-name>
• Imported program elements are available through the .
notation
<module-name>.<program-element-name>
Megha Patel @ Sheridan College 44
. (DOT) notation
• The . notation is used whenever you try to access
programming elements contained by others
<container-name>.<element-name>

Package

Module

Package Variables Classes & Objects


Functions Variables Methods

Megha Patel @ Sheridan College 45


HelloWorld-V6
Hands-On import HelloModule

msg = HelloModule.HelloMessage()
msg.show()

HelloModule
class HelloMessage:
def show(self):
helloMsg = 'Hello programming world’
print(helloMsg)
courseMsg = 'Programming Foundatons
Python’
print(courseMsg)
courseNo = 12583
print('#prog', courseNo, sep="")
Megha Patel @ Sheridan College 46
from Statement
• Extension of the import statement that copies all the
elements from the container where they are defined into
the module where they are used
from <module-name> import <element-name>
or
from <module-name> import *
• The * symbol stands for everything as in import all elements
• The from statement makes it look like the elements were
defined in the module they are used
• No need to access them using the DOT notation
• The imported module is unnamed
• Can generate naming conflicts if the module is already using
some of the names

Megha Patel @ Sheridan College 47


Module names
• The name of the module is the name of the file
without the .py extension
• Python naming convention is all lower case with
or without _ separating different words
• Spaces are not allowed in module names
• At runtime, the name of the module is stored in
built-in variable called __name__ (double
underscores before and after)
• The module used to start the program is called the
top-level or the main module or script
• At runtime, the __name__ built-in variable is
automatically set to “__main__” regardless of the
actual module name
Megha Patel @ Sheridan College 48
Exercise: Python Modules
• Using HelloWorldV6, experiment with the difference
between import and from statements
• Create a copy named HelloWorldV6b and use the from
statement instead of the import
• What chances do you have to make to the code and
why?
• Find out what is the __name__ of the modules in use
• In HelloWorldV6 add a print statement at the end of
the program
• print(‘Executed by ’, __name__)
• In HelloModule add a print statement at the end of the
show() method
• print(‘Message from ’, __name__)

Megha Patel @ Sheridan College 49


Exercise: Know your Python
• The Python Language and the Python Standard library are
documented at https://docs.python.org/3/
• Language reference documentation:
https://docs.python.org/3/reference/index.html
• Python Standard Library documentation:
https://docs.python.org/3/library/index.html
• Python tutorial:
https://docs.python.org/3/tutorial/index.html
• Using your browser inspect the documentation for the
• input() function (Built-in Function in the Standard
Library)
• The % operator and format() method (Input and Output
in Tutorial)

Megha Patel @ Sheridan College 50


Click to edit Master title style

Python Fundamentals

Megha Patel (2023), Raed Karim(2023)

1
Python Fundamentals
Click to edit Master title style
Objectives

At the end of this module, students will be able to:


• Define the fundamentals of computer programming with Python
language.
• Analyze code syntax.
• Apply the programming fundamentals by writing python programs using
the IDE (Visual Studio Code).
• Identify different types of errors in a program and fix them.
• Define and analyze numbers and arithmetic expressions through code.

2 2
Click to edit Master title style

Python Fundamentals
Part - 1

3 3
Python Fundamentals
Click to edit Master title style
Block of statements:

• A statement in Python is the instructions you type in the editor (visual


studio code) that interpreter executes, e.g., print(“Hello World!”). Python
interpreter executes the print statement and displays the result to the
console.
• A block is a group of statements in a program or script. Usually, it
consists of at least one statement and of declarations for the block,
depending on the programming or scripting language. Your code could
also contain nested blocks.

4 4
Python Fundamentals
Click to edit Master title style
Block of statements: an example of a block of statement (lines 3 and 4)

5 5
Python Fundamentals
Click to edit Master title style
Rules for coding Python

• Python relies on proper indentation.


• Unlike many programming languages, the indentation of each line
matters in a Python program. With Python, the indentation is typically
four spaces (or one tab).
• Python doesn't use braces { } to indicate blocks of code for class and
function definitions or flow control.
• Blocks of code are denoted by line indentation, which is rigidly
enforced. All statements within the block must be indented the same
amount.

6 6
Python Fundamentals
Click to edit Master title style
Indentation Examples:

• A good indentation in Python:

7 7
Python Fundamentals
Click to edit Master title style
Indentation Examples:
• An indentation that causes an error:

8 8
Python Fundamentals
Click to edit Master title style
Statement continuation:

• You can use implicit continuation.


• To do that, you divide a statement before or after an operator like a plus
or minus sign.
• You can also divide a statement after an opening parenthesis.

9 9
Python Fundamentals
Click to edit Master title style
Statement continuation:

• You can also use explicit continuation.


• To do that, you code a backslash to show that a line is continued.
• However, this way is discouraged.

1010
Python Fundamentals
Click to edit Master title style
Comments:

• Adding comments to programs is a very important practice in


programming.
• Comments are added for people (not the computer) to understand what
a part of the program does – they are notes added by programmers to
explain part for the code.
• Python interpreter ignores the comments – it does not execute them.
They have no effect on the operation of the program.

1111
Python Fundamentals
Click to edit Master title style
Comments:

• To add a comment to describe a portion of the code, type # then type


the python statement.
• You can also add a comment after the statement (inline comments).
• Another way to add a comment is by commenting out a python
statement, if you don’t want the interpreter to execute that statement
(this is mainly for testing purpose).

1212
Python Fundamentals
Click to edit Master title style
Comment examples:

1313
Python Fundamentals
Click to edit Master title style
Quotation in Python:

• In programming terms, a sequence of characters that is used as data is


called a string.
• When a string appears in the actual code of a program, it is called a
string literal.
• In Python code, string literals must be enclosed in quote marks.

1414
Python Fundamentals
Click to edit Master title style
Quotation in Python:

• Python accepts single ('), double (") and triple (''' or """) quotes to
denote string literals, as long as the same type of quote starts and ends
the string.
• The triple quotes are used to span the string across multiple lines. In
this case, the string can be a comment.

1515
Python Fundamentals
Click to edit Master title style
Quotation in Python:

• The quote marks are not displayed when the statement executes.
• The quote marks simply specify the beginning and the end of the text
that you wish to display.

output

1616
Python Fundamentals
Click to edit Master title style
Quotation in Python:

• If you want a string literal to contain either a single-quote or an


apostrophe as part of the string, you can enclose the string literal in
double-quote marks.
• Likewise, you can use single-quote marks to enclose a string literal that
contains double-quotes as part of the string.

output

1717
Python Fundamentals
Click to edit Master title style
Working with datatypes and variables in Python:

• We saw three different types of data in the previous examples – string


(str), integer (int) and floating-point (float).
• The str data type holds string literals.
• The int and float data types hold numerical literals.

1818
Python Fundamentals
Click to edit Master title style
Working with datatypes and variables in Python:

• When you develop a python program, you work with variables that store
data (values). Variables vary as code executes.
• To work with variables, you assign data to them using the assignment
operator (=). This is called (assignment statement).
• Initialization is when assign an initial value to a variable. Then different
values are assigned later in the program.
• You can assign literal values or literal strings to a variables.

1919
Python Fundamentals
Click to edit Master title style
Working with datatypes and
variables in Python:

• To code a literal value for a string,


enclose the characters of the string
in single or double quotation
marks. This is called a string literal.
• To code a literal value for a
number, code the number without
quotation marks. This is called a
numeric literal.

2020
Python Fundamentals
Click to edit Master title style
Working with datatypes and
variables in Python:

• You can also assign multiple


values to multiple variables in one
statement.

• Because variable names are


case-sensitive, you must be sure
to use the correct case when
coding the names of variables.

2121
Python Fundamentals
Click to edit Master title style
Working with datatypes and variables in Python:

Variables naming conventions that must be respected by programmers


• A variable name must begin with a letter or underscore.
• A variable name can’t contain spaces, punctuation, or special
characters other than the underscore.
• A variable name can’t begin with a number, but can use numbers later
in the name.
• Use underscore notation or camel case.
• Use meaningful names that are easy to remember.
• Don’t use the names of built-in functions, such as print().
2222
Python Fundamentals
Click to edit Master title style
Working with datatypes and variables in Python:

Variables naming conventions

A variable name can’t be the same as a keyword that’s reserved by Python.

Two naming styles for variables

2323
Python Fundamentals
Click to edit Master title style
The print() function:

• The print function is one of the most important built-in functions in


python that you will be using to print out and display the results
(outputs) of the code to the screen.
• A function is a reusable unit of code that performs a specific task.
• Python provides many built-in functions that do common tasks like
getting input data from the user and printing output data to the console.

2424
Click to edit Master
Python
title
Fundamentals
style

The print() function:

• When you call a function, you code the name of the


function followed by a pair of parentheses.
• Within the parentheses, you code any arguments
(could values of variables) that the function requires,
and you separate multiple arguments with commas.
• In a syntax summary like the one at the top of this
page, brackets [ ] mark the portions of code that are
optional.
• The italicized portions of the summary are the ones that
you have to supply.
• But note that the arguments are optional. If no
arguments are passed to this function, it prints a blank
line.

2525
Click to edit Master
Python
title
Fundamentals
style

The print() function:

2626
Click to edit Master
Python
title
Fundamentals
style

The print() function:

• Print can take other arguments like (sep)


and (end).
• sep: string inserted between values,
default a space.
• end: string appended after the last value,
default a newline.

2727
Click to edit Master
Python
title
Fundamentals
style
The type() function:

• type() is another built-in function that can


be used by programmers to debug their
code( debugging is the process of
identifying and fixing bugs in the software).
• It returns the class type of object (data)
passed to it, in between the parenthesis.
• The example, on the right, shows the data
type of list (line 1), tuple (line 2), string (line
3), float (line 4) and integer (line 5).
• We will discuss more of the data types
later.

2828
Click to edit Master
Python
title
Fundamentals
style

Type casting (conversions):

• There are two types of type conversion in


python; implicit and explicit type
conversions.
• In the implicit, python automatically
converts one data type to another.
• Python can perform the conversion of
lower datatypes to the higher without data
loss like converting integer to float.

2929
Click to edit Master
Python
title
Fundamentals
style
Type casting (conversions):

• In the explicit, programmers perform the conversion using some pre-defined functions
(e.g., int(), float(), str()).
• The int() converts numbers with decimals (e.g., 89.5) or literal values in between quotes (
‘123’) into integer.
• The float() converts integers to float format (adding a zero after the decimal point) or literal
values in between quotes into float.
• You cannot convert string literal into numbers (e.g., “abc” into a number).
• The str() converts values into strings (e.g., 87 into “87”).

3030
Click to edit Master
Python
title
Fundamentals
style
Type casting (conversions):

3131
Click to edit Master
Python
title
Fundamentals
style
Types of errors:

• As you test your program, three types of errors can occur.


• Syntax errors prevent your program from compiling and running. Since syntax
errors occur when Python attempts to compile a program, they’re known as
compile-time errors. This type of error is the easiest to find and fix.
• When you use Visual Studio Code, it highlights the location of the syntax errors
that it finds each time you attempt to run the program. Then, you can correct that
error and try again.

3232
Click to edit Master
Python
title
Fundamentals
style
Types of errors:

Common syntax errors


• Misspelling keywords.
• Forgetting the colon at the end of the opening line of a function definition, if clause,
else clause, while statement, for statement, try clause, or except clause.
• Forgetting an opening or closing quotation mark or parenthesis.
• Using parentheses when you should be using brackets, or vice versa.
• Improper indentation.

3333
Click to edit Master
Python
title
Fundamentals
style
Types of errors:

• Syntax error example (can you figure what causes theses errors?!)

3434
Click to edit Master
Python
title
Fundamentals
style
Types of errors:

• Runtime errors don’t violate the syntax rules, but


they throw exceptions (errors that python
interpreter generates and displayed in the
console or the terminal) that stop the execution of
the program. Many of these exceptions are due to
programming errors that need to be fixed.
• This example shows the runtime error occurs
when trying to divide a value by zero. You notice
that there was no syntax error meaning the
program was compiled and run and then python
threw an exception: ZeroDivisionError: division by zero

3535
Click to edit Master
Python
title
Fundamentals
style
Types of errors:

• Logic errors are statements that don’t cause syntax or runtime errors, but produce
the wrong results. In the example shown above the program produced a wrong
result. The value of average should be 90, not 260.
• It is the programmer’s responsibility to ensure that the code is written right so the
result is right.
• (can you try and fix the error ?!!)

3636
Click to edit Master
Python
title
Fundamentals
style

Class exercises: Do it yourself !

Write a python program to produce the following output (define variables


and assign values to them, then use print function).

3737
Click to edit Master
Python
title
Fundamentals
style

Class exercises: Do it yourself !

Write a python program that contains 4 variables for 4 grades of a


student. Assign values to the variables. Find the sum of the 4 grades.
Make sure to use explicit continuation for the sum statement. Print the
sum and use the end keyword in the print statement. Your program should
start with a comment that spans two lines to describe your code.

3838
Click to edit Master
Python
title
Fundamentals
style

Class exercises: Do it yourself !

Write a python program that assign 3 tax amounts to 3 variables all in one
statement. Then print all the values using one print statement with the sep
keyword.

3939
Click to edit Master title style

Working with numeric data


and arithmetic operations

1 1
Click to Fundamentals
Python edit Master title style

• Arithmetic operators consist of two or more


operands that are operated upon by arithmetic
operators.
• The operands in an expression can be either
numeric variables or numeric literals.
• The +, -, * and / are the same as those used in
basic arithmetic.
• Python also has an operator for integer division (//)
that truncates the decimal portion of the division. It
has a modulo operator (%), or remainder operator,
that returns the remainder of a division. And it has
an exponentiation operator (**) that raises a number
to the specified power.

2 2
Click to edit Master Python Fundamentals
title style

3 3
Click to Fundamentals
Python edit Master title style

• The order of precedence: when an expression


includes two or more operators, the order of
precedence determines which operators are applied
first. This order is summarized in the table in this
figure. For instance, Python performs all
multiplication and division operations from left to
right before it performs any addition and subtraction
operations.
• If you need to override the default order of
precedence, you can use parentheses. Then,
Python performs the expressions in the innermost
sets of parentheses first, followed by the
expressions in the next sets of parentheses, and so
on.

4 4
Click to Fundamentals
Python edit Master title style

• On the right side:

Code that calculates sales tax

Code that calculates the perimeter


of a rectangle

5 5
Click to Fundamentals
Python edit Master title style

• The compound assignment operators provide a shorthand way to code common


assignment statements.
• For instance, the += operator modifies the value of the variable on the left of the
operator by adding the value of the expression on the right to the value of the variable
on the left. When you use this operator, the variable on the left must already have
been initialized.
• The other operators, -= and *= work similarly.

6 6
Click to Fundamentals
Python edit Master title style

7 7
Click to Fundamentals
Python edit Master title style

Floating-point numbers:

• A floating-point number consists of a positive or negative sign, a decimal value for the
significant digits, and an optional exponent.
• Floating-point numbers provide for very large and very small numbers, but with a
limited number of significant digits. The float type can only use 16 significant digits to
store the number.
• To express the value of a floating-point number, you can use scientific notation.
• This notation consists of an optional plus sign or a required minus sign, a decimal
value for the significant digits, the letter e or E, and a positive or negative exponent.
For example:
2.302e+5

8 8
Click to Fundamentals
Python edit Master title style

Floating-point numbers:

• In this example, the number contains four significant digits (2.302), and the exponent
specifies how many places the decimal point should be moved to the right or to the
left. Here, the exponent is positive so the point is moved to the right and the value is:
230,200
• But if the exponent was negative (e-5), the point would be moved to the left and the
value would be:
.00002302
• An integer is an exact value that yields expected results.
• A floating-point number is an approximate value that can yield unexpected results
known as floating-point errors.

9 9
Click to Fundamentals
Python edit Master title style

Floating-point numbers:
• The floating-point numbers are approximate values,
not exact values. Look at this example:
• In this example, Balance should be 300.30
• As a result, they sometimes cause floating-point errors.

• To fix this error, we use round() function. The round()


function can take additional argument which is an integer
that represents the number of digits to display after the
decimal point.

1010
Click to Fundamentals
Python edit Master title style

The standard math module:


• The math module for Python provides many functions
for mathematical, trigonometric, and logarithmic operations.
• The floating-point numbers are approximate values,
not exact values. Look at this example:
Balance should be 300.30
• As a result, they sometimes cause floating-point errors.

• To fix this error, we use round() function. The round()


function can take additional argument which is an integer
that represents the number of digits to display after the
decimal point.

1111
Click to Fundamentals
Python edit Master title style

The standard math module:


• We list four common functions and the pi constant that required importing the math
module.
• You can use the ceil() function if you always want to round up (towards the ceiling).
And you can use the floor() function if you always want to round down (towards the
floor). See examples in next slide
* you can also use the exponential operator (**) to raise a number to the power.

1212
Click to Fundamentals
Python edit Master title style

The standard math module:


• The m in the import statement is called alias that is defined so we use through
the program instead of using the module name – math.

1313
Click to Fundamentals
Python edit Master title style

The standard math module:


• The m in the import statement is called alias that is
defined so we use through the program instead of
using the module name – math.

1414
Click to Fundamentals
Python edit Master title style

Class exercises: Do it yourself !


• Create a program that calculates a user’s weekly gross and take-home pay.
• Follow the Console (on the right) and assign values to the hours Worked and hourly pay rate.
Specifications Console
Pay Check Calculator
The formula for calculating gross pay is: Hours Worked: 35
ü gross pay = hours worked * hourly rate Hourly Pay Rate: 14.50
Gross Pay: 507.5
The formula for calculating tax amount is:
Tax Rate: 18%
ü tax amount = gross pay * (tax rate / 100) Tax Amount: 91.35
The formula for calculating take home pay is: Take Home Pay: 416.15
ü take home pay = gross pay – tax amount
• The tax rate should be 18%, but the program should store the tax rate in a variable so
you can easily change the tax rate later just by changing the value that’s stored in the variable.

1515
Click to Fundamentals
Python edit Master title style

Class exercises: Do it yourself !


• Create a program that calculates total sales and dsplays the following information to the
console.
• Follow the Console (on the right) and assign values to the cost of the meal and the tip percent.
Console
Tip Calculator
Cost of meal: 52.31
Tip percent: 20

Tip amount: 10.46


Specifications
Total amount: 62.77
The formula for calculating the tip amount is:
ü tip = cost of meal * (tip percent / 100)

1616
Click to Fundamentals
Python edit Master title style

Class exercises: Do it yourself !


• Create a program that converts the temperature in Celsius into Fahrenheit and vice versa.
• Follow the Console (on the right) and assign values to the cost of the meal and the tip percent.
Console
Temperature conversion Calculator
In Celsius: 20.0
In Fahrenheit: 68.0

In Fahrenheit: 68.0
In Celsius: 20.0
Specifications
The formula for calculating the tip amount is:
ü Fahrenheit = (Celsius * 9/5) + 32
ü Celsius = (Fahrenheit – 32) * 5/9

1717
References
Click to edit Master title style
Material has been taken from (can be accessed through Sheridan's Library Services) :

• Starting Out with Python (ISBN-13: 9780136912330 ):


• https://www.pearson.com/en-ca/subject-catalog/p/starting-out-with-
python/P200000003356/9780136912330

• Murach’s Python 2nd Edition programming, 2nd Edition :


• https://bookshelf.vitalsource.com/reader/books/9781943872756/pages/recent

• Introducing Python, Lubanovic, B., O'Reily Media, 2nd Edition, 2019


• https://www.oreilly.com/library/view/introducing-python-
2nd/9781492051374/
1818
Click to edit Master title style

3 Python Fundamentals(2)

Raed Karim[2023], Megha Patel[2023]

1
Python Fundamentals(2)
Click to edit Master title style
Objectives

At the end of this module, students will be able to:


• Prompt users to enter data from keyboard and process them in their
programs.
• Define and analyze strings.
• Define and implement strings functions and methods.
• Format program outputs in different data types; int, float and strings.
• Apply relational and logical operators.
• Define and implement Boolean expressions.
2 2
Click to edit Master title style

Python Fundamentals(2)
Part - 1

3 3
Python Fundamentals(2)
Click to edit Master title style
Getting inputs from users
• we use Python’s built-in function to read input from the keyboard.
• The function reads a piece of data that has been entered at the
keyboard and returns that piece of data, as a string, back to the
program.
• You normally use the function in an assignment statement that follows
this general format:

4 4
Python Fundamentals(2)
Click to edit Master title style
Getting inputs from users
• In the general format, prompt is a string that is displayed on the screen.
• The string’s purpose is to instruct the user to enter a value.
• variable is the name of a that references the data that was entered on
the keyboard.
variable = input(prompt)

• The input() function always returns string data, even if the user enters a
number.

5 5
Click to Fundamentals(2)
Python edit Master title style
Getting inputs from users
Look at the following example:

When this statement executes, the following things happen:


ü The string is displayed on the screen.
ü The program pauses and waits for the user to type the first
name on the keyboard and then to press the Enter key.
ü When the Enter key is pressed, the data that was typed is
returned as a string and assigned to the variable,
first_name. then print() displays the first name on the
screen along with the string “hello : “

6 6
Python Fundamentals(2)
Click to edit Master title style
Getting inputs from users
• The input() function always returns string data, even if the user enters a
number.
• if the program tries to add that variable to a variable with a numeric
data type, a TypeError exception ( a runtime error) occurs because you
can’t add a string to a number.

7 7
Click to Fundamentals(2)
Python edit Master title style
Getting inputs from users
• To fix that (the TypeError), you can use the int() and float()
functions.
• The functions perform type conversions, strings to numerical
values that can be used in the arithmetic operations.
• Suppose you are writing a payroll program and you want to get
the number of hours the two days that the user has worked for,
then adding them to get the total hours worked:

* the user inputs must match whatever the conversion functions


performs, meaning a user must enter an integer value to be
converted to an integer

8 8
Click to Fundamentals(2)
Python edit Master title style
Getting inputs from users
• In the previous example, you can chain the functions:
input() and int().
• The input() function is coded as the argument of the int()
function to make one python statement.
• In the same way, the input() function is coded as the
argument of the float() function.
• Suppose, we want to calculate the total cost of 5
products if we know the unit price of a product is $9.49:

9 9
Click to Fundamentals(2)
Python edit Master title style
Getting inputs from users
• You can prompt the user to enter multiple values in one
input statement.
• Python has a split() function that must be used so that
multiple data is assigned to multiple variables.
Look at the example on right!!

• Notice that we left one space between the two inputs: 3 5


• You can determine how to separate the inputs at the
prompt by adding an argument (a piece of data additional
information) inside the parenthesis, such a special
character from the keyboard; e.g., ( ,), (;), (:), (|), etc.
• Notice how we use the float() function to convert the two
inputs in line 2 of the program !

1010
Click to Fundamentals(2)
Python edit Master title style

Getting inputs from users: Do it yourself !

• Prompt the user to enter the value of miles driven by her vehicle.
• Prompt her again to enter the value of gallons consumed by the vehicle.
• Calculate the value of mpg (mile / gallons).
• Print the value of mpg.

1111
Click to edit Master title style

Python Fundamentals(2)
Part - 2

1212
Click to Fundamentals(2)
Python edit Master title style

Working with string data


Ø In the last week lesson, we learn a few things about string data
types in python such as quotations, assigning strings to variables,
printing string data and using str() function.
• In this week, we can dig a little deeper into this amazing type of
data: string !

Ø You can concatenate strings into a single unified string.


Concatenation means joining two or more string to form a single
one, like joining your first name then a space then your last name
to form your full name. The + operator is used to concatenate.
Note the + is also the addition operator to add numbers, as we
have learned last week.

1313
Click to Fundamentals(2)
Python edit Master title style

Working with string data


Ø Data in Python are objects, including strings. Objects are associated
with methods. In a particular str object a method called format.
Ø The syntax for methods is as follows:
object.methodname(parameters)

* parameters are pieces of data passed to methods to process it

1414
Click to Fundamentals(2)
Python edit Master title style

Working with string data


Ø You can also join strings with f-string.
Ø You can join strings with numbers into a single
string.

* Notice in line 10 of the code, we use str() to convert the


numerical value of age into a string to concatenate it with
other string data in the statement.

Try to remove str() from line 10 and run the program again,
What do you observe ? why?!!

1515
Click to Fundamentals(2)
Python edit Master title style

Working with string data


Ø You can access a character in a string using
indexes.
§ Each character in a string has an index that can
be zero, a positive or negative integer. It specifies
the position of the character in the string. From
the left side of the string, indexes start from zero,
and from the right starts with -1.

1616
Click to Fundamentals(2)
Python edit Master title style

Working with string data


Ø You can slice a string meaning you get a
span of characters from within the string.
Sometimes slices are called substrings.
How to slice a string:

* Python slices a string starting from the index at start to the


index at end - 1

1717
Click to Fundamentals(2)
Python edit Master title style

Working with string data


Ø You can use the repetition operator to
repeat a string.

1818
Click to Fundamentals(2)
Python edit Master title style
Working with string data
Ø Strings are immutable meaning that means once they are created, they cannot
be changed or modified.
• Some operations, such as concatenation or slicing, give the impression that
they modify strings, but in reality they do not.
• In the first example, we do not change the string name rather we
concatenate it with two new strings, a single space and ‘Patel’ to create a
new string of name (line2).

• In the second example, we try to change the first character of the string
referred to with the variable name.
• Since strings are immutable, python threw an exception.

1919
Click to Fundamentals(2)
Python edit Master title style

Working with string data


Ø Python has a built-in function (len) that returns the
length of a string (the number of characters contained in
the string .

string length: len(string)

* Len function can also be used for the other sequences in


python as we will learned about in future.

2020
Click to Fundamentals(2)
Python edit Master title style
Working with string data
Ø Python offers a set of built-in methods that can used to work
with strings. Built-in methods are programs have been
developed and are ready to use by programmers. They are
loaded to your computer when you installed python interpreters.
§ The two first groups in the table, methods return either True
or False value after they have been processed by the
interpreter.

* The Python Boolean type is one of Python's built-in data


types. It's used to represent the truth value of an expression.
For example, the expression 1 <= 2 is True , while the
expression 0 == 1 is False . Understanding how Python
Boolean values behave is important to programming.

2121
Click to Fundamentals(2)
Python edit Master title style

• Working with string data: examples

2222
Click to Fundamentals(2)
Python edit Master title style

Working with string data: testing a string with in and not in


Ø In Python, you can use the operators ( in ) or ( not in ) to determine whether one string is contained in another
string. The syntax is:
string1 in string2

Ø The expression returns true if string1 is found in strings; otherwise, it returns false.

Ø You can also use the operator to determine whether one string is not contained in another string.

string1 not in string2

2323
Click to Fundamentals(2)
Python edit Master title style

Working with string data: Do it yourself!


Ø Look at the code shown on the right side to implement
string methods: your task is to add a print statement after
each block of statements to display its output

2424
Click to Fundamentals(2)
Python edit Master title style

Working with string data


Ø You can use the split() method to split a string into a list of strings.

2525
Click to Fundamentals(2)
Python edit Master title style
Working with string data
Ø In the code shown on the right,
the string quotation is split into a set
of words with the space delimiter,
since no parameter is supplied in
the split() method.

* A delimiter is a character that’s used to divide


a string into multiple parts.

2626
Click to Fundamentals(2)
Python edit Master title style

Working with string data


Ø You can use the join() method to join a list of strings into
a single string.
§ In the example, the second statement specifies the pipe
character (|) as the delimiter for the strings in the list. As
a result, the joined string consists of each item in the list
separated by the pipe character.

2727
Click to Fundamentals(2)
Python edit Master title style

Working with string data: Do it yourself?


Ø A variable, word, hold a string value of ‘Sheridan’, use the string method, join
to produce the following output: S h e r i d a n

2828
Click to Fundamentals(2)
Python edit Master title style

Working with string data: escape sequences


Ø Escape sequences to include special characters
Ø These sequences let you put characters in a string that you
can’t put in just by pressing the appropriate key on the
keyboard. For instance, the \n escape sequence is similar to
pressing the Enter key in the middle of a string.
Ø On the right side, a table that shows how to use escape
sequences.

2929
Click to Fundamentals(2)
Python edit Master title style

Working with string data: escape sequences


Ø Escape sequences are needed so the Python compiler can interpret the code correctly. For instance, since single and
double quotations marks are used to identify strings, coding them within the strings can cause syntax errors. But when
the quotation marks are preceded by escape characters, the Python compiler can interpret them correctly. Escape
sequences to include special characters

In the example, the new line sequence is used to start a new line.
In the example, four ways to include quotation marks in a string

3030
Click to Fundamentals(2)
Python edit Master title style
Working with string data: escape sequences
Ø Escape sequences are needed so the Python compiler can interpret the code correctly. For instance, since single and double
quotations marks are used to identify strings, coding them within the strings can cause syntax errors. But when the quotation
marks are preceded by escape characters, the Python compiler can interpret them correctly. Escape sequences to include
special characters

In the example, adding a tab within a string.


In the example, the backslash sequence is used to display a backslash
character.

3131
Click to Fundamentals(2)
Python edit Master title style

Working with string data: : using format method()


Ø There is a particular operation on strings called format, that makes substitutions into places enclosed in
braces.
Ø There could be multiple replacements in the format approach as shown in the example below.
Ø Each place in the format string where there is '{}', the format operation will replace the value of the next
parameter in the format parameter list.

3232
Click to Fundamentals(2)
Python edit Master title style

Working with string data: using format method()


Ø In the first example, python replaces {} with the value of the
format parameter, name. here the value of variable name is
taken from the user (line 1).

Ø In the second example, the object contains three places.


format(instructor, subject, term) replaces the places with the
three parameters: instructor, subject, term. Their values are
entered by the user (lines 1,2 and 3)

3333
Click to Fundamentals(2)
Python edit Master title style

Working with string data: using format method()


Ø With the format () method, you can number the places. You can choose any order of numbers, like: {2},{0},{1}.

3434
Click to Fundamentals(2)
Python edit Master title style
Working with string data: using format method()
Ø With the format () method, you can format float numbers by providing additional information with { }.
Ø You can specify how many decimal digits to format a number, the syntax:
{m.nf}.format(x)
m: the order of the value to place , n: the number of digits to format , f: indicates the number is float type
Ø In the example, the first value is a literal string, the second is a float value with 2 digits after the decimal point, the last value is
another float with 3 digits after the decimal point. Note that you can specify the order of places by entering them within { } and
before :

3535
Click to Fundamentals(2)
Python edit Master title style

Working with string data: Do it yourself!


Ø Write a python program to display the output as shown in the sample below. Use string methods and format method.
There is a tab in each of the third and fourth lines. Using format() round the amount in dollar to 3 digits.

JZCORP
Business Account
a link to the file: C:\users\jzcorp\ba.txt
amount in dollar: 456.45912

3636
Click to Fundamentals(2)
Python edit Master title style

Working with string data: formatting strings


Ø In python you can also format your string with % operator. You can print characters at some specific locations on the
line that has tabular format.
Ø To specify the print format you need to use a specific field width (field width specifiers). Field width is the total number
of spaces a string must use, including any spaces. The syntax to format a string:
(“%Ns” % “string-to-format”)
N is the number of spaces a string must use; s indicates the type of data is string.
If N is positive then is Right-Justified, negative is Left-Justified.

3737
Click to Fundamentals(2)
Python edit Master title style

Working with string data: formatting strings (more examples)


Ø

in the example, the first name is right justified by 15 spaces (line 2), and
in the example, the first name is right justified (line 2) and left justified by 15 spaces (line3).
last name is left justified by 14 spaces both in the same print() line.

3838
Click to Fundamentals(2)
Python edit Master title style

Working with string data: formatting integer and float numbers


Ø To format integers you use the same syntax, as in strings, but instead of s you use d, which specifies integer data type.

(“%Nd” % number)

Ø If you have to tabulate multiple numbers, you can use multiple format operators
(“%Nd%Nd%Nd” % (num1, num2, num3))

Ø In cases like this the first %N applies to num1, the second to num2, and so on.

3939
Click to Fundamentals(2)
Python edit Master title style

Working with string data: formatting integer and float numbers (examples)

4040
Click to Fundamentals(2)
Python edit Master title style

Working with string data: formatting integer and float numbers


Ø We have seen how to format a floating point number, such as the format() function, format method, and round()
function. You also can format using ( % ) operator following the syntax:

(‘%n.mf’%(float numbers)
n is the number of spaces to use, and m the decimal digits, f floating point data type.
To left justify use a negative n.

4141
Click to Fundamentals(2)
Python edit Master title style

Working with string data: formatting integer and float numbers (examples)

4242
Click to Fundamentals(2)
Python edit Master title style
Working with string data: Do it yourself!
1. Personal Information
Write a program that displays the following information:
Your name
Your address, with city, state, and ZIP
Your telephone number
Your college major
2. Sales Prediction
A company has determined that its annual profit is typically 23 percent of total sales. Write a program that asks the user to enter the projected amount of total sales,
then displays the profit that will be made from that amount.
3. Land Calculation
One acre of land is equivalent to 43,560 square feet. Write a program that asks the user to enter the total square feet in a tract of land and calculates the number of
acres in the tract. Hint: Divide the amount entered by 43,560 to get the number of acres.

4. Write a python program that create the output as shown in the screenshot (make sure to format the data as
you learned in this lesson:

4343
Click to edit Master title style

Python Fundamentals(2)
Part - 3

4444
Click to Fundamentals(2)
Python edit Master title style

Working with relational and logical operators


Ø Boolean expressions (or conditional expressions) are logical statements (in a programming language) that can be used
to test the relationships between two or more values if a specific relationship is True or False (e.g., user_name ==
‘r2kar’). Here, we test if user name is equal to ‘r2kar’, if it is, the result is True; otherwise, False.
Ø The Boolean expressions use six relational operators as summarized in the table shown below:

*Boolean expressions, named in honor of the English mathematician George Boole. In the 1800s, Boole invented a system of
mathematics in which the abstract concepts of true and false can be used in computations.

4545
Click to Fundamentals(2)
Python edit Master title style

Working with relational and logical operators


Ø In the example, (lines 1-2), we compare the value of age with 39 if
they are equal; both are integers. In lines(4-5), we compare the
value of user_name with the value of ‘r2kar’ if they are equal; both
are literal strings. The same is in lines(7-8), but the values we
compare are float numbers.
Ø In lines(10-11), we compare a string with a number which causes
a runtime error. You need to make sure that your expressions
compare numbers with numbers and strings with strings.

4646
Click to Fundamentals(2)
Python edit Master title style

Working with relational and logical operators


Ø To code a compound conditional expression, you can use the logical operators as shown in the table below:

Ø If you use the AND operator, the compound expression only returns True if both expressions are True. If you use the OR
operator, the compound expression returns True if either expression is True. If you use the NOT operator, the value
returned by the expression is reversed (True to False and vice versa).

4747
Click to Fundamentals(2)
Python edit Master title style

Working with relational and logical operators


Ø The logical operator also have the order of precedence as shown below:

Ø That is the order in which the operators are evaluated if more than one logical operator is used in a compound
expression. This means that NOT operators are evaluated before AND operators, which are evaluated before OR
operators. Although this is normally what you want, you can override this order by using parentheses.

4848
Click to Fundamentals(2)
Python edit Master title style

Working with relational and logical operators: (examples)

4949
Click to Fundamentals(2)
Python edit Master title style

Working with relational and logical operators: comparing strings


Ø When numbers are compared, they are compared based on their numeric values. By contrast, the comparison of strings
is more complicated. They are evaluated on a character by character basis from left to right. Thus, “peach” comes before
“pear”.
Ø To understand string comparisons, though, you need to know the sort sequence of the letters and digits.
Ø The digits are lower than (come before) all uppercase letters, and uppercase letters are lower than (come before) all
lowercase letters. But that means that “Peach” comes before “apple”, which isn’t usually what you want when you sort or
compare two strings.

5050
Click to Fundamentals(2)
Python edit Master title style
Working with relational and logical operators: comparing strings
Ø To resolve this issue of strings comparison, Python provides two
string methods. The lower() method converts a string to all
lowercase letters. The upper() method converts a string to all
uppercase letters.

Ø You call the method with the dot ( . ) notation, starting with a
string then dot following by one of these methods:
my_str = ‘karim’
my_str.upper()
Ø By converting both operands to the same case (lower or upper)
you can make the comparisons without getting unexpected
results.

5151
Click to Fundamentals(2)
Python edit Master title style
Pseudocode for writing selection (Decision) structures
Ø To resolve this issue of strings comparison, Python provides two
string methods. The lower() method converts a string to all
lowercase letters. The upper() method converts a string to all
uppercase letters.

5252
Click to Fundamentals(2)
Python edit Master title style
Working with string data: Do it yourself!
Problem 1
• How would you compare the followings: (YES, yes), and (NO, no)? Hint: what methods would you use?
• Then use one of these methods to compare them with a user input and display the result (True or False).
• Then use a logical operator to combine both terms in one Boolean expression to compare and display the result.
Problem 2
• Suppose that we have three variables (day, ticketPrice and status) – the day can be either weekday or weekend; the
status can be one of the following: a student, a child less than 14 years old, or an elder greater than 65 years old.
• Use logical operators to test the three variable all in one line by joining them in a compound conditional expression.
Then display the result (True or False)

5353
References
Click to edit Master title style
Material has been taken from (can be accessed through Sheridan's Library Services) :

• Starting Out with Python (ISBN-13: 9780136912330 ):


• https://www.pearson.com/en-ca/subject-catalog/p/starting-out-with-
python/P200000003356/9780136912330

• Murach’s Python 2nd Edition programming, 2nd Edition :


• https://bookshelf.vitalsource.com/reader/books/9781943872756/pages/recent

• Introducing Python, Lubanovic, B., O'Reily Media, 2nd Edition, 2019


• https://www.oreilly.com/library/view/introducing-python-
2nd/9781492051374/
5454
4 Decision (Selection) Structures,
Turtle Module and Debugger

Raed Karim[2023], Megha Patel[2023]

1
Decision Structures
Objectives

At the end of this module, students will be able to:


• Write pseudocode for Decision structures to plan for programming.
• Define and analyze the three types of Decision structures:
§ Single alternative Decision Structures.
§ Dual alternatives Decision Structures.
§ Multiple alternatives Decision Structures.
• Analyze and implement Turtle module to help solve decision problems.
• Run and debug program using debugger and othre testing and
debugging techniques.
2
Writing Pseudocode for Decision
Structures
Part - 1

3
Decision Structures
Introduction to Decision Structures
• A decision structure (or selection structure) allows a program to perform actions
only under certain conditions.
• An if statement lets you control the execution of statements based on the results of
a Boolean expression.
• Different types of decisions include:
• If, also called single alternative
• If then else, also called dual alternative
• If, else if then else structure for multiple alternative decisions

4
Decision Structures
Designing a program
• Before we delve into and work with decision structure, let’s understand how a
program should be designed in order to implement it (code it).
Two steps in designing a program:
1. Understand the tasks that the program is to perform.
• Learning what the customer wants.

2. Determine the steps that must be taken to perform the task.


• Create an algorithm, or step-by-step directions to solve the problem.
• Use flow charts and/or pseudocode to solve.

5
Decision Structures
Designing a program
• We use Pseudocode and/or Flowcharts to help design programs.
• The design is the foundation of a good program- a program that works and
produces expected results.

The program development cycle

6
Decision Structures
Designing a program
• Pseudocode is fake code used as a model for programs.
• No syntax rules
• Well written pseudocode can be easily translated to actual code (e.g., python).
An example of a pseudocode that allows a user to enter the values of hours worked
and a pay rate for an employee, then the gross pay value is calculated (the fifth
step); last, the output is displayed.

Display "Enter the number of hours"


Input hours
Display "Enter the hourly pay rate"
Input payRate
Set grossPay = hours * payRate
Display "The gross pay is $", grossPay

7
Decision Structures
Designing a program
Flowchart for the pay calculating program
• Flowchart is a diagram that graphically depicts
the steps that take place in a program.

8
Decision Structures
Designing a program
• Flowchart Connector Symbol
• Use connectors to break a flowchart into two
or more smaller flowcharts and placing them
side-by-side on the page.

9
Decision Structures
Designing a program
• Calculate the batting average for any player

Batting Average = Hits ÷ Times at Bat

Determine what is required for each phase of the program:


1. What must be read as input?
2. What will be done with the input?
3. What will be the output?

10
Decision Structures

Designing a program
• Input is received.
• The number of hits
• The number of times at bat
• Some process is performed on the input.
• Calculate the batting average
• Divide the number of hits by the number of
times at bat
• Output is produced.
• The player’s batting average

11
Decision Structures

Designing a program

12
Decision Structures

Designing a program

• The benefit of the pseudocode is that you can plan the logic without worrying
about coding details like parentheses, quotation marks, and colons. As a result,
you can document the logic more quickly and experiment with multiple
approaches before you decide on the best one and use it as your guide to the
Python coding.
• In practice, you often write out your pseudocode by hand. Because you’re the
only one who is going to use it, it doesn’t need to be neat or formal. Then, after
you’ve coded and tested the Python code, you usually throw away the
pseudocode.

13
Decision Structures

Intro to Decision Structure: a single alternative structure


A single alt. decision structure
for an everyday task
The if statement:
• An action only occurs (pseudocode
of a single If statement)
If condition Then
statement
statement
End If

14
Decision Structures

Intro to Decision Structure: a single alternative structure

Relational Operators:
• Determines whether a specific
relationship exists between two
values
• Used within the condition, a Boolean
expression
• A single alt. decision structure for an
everyday task

15
Decision Structures
Intro to Decision Structure: dual alternative structure
If then else statement
– Executes one group of statements if it’s
Boolean expression is true, or another
group if its Boolean expression is false
A dual alternative decision structure

16
Decision Structures
Intro to Decision Structure: dual alternative structure
If condition Then If temperature < 40 Then
statement Display "A little cold"
Display "Get a coat!"
statement Else
Else Display "Nice weather"
statement Display "And sunny!"
statement
End If
The If statement checks for the temperature if it’s less than 40.
End If If it evaluates the condition to Ture, then two Display
statements are executed:
Display "A little cold"
Display "Get a coat!"

However, if it evaluates the condition to False the Else clause


is executed and the two Display statements are executed:
Display "Nice weather"
Display "And sunny!"
17
Decision Structures
Intro to Decision Structure: dual alternative structure
Indentation in the if-else Statement

When you write an statement, follow these


guidelines for indentation:

• Make sure the if clause and the else clause are


aligned.
• The if clause and the else clause are each
followed by a block of statements.
• Make sure the statements in the blocks are
consistently indented.

Pseudocode to compare two strings


18
Decision Structures
Intro to Decision Structure: multiple alternative structure
Decisions are nested in order to test more
than one condition
If salary >=3000 Then
if yearsOnJob >= 2 Then
Display " You qualify for
the loan. "
Else
Display " You must have
been on your current
job for at least two
years to qualify. "
Else
Display " You must earn at least
$3000 per year to qualify. " A nested decision structure
End If
19
Decision Structures
Intro to Decision Structure: multiple alternative structure
• Decisions are nested in order to test more
than one condition
If salary >=3000 Then
if yearsOnJob >= 2 Then
Display " You qualify for
the loan. "
Else
Display " You must have
been on your current
job for at least two
years to qualify. "
Else
Display " You must earn at least
$3000 per year to qualify. " A nested decision structure
End If
20
Decision Structures
Intro to Decision Structure: multiple alternative structure
How the nested if structure works in the previous slide?

The outer if checks for the salary if greater or equal to $3000. If the condition is
evaluated to True the inner if clause is executed; otherwise, the Else clause is
executed and the message " You must earn at least $3000 per year
to qualify. “ is displayed.
Inside the outer if the condition (yearsOnJob >= 2) is evaluated to True, the
Display " You qualify for the loan. " is executed; otherwise,
Display " You must have been on your current job for at
least two years to qualify. “ is executed.

21
Decision Structures
Intro to Decision Structure: multiple alternative structure
• In this example, after getting the value of • Another way to implement the multiple alternative decision
score from the user, the if clause checks for structure.
the score value. If (score < 60) is evaluated to Read score
True, the Display "Grade is F. " is If score < 60 Then
executed, and the interpreter exists the entire Display "Grade is F."
if structure, and continues in the program after Else If score < 70 Then
the if structure. However, if the condition is Display "Grade is D."
evaluated to False, the Else If is evaluated,
Else If score < 80 Then
and the process continues in the same way.
Display "Grade is C."
• In a single run, only one clause in the if Else If score < 90 Then
structure is executed depends on how the Display "Grade is B."
condition gets evaluated. Else
Display "Grade is A."
End If

22
Decision Structures

Pseudocode Exercise: Do it yourself !

• Design a program that solves the following problem: Hint: if someone asks you to design a
program, the first thing should come to your mind is NOT to code because design happens before
coding. To design you write a pseudocode and/or draw a flowchart.
• The user enters a customer type (‘r’ , or ‘w’) and the total of purchases.
• The program checks for the customer type (‘r’), if evaluated to True, it checks for the total. If the
total > 0 and < $100, the discount percent is 0.1; if total >= $100 and < $250, the discount percent
is 0.2; if the total >= $250 and < $500, the discount percent is 0.3; otherwise, the discount percent
is 0. 4.
• If the customer type (‘r’) is evaluated to False, it checks for type (‘w’); if it’s evaluated to True, the
program checks for the following: if the total of purchases > 0 and < $300, the discount percent is
0.15; if the total is >= $300 and < $600, the discount percent is 0.25; otherwise, it sets to 0.35.
• If the customer type neither (‘r’) nor (‘w’), the discount percent is set to 0.
• Outside the if structure, your program should print the total before the discount, the discount
percent, the discounted amount and the final total that customer should pay.
23
Implementing Decision
Structures with Python
Part - 2

24
Decision Structures
Intro to Decision Structure

Now, we have learned about if (decision) structures and how it works using the
pseudocode. Remember that the decision structure is just part of your program.

Let’s try the decision structures with Python !

In the following slides, you will see implementations of the three types of the
decision structures.

25
Decision Structures
Implementing the Decision Structures

Python syntax

Notice the following:

ü In python, we use elif instead of else if in the pseudocode.


ü Indentation must be respected ! Otherwise python interpreter complains with syntax
errors.
ü The ( : ) at the end of the if , elif and else statements !
ü No End If at the end of the structure.

26
Decision Structures
Implementing the Decision Structures: examples

27
Decision Structures
Implementing the Decision Structures: examples

28
Decision Structures
Implementing the Decision Structures: examples

29
Decision Structures
Implementing the Decision Structures: examples

30
Decision Structures
Implementing the Decision Structures: examples

31
Decision Structures
Implementing the Decision Structures
Checking Numeric Ranges with Logical Operators
• Sometimes you will need to design an algorithm that determines whether a
numeric value is within a specific range of values or outside a specific range of
values. When determining whether a number is inside a range, it is best to usethe
and operator.
• For example, the following if statement checks the value in x to determine whether
it is in the range of 20 through 40:
if x >= 20 and x<=40:
print(“ the value is withing the acceptable range”)

32
Decision Structures
Implementing the Decision Structures
Checking Numeric Ranges with Logical Operators

• The compound Boolean expression being tested by this statement will be true
only when is greater than or equal to 20 and less than or equal to 40.

33
Decision Structures
Implementing the Decision Structures
Checking Numeric Ranges with Logical Operators
• When determining whether a number is outside a range, it is best to use the or
operator. The following statement determines whether x is outside the range of 20
through 40:.

if x < 20 or x > 40:


print(“ the value is outside the acceptable range”)

34
Decision Structures

Decision Structures implementation Exercise: Do it yourself !

1. Tip Calculator:
• Create a program that calculates three options for an
appropriate tip to leave after a meal at a restaurant.
• Specifications
• The program should calculate and display the cost of
tipping at 15%, 20%, or 25%.
• Assume the user will enter valid data.
• The program should round results to a maximum of
two decimal places.

35
Decision Structures

Decision Structures implementation Exercise: Do it yourself !


2. Shipping Calculator
• Create a program that calculates the total cost of an order including shipping.
• Use the following table to calculate shipping cost:
COST OF ITEMS SHIPPING COST
============= ==============
< 30.00 5.95
30.00-49.99 7.95
50.00-74.99 9.95
>= 75.00 FREE

• After entering the cost of items, your program validates the user input (the cost value) so only values
that are greater than 0 should be accepted and processed; otherwise, no processing can occur and the
program displays an error message for the user. Hint: use this if statement after the input statement:
if cost_of_items > 0:

36
Decision Structures

Decision Structures implementation Exercise: Do it yourself !


2. User name and password
• Create a program that prompts the user to enter the user name and password (e.g., raedk1, user123).
• The program checks for the user name and password entered by the user, if they match predetermined values (e.g., raedk1,
user123).
• If they match, the program displays a message “You’re logged in!”; otherwise, it displays “Incorrect information.”
• Last, the program dispalys a message “Thanks for using my program!”.

*prompts: it’s a professional keyword programmers use to mean “asks”. As a programmer you should
get used to use professional/technical terminology J

37
Learning Python Turtle Module
Part - 3

38
Turtle Module

Introduction to Turtle Module

• A Python Module is a library of programming solutions for specific tasks.


• The turtle graphics library provides numerous functions that you can use in
decision structures to determine the state of the turtle and conditionally
perform actions.
• For example, there is a math module that contains all functions pertaining
to math functions only.
• For example, the Turtle module contains functions to draw graphics.

39
Turtle Module

Introduction to Turtle Module

• There are many modules in Python.


• The advantage of modules is that instead of writing code from scratch all
the time, a module can be called to solve a particular problem.
• This is the concept of software re-utilization.
• There is no need to invent the wheel every time, if the wheel exists
already, then just use it.

40
Turtle Module
Introduction to Turtle Module

• The Python Turtle Module is used to draw.


• A “turtle” leaves a trail as it moves.
• By directing the direction of the movement, lines or shapes can be
obtained.
• Turtle Graphics is a fun way to introduces several concepts in Python
programming, from basics to complex drawings.

41
Turtle Module
Introduction to Turtle Module

• First, call the module (import turtle)


• After the module is imported into Python IDLE, the Python Objects of
the Turtle module are available to be used.
• An Object has:
• Methods: like movement actions (forward, backward, right, left)
• Attributes: like colour, shape, position, width, speed.

Object screen Attributes:


Colour blue
Width = base x
height
42
Turtle Module
Introduction to Turtle Module

• What do we need to make a drawing?


• We need a canvas to draw, a screen. So we need to call a method that
provides such screen.
• We need to specify (or customize) the looks of the screen. So we need to
modify the attributes to do that.
• How do we make the drawing?
• We need something that makes the drawings. So, we need to call the method
to create the “turtles”.
• We need to move them in the direction and distance that we want. So, we
need to supply the attributes to do that.

43
Turtle Module
Introduction to Turtle Module

• What do we need to make a drawing?


• Make the screen. Give it a name.
• Make the screen, call the method that makes screens.
• Customize it, if you want.

• How do we make the drawing?


• Make the turtle. Give it a name.
• Call the method that makes turtles.
• Customize it, if you want.

44
Turtle Module
Introduction to Turtle Module

45
Turtle Module
Introduction to Turtle Module

46
Turtle Module
Introduction to Turtle Module

47
Turtle Module
Introduction to Turtle Module

48
Turtle Module
Introduction to Turtle Module

49
Turtle Module
Introduction to Turtle Module

50
Turtle Module
Introduction to Turtle Module

51
Turtle Module
Introduction to Turtle Module

Result

52
Turtle Module
Introduction to Turtle Module

• import turtle means: “tell Python to load


the module named turtle”.
• Such module contains, among other
things, two types: the screen type and
the turtle type.
• turtle.Turtle means: “Python, use the
turtle type as defined in the turtle
module.
• Python is case sensitive, the module
name is turtle and the type name is
Turtle.

53
Turtle Module
Introduction to Turtle Module

1. Call the module library (import the_name_of_the_module)


2. Create a working space (canvas or screen wn = turtle.Screen()
3. Create a turtle. (example = turtle.Turtle()
4. Instruct it to move. (The object is moved by invoking the methods)
• The dot symbol means “referred to”, for example:
• something.method

54
Turtle Module
Introduction to Turtle Module

• The table at: www.w3schools.com/colors/colors_names.asp


contains all the colour definitions supported by all browsers.

55
Turtle Module
Introduction to Turtle Module
• The table at: www.w3schools.com/colors/colors_names.asp
contains all the colour definitions supported by all browsers.
• Colours can be called by names or numbers (hex), for example:
• Grey is 808080
• Black is 000000
• Blue is 0000FF
• Ghost white is F8F8FF
• screen_name.bgcolor(‘grey’)
• screen_name.bgcolor(‘aqua’)
56
Turtle Module
Introduction to Turtle Module

• Each turtle is an independent object or instance of the turtle


type (belonging to a class).
• Each instance has its own attributes and methods.

We will talk more later about classes, objects, attributes and


methods.

57
Turtle Module

Turtle Exercise: Do it yourself!

• Make two turtles: blue and red.


• Concept: each turtle is an independent object or instance of
the turtle type (belonging to a class).
• One turtle draws a square.
• The other turtle draws a bigger square.
• Concept: each instance has its own attributes and methods.

58
Turtle Module

59
Turtle Module

• Red turtle
executes next.
• Just as in the
order written in
the program.

• Blue turtle executes


first.

60
Determining Turtle state
Part - 4

61
Turtle Module
Introduction to Turtle Module

• You can use the turtle.xcor() and turtle.ycor() functions to get


the turtle’s current X and Y coordinates.
• The following code snippet uses an if statement to determine
whether the turtle’s X coordinate is greater than 249, or the
turtle’s Y coordinate is greater than 349. If so, the turtle is
repositioned at (0, 0):

if turtle.xcor() > 249 or turtle.ycor() > 349 :


turtle.goto(0,0)
62
Turtle Module

Introduction to Turtle Module

• The turtle.heading() function returns the turtle’s heading. By default, the


heading is returned in degrees.
try: turtle.heading()
• The following code snippet uses an if statement to determine whether the
turtle’s heading is between 90 degrees and 270 degrees. If so, the turtle’s
heading is set (using setheading() to 180.

If turtle.heading() >= 90 and turtle.heading()<= 270:


turtle.setheading(180)

63
Turtle Module

Introduction to Turtle Module


• In Python, you can use the command to raise the pen, and the command to
lower the pen. When the pen is up, you can move the turtle without drawing a
line. When the pen is down, the turtle leaves a line when it is moved. (By
default, the pen is down.)
• When you execute the function turtle.pencolor()without passing it an
argument, the function returns the pen’s current drawing color as a string.
turtle.pencolor() # it returns the current color
• The following code snippet uses an if statement to determine whether the pen’s
current color is red. If the color is red, the code changes it to blue:

If turtle.pencolor() == ‘red’:
turtle.pencolor(‘blue’)
64
Turtle Module
Introduction to Turtle Module

65
Testing and Debugging
Part - 5

66
Testing and Debugging

• When you test a program, you run it to make sure that it works correctly. As you test
the program, you try every possible combination of input data and user actions to
be certain that the program works in every case. In other words, the goal of testing
is to make the program fail.
• When you debug a program, you fix the errors (bugs) that you discover during
testing. Each time you fix a bug, you test again to make sure that the change you
made didn’t affect any other aspect of the program.

67
Testing and Debugging

• The goal of testing :


To find all errors before the program is put into production.
• The goal of debugging:
To fix all errors before the program is put into production

Common syntax errors:


• Misspelling keywords.
• Forgetting the colon at the end of the opening line of a function definition, if clause, else clause, while
statement, for statement, try clause, or except clause.
• Forgetting an opening or closing quotation mark or parenthesis.
• Using parentheses when you should be using brackets, or vice versa.
• Improper indentation.

68
Testing and Debugging

• We knew from Week 2 that there are three types of errors might occur in a program.
• Syntax errors prevent your program from compiling and running. Since syntax errors occur
when Python attempts to compile a program, they’re known as compile-time errors. This
type of error is the easiest to find and fix. When you use Visual Studio Code, it highlights
the location of the first syntax error that it finds each time you attempt to run the program.
Then, you can correct that error and try again.
• Unfortunately, some errors can’t be detected until you run a program. These errors are
known as runtime errors, and they throw exceptions that stop the execution of a program.
• Even if a program runs without throwing exceptions, it may contain logic errors that prevent
the program from working correctly. This type of error is often the most difficult to find and
fix.

69
Testing and Debugging

Problems with names and values:


• Misspelling or incorrectly capitalizing a variable or function name.
• Using a keyword as a variable or function name.
• Not checking that a value is the right data type before processing it. For example, using a number
when it needs to be converted to a string, or vice versa.
Problem with floating-point arithmetic:
• The float data type in Python uses floating-point numbers, and that can lead to arithmetic results that
are imprecise. For example:
sales_amount = 74.95; discount = sales_amount * .1;
# result is 7.495000000000001
• One quick way to fix this problem is to round the result to the right number of decimal places. If
necessary, you can also convert it back to a floating-point number:
discount = round(discount, 2) # result is 7.5

70
Testing and Debugging

The two critical test phases:


• Test the program with valid input data to make sure the results are correct.
• Test the program with invalid data or unexpected user actions. Try everything you can think of to make the program fail.
How to make a test plan for the critical phases:
• List the valid entries that you’re going to make and the correct results for each set of entries. Then, make sure that the results
are correct when you test with these entries.
• List the invalid entries that you’re going to make. These should include entries that test the limits of the allowable values.
Two common testing problems:
• Not testing a wide enough range of entries.
• Not knowing what the results of each set of entries should be and assuming that the answers are correct because they look
correct.

71
Testing and Debugging

Tracing code execution


• When you trace the execution of a program, you add statements to your code that
display messages or variable values at key points in the code. You typically do this
to help find the cause of a logic error. You can insert print() functions into the code
to print values or displaying messages.

72
Testing and Debugging

Tracing code execution


• The code on the right side contains two additional print statements (lines 8 and 10).
They are added for code tracing purpose. The programmer can trace the values of
bonus and the average_value to make sure they are correct.

73
Testing and Debugging

Top-down Testing
• Another way to simplify debugging is to code and test just a small portion of a
program at a time. This can be referred to as top-down testing.
• Later in the course, you will learn about functions.
• A function is that small portion of a program that performs a small and specific task
of the entire program- (a program usually has multiple tasks to perform).
• That tells us that a program can have multiple functions to solve a problem.

74
Testing and Debugging

Top-down Testing
• When testing, a programmer or a tester usually test the
functions independently starting from the main function
down to the other functions in the program to make sure
they work properly and produce the expected results. You
can use the code tracing technique to test each function in
your program.
• In this way, we easily and efficiently test the entire
program – by testing its functions independently.
• Multiple testers can test multiple functions concurrently
which is GREAT to save testing time!

75
Testing and Debugging

Using Debugger
• So far in this chapter, you’ve learned the skills that you’ll use to solve most of your debugging
problems. Occasionally, though, you’ll run into bugs that are difficult to isolate.
• Most modern IDEs (like Visual Studio Code) include debuggers.
• Breakpoints can be toggled by clicking on the editor margin or using F9 on the current line.
Finer breakpoint control (enable/disable/reapply) can be done in the Run and
Debug view's BREAKPOINTS section.
• Breakpoints in the editor margin are normally shown as red filled circles.
• Disabled breakpoints have a filled gray circle.
• When a debugging session starts, breakpoints that cannot be registered with the debugger
change to a gray hollow circle. The same might happen if the source is edited while a debug
session without live-edit support is running.

76
Testing and Debugging

Using Debugger

A breakpoint (select a line then press F9


on the keyboard to enable)

77
Testing and Debugging

Using Debugger

Debugger
traces the
variables

The debug
toolbar

A breakpoint

78
Testing and Debugging

• You can watch this short tutorial for debugging python programs in
visual studio code:
https://www.youtube.com/watch?v=FT-IWVYJYug

79
Testing and Debugging

Debugger Exercise: Do it yourself !

• Use the VS code debugger to debug the code shown in slide 27.
• Do the following:
• Set multiple breakpoints in the code.
• Run and Debug
• Step into, Step Over
• Analyze the VARIABLES in the RUN AND DEBIG panel.

80
Testing and Debugging

Debugger Exercise: Do it yourself !

• Review the code shown to the right side.


• Trace the code by inserting multiple print()
functions (one at a time) to display the
values and to make sure they are correct
(what you expect). If they are not, your task
is to fix the errors.

81
References
Material has been taken from (can be accessed through Sheridan's Library Services) :

• Starting Out with Python (ISBN-13: 9780136912330 ):


• https://www.pearson.com/en-ca/subject-catalog/p/starting-out-with-
python/P200000003356/9780136912330

• Murach’s Python 2nd Edition programming, 2nd Edition :


• https://bookshelf.vitalsource.com/reader/books/9781943872756/pages/recent

• Introducing Python, Lubanovic, B., O'Reily Media, 2nd Edition, 2019


• https://www.oreilly.com/library/view/introducing-python-
2nd/9781492051374/
82
Data Types-Lists
(Midterm Test)

Raed Karim[2023], Megha Patel[2023]

1
Data Types-Lists
Objectives

At the end of this module, students will be able to:


• Define and create List to store data.
• Process and access data stored in Lists.
• Write and implement List methods and functions.
• Solve problems that requires data stored in Lists.

2
Working with Lists
Part - 1

3
Data Types- Lists
Working with Lists
• A List contains a collection of items (data).
• Lists are ordered (indexed) sequences of arbitrary data (items) that is mutable.
• Sequence means that a list stores items in the sequence in which they are added to
the list, lists are a type of data structure known as a sequence.
• Mutable means that the length of the sequence can be changed and elements can
be substituted.
• Lists can be of any data, of one type or mixed type, and can be written explicitly.
• The basic format is a square-bracket-enclosed [ ], comma-separated list of arbitrary
data.

4
Data Types- Lists
Working with Lists

• You can also create an empty list. Then, you can add items to this list later on.
• In some languages (like Java), this structure is referred to as an array and the items
in the array are referred to as elements.
• Just like strings, to refer to (and to get) an item in a list, you use an index starting at
0. The second item has an index of 1, and so on.
• You can also get items starting from the end of the list by using a negative integer
as the index. Then, the last item in a list has an index of -1, the second to last item
has an index of -2, and so on.
• You can get an item in a list and assign its value to a variable.

5
Data Types- Lists
Working with Lists

• You can use the repetition operator (*) to help create a list. For example, you create
a list with one item, then you use the repetition operator to repeat that item as many
times as you want.
• In the same way, you can add an item to a list. Here, you code the name of the list
and the index that accesses the item on the left of the assignment operator (=).
Then, you code the data that you want to assign to the item on the right side of the
assignment operator.
• If you attempt to access an item that doesn’t exist in the list, you’ll get an IndexError
that indicates that the index is out of range.

6
Data Types- Lists
Working with Lists: Examples

7
Data Types- Lists
Working with Lists: Examples

8
Data Types- Lists
Working with Lists: slicing lists

• You can slice a list to get a subset of the original list.


• If you only want to supply start and end arguments, you only need to code one
colon.
• If you want to start slicing at the beginning of the list, you can omit the start
argument. Or, if you want to continue slicing to the end of the list, you can omit the
end argument.
• If you include the step argument, it specifies which items in the list should be
included. If, for example, you want to get every other item in the list, you can supply
a step argument of 2. Or, if you want to reverse the items, you can supply a step
argument of -1.

9
Data Types- Lists
Working with Lists: Examples for slicing and concatenating lists

10
Data Types- Lists
Working with Lists: copying lists

• The assignment operator makes a shallow copy of a list, so both list variables refer
to the same list. Since a list is a mutable type, this causes both variables to refer to
the same list. As a result, if you use one variable to change the list, those changes
are also available to the other variable.
• By contrast, the deepcopy() function of the copy module makes a deep copy of the
list, so the list variables refer to two different lists.
• You have to import the copy module in order to use the deepcopy() function. As a
result, you can use one variable to change items in one list, and you can use the
other variable to change the items in the other list.

11
Data Types- Lists
Working with Lists: Examples for copying lists

12
Data Types- Lists
Working with Lists: creating a list of lists

• To create a list of lists, you code another list within each item of a first list. This
takes what you learned about lists and applies it to a list of lists.
• To refer to the items in a list of lists, you use two indexes. If necessary, you can also
use negative indexes to work from the end of each list.
• This can also be referred to as a two-dimensional list, and you can think of the data
as columns within rows.

13
Data Types- Lists
Working with Lists: Examples of creating a list of lists

14
Data Types- Lists
Working with Lists: Examples of creating a list of lists

15
Data Types- Lists

Working with Lists: Methods for modifying a list

• You can use the list methods to add and remove


the items in a list.
• You can add items to a list and remove items from
a list. To do that, you can use some of the
methods that are available for a list. These are
summarized in the table shown to the right.

16
Data Types- Lists

Working with Lists: Examples for list methods

17
Data Types- Lists

Working with Lists: Examples for list methods

18
Data Types- Lists

Working with Lists: Methods for modifying a list

• What is the difference between remove() and


pop()?
ü Remove() takes the item itself as an argument to
remove; however, pop() takes an index of an item
as an argument to remove.
ü pop() returns the item removed so you can
assign to a variable; however, remove() doesn’t
return.

19
Data Types- Lists

Working with Lists: Methods for modifying a


list

• There are three other methods: count(),


reverse() and sort().
• The sort() method requires a second argument
if the list contains strings with mixed cases.
That’s because uppercase letters come before
lowercase letters when strings are compared.

20
Data Types- Lists

Working with Lists: Methods for modifying a list

21
Data Types- Lists

Working with Lists: Methods for modifying a list

• There is another useful method: extend().


• You can use this method to extend a list to
include items of another list.

22
Data Types- Lists

Working with Lists: Functions for processing


list items

• You can use the built-in len() function to get


the length of the list, which is the number of
items in the list.
• If, for example, there are 10 items in a list,
the indexes range from 0 through 9, but the
len() function returns 10.

23
Data Types- Lists

Working with Lists: Functions for


processing list items

• You can use the min() function to get


the lowest value in the list and the
max() function to get the highest value.
• You use the sum() function to get the
sum of all the values in the list. You can
include a value for the optional start
argument. This adds the start value to
the total that’s returned by sum().

24
Data Types- Lists

Working with Lists: Functions for


processing list items

• You can use the enumerate() function to


returns all the items with their
corresponding indexes.

25
Data Types- Lists
Working with Lists: Functions for processing list
items

• Later, we will learn about functions. At this point,


we want to know how to use some useful
functions of Module random to process list items.
• The random module provides functions for
generating random numbers. One of its uses is
for game development.
• You can use the choice() function to get a
randomly selected item from a list. Here, choice is
used as the variable name to hold the returned
randomly selected item.
• You can use the shuffle() function to shuffle the
numbers in a list.
26
Data Types- Lists

Working with Lists: Functions for processing list items

27
Data Types- Lists

Working with Lists: Functions for


processing list items

• You can use the in keyword to search for


an item in a list. This is one way to make
sure that an item is in a list before you
process it. In this example, the item is
removed after the code makes sure it’s in
the list.

28
Data Types- Lists

Working with Lists: Functions for


processing list items

• In the same way, you can use the not in


keyword to check if an item does not
exist in a list. In this example, the item
is appended to the list after the code
makes sure it’s not in the list.

29
Data Types- Lists

Working with Lists: Functions for


processing list items
Where n is the number
of elements; the first
• There is a built-in function range(), that can be range(n)
element is index 0, and
used to automatically generate regular
last n-1
arithmetic sequences.
start at n and stop
• The range() is useful when you need to generate range(n, m)
at m-1
a list sequence. Begin, increment
range(begin, end, step)
• The range() syntax is shown to the right: by step, stop at end-1

30
Data Types- Lists

Working with Lists: Functions for


processing list items
Where n is the number
of elements; the first
• There is a built-in function range(), that can be range(n)
element is index 0, and
used to automatically generate regular
last n-1
arithmetic sequences.
start at n and stop
• The range() is useful when you need to generate range(n, m)
at m-1
a list sequence. Begin, increment
range(begin, end, step)
• The range() syntax is shown to the right: by step, stop at end-1

31
Data Types- Lists

Working with Lists: Functions for


processing list items

32
Data Types- Lists

Working with Lists:Do it yourself !


• Ask the user to enter first name, last name and a student id, all in one input statement.
• Create an empty list, then append the entered information into the list using append() one at a time.
• Last, print the list.

33
33
Data Types- Lists

Working with Lists: Do it yourself !


• Ask the user to enter 4 sales amounts as float values, all in one input statement separated with ( , ).
• Append them into a list.
• Find the minimum, maximum, the sum of the list of the sales.
• Sort the list then reverse it.
• Last, count the number of times an amount occurs in a list.
• Print out all outputs in the above questions.

34
34
Data Types- Lists

Working with Lists: Do it yourself !


• Create a list of 3 subjects you take in your school.
• Create another list of the 3 grades of the subjects. A sample of the extended list:
• Extend the first list to include the second one. ['math', 'python', 'network', 90, 93, 88]
• Check for a specific subject if it is in the list, if so, remove it with its grade. If the subject is not in the
list, append it with its grade into the list so it still looks consistent- the subjects followed by the
grades.
• Calculate the average of the grades. In a new list, append or extend it to include the subjects and
the average value.
• Get the average value from the list and check for it to print the corresponding grading letter (e.g., A,
B, C, etc.) – follow the example in the last week lesson.

35
35
Data Types- Lists

Working with Lists: Do it yourself !


• Create a list of three lists of 2 float numbers in each.
• Access the second list.
• Compare the two values of that list.
• If they are equal, append ‘neutral’ to the list, if the first value is smaller than the second, append
‘safe’; otherwise, append ‘risky’.
• Access the appended value in the previous step and print out to the screen.

36
36
References
Material has been taken from (can be accessed through Sheridan's Library Services) :

• Starting Out with Python (ISBN-13: 9780136912330 ):


• https://www.pearson.com/en-ca/subject-catalog/p/starting-out-with-
python/P200000003356/9780136912330

• Murach’s Python 2nd Edition programming, 2nd Edition :


• https://bookshelf.vitalsource.com/reader/books/9781943872756/pages/recent

• Introducing Python, Lubanovic, B., O'Reily Media, 2nd Edition, 2019


• https://www.oreilly.com/library/view/introducing-python-
2nd/9781492051374/
37
Midterm Exam
PROG12583- Programming Foundations-Python

Format: Online exam on SLATE with lockdown browser with Respondus Monitor [check your
lockdown browser and webcam with test quiz given on SLATE under Quizzes]

Total marks 50 marks, Worth 30% of final grade


Time duration: 120 minutes

Quiz consists of:

• 10-20 multiple choice / true-false / fill in the blank [20 Marks] [refer quizzes]
• 2 to 5 short-answer, comprehension-style questions [10 Marks] [ refer code completed in class,
assignments and class materials along with reference links given to you ]
• written response-based question (In this section the student will be given an opportunity to
write a small segment of code as per output requirements or to find errors or to compete a
code (by adding 2-3 statements) as per requirements. [20 Marks] [ refer code completed in
class, assignments and class materials along with reference links given to you ]

You might also like