Python Part 1
Python Part 1
1 1
Introductions
Click to edit Master title style
What is IDE?
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/
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.
1414
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/
1515
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/
1616
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/
1717
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/
1818
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/
1919
Introductions
Click to edit Master title style
Visual studio code downloads
• Download visual studio code:
• https://code.visualstudio.com/
2020
Click to edit Master title style
1
Introductions
Click to edit Master title style
Designing a program
2 2
Introductions
Click to edit Master title style
Designing a program
3 3
Introductions
Click to edit Master title style
Designing a program
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
8 8
Introductions
Click to edit Master title style
Designing a program
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) :
Computer Programs
Memory BrainCells
Our Brain
Once we think, we
Only Vulcans can
open our mouth or
mind-meld, we
so it’s supposed to
work. tweet
Memory
(RAM)
Input
Devices
(Keyboard & Mouse)
Storage Devices
CPU (HDD)
Output
Devices Computer’s
(Monitor, Printer) Brain Communication
Devices
(Network)
(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
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
1
Megha Patel @ Sheridan College
7
The compiler translates
Programming
________Language
into
Machine Language
__________.
Print(“Hello
World”)
Compiler
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
2
Megha Patel @ Sheridan College
3
A program is also
collection of sourcefiles
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
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
I am a language
Python Fundamentals
courseMsg =
'Programming
Principles with
Python’
print(courseMsg)
courseNo = 10004
print('#prog',
courseNo, sep="")
HelloWorld-V1
print('Hello Programming World')
print('Programming Foundations- Python')
print('#prog12583')
__________ __________
__________ __________
__________ __________
__________ __________
__________ __________
__________ __________
__________
__________
Sequential lines with __________
the same indentation __________
designate a block
HelloWorld-V2
””” This is a Hello World Program ”””
print('Hello Programming World')
print('Programming Foundations-Python’)
HelloWorld-V3
helloMsg = 'Hello programming world'
print(helloMsg)
courseMsg = 'Programming Foundations Python'
print(courseMsg)
courseNo = 12583
print('#prog', courseNo, sep="")
---> statement 1
---> statement 2 Definition
---> statement 3
---> statement 1
Compound
---> statement 2 Statement
---> statement 3
…
HelloWorld-V4
def sayHello():
helloMsg = 'Hello programming world'
print(helloMsg)
courseMsg = 'Programming Foundations
Python'
print(courseMsg)
courseNo = 12583
print('#prog', courseNo, sep="")
sayHello()
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
Package
Module
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
Python Fundamentals
1
Python Fundamentals
Click to edit Master title style
Objectives
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:
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
6 6
Python Fundamentals
Click to edit Master title style
Indentation Examples:
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:
9 9
Python Fundamentals
Click to edit Master title style
Statement continuation:
1010
Python Fundamentals
Click to edit Master title style
Comments:
1111
Python Fundamentals
Click to edit Master title style
Comments:
1212
Python Fundamentals
Click to edit Master title style
Comment examples:
1313
Python Fundamentals
Click to edit Master title style
Quotation in Python:
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:
output
1717
Python Fundamentals
Click to edit Master title style
Working with datatypes and variables in Python:
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:
2020
Python Fundamentals
Click to edit Master title style
Working with datatypes and
variables in Python:
2121
Python Fundamentals
Click to edit Master title style
Working with datatypes and variables in Python:
2323
Python Fundamentals
Click to edit Master title style
The print() function:
2424
Click to edit Master
Python
title
Fundamentals
style
2525
Click to edit Master
Python
title
Fundamentals
style
2626
Click to edit Master
Python
title
Fundamentals
style
2727
Click to edit Master
Python
title
Fundamentals
style
The type() function:
2828
Click to edit Master
Python
title
Fundamentals
style
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:
3232
Click to edit Master
Python
title
Fundamentals
style
Types of errors:
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:
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
3737
Click to edit Master
Python
title
Fundamentals
style
3838
Click to edit Master
Python
title
Fundamentals
style
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
1 1
Click to Fundamentals
Python edit Master title style
2 2
Click to edit Master Python Fundamentals
title style
3 3
Click to Fundamentals
Python edit Master title style
4 4
Click to Fundamentals
Python edit Master title style
5 5
Click to Fundamentals
Python edit Master title style
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.
1010
Click to Fundamentals
Python edit Master title style
1111
Click to Fundamentals
Python edit Master title style
1212
Click to Fundamentals
Python edit Master title style
1313
Click to Fundamentals
Python edit Master title style
1414
Click to Fundamentals
Python edit Master title style
1515
Click to Fundamentals
Python edit Master title style
1616
Click to Fundamentals
Python edit Master title style
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) :
3 Python Fundamentals(2)
1
Python Fundamentals(2)
Click to edit Master title style
Objectives
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:
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:
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!!
1010
Click to Fundamentals(2)
Python edit Master title style
• 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
1313
Click to Fundamentals(2)
Python edit Master title style
1414
Click to Fundamentals(2)
Python edit Master title style
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
1616
Click to Fundamentals(2)
Python edit Master title style
1717
Click to Fundamentals(2)
Python edit Master title style
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
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.
2121
Click to Fundamentals(2)
Python edit Master title style
2222
Click to Fundamentals(2)
Python edit Master title style
Ø 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.
2323
Click to Fundamentals(2)
Python edit Master title style
2424
Click to Fundamentals(2)
Python edit Master title style
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.
2626
Click to Fundamentals(2)
Python edit Master title style
2727
Click to Fundamentals(2)
Python edit Master title style
2828
Click to Fundamentals(2)
Python edit Master title style
2929
Click to Fundamentals(2)
Python edit Master title style
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
3131
Click to Fundamentals(2)
Python edit Master title style
3232
Click to Fundamentals(2)
Python edit Master title style
3333
Click to Fundamentals(2)
Python edit Master title style
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
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
3737
Click to Fundamentals(2)
Python edit Master title style
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
(“%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
(‘%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
*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
4646
Click to Fundamentals(2)
Python edit Master title style
Ø 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
Ø 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
4949
Click to Fundamentals(2)
Python edit Master title style
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) :
1
Decision Structures
Objectives
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.
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.
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.
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
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
14
Decision Structures
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!"
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
• 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.
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
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:.
34
Decision Structures
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
• 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
*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
39
Turtle Module
40
Turtle Module
Introduction to Turtle Module
41
Turtle Module
Introduction to Turtle Module
43
Turtle Module
Introduction to Turtle Module
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
53
Turtle Module
Introduction to Turtle Module
54
Turtle Module
Introduction to Turtle Module
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
57
Turtle Module
58
Turtle Module
59
Turtle Module
• Red turtle
executes next.
• Just as in the
order written in
the program.
60
Determining Turtle state
Part - 4
61
Turtle Module
Introduction to Turtle Module
63
Turtle Module
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
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
70
Testing and Debugging
71
Testing and Debugging
72
Testing and Debugging
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
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
• 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
81
References
Material has been taken from (can be accessed through Sheridan's Library Services) :
1
Data Types-Lists
Objectives
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
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
16
Data Types- Lists
17
Data Types- Lists
18
Data Types- Lists
19
Data Types- Lists
20
Data Types- Lists
21
Data Types- Lists
22
Data Types- Lists
23
Data Types- Lists
24
Data Types- Lists
25
Data Types- Lists
Working with Lists: Functions for processing list
items
27
Data Types- Lists
28
Data Types- Lists
29
Data Types- Lists
30
Data Types- Lists
31
Data Types- Lists
32
Data Types- Lists
33
33
Data Types- Lists
34
34
Data Types- Lists
35
35
Data Types- Lists
36
36
References
Material has been taken from (can be accessed through Sheridan's Library Services) :
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]
• 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 ]