Lesson 1: Python Overview
• In this lesson, we will explore the Python programming language, its origin, its
features, and its uses.
After studying this lesson, you should be able to:
• get acquainted with Python and its history;
• list the features of Python;
• differentiate between the versions of Python; and
• list the uses of Python.
Objectives
• Computers are machines, and they only understand binary or sequences of ones
and zeroes.
• Programming languages allow us to write instructions in a way that is
understandable to humans.
• A compiler or an interpreter is then used to translate these instructions into
binary.
• The process of writing instructions using a programming language is called
coding.
Introducing Python
Python is an interpreted general-purpose programming language that can be used in a
wide array of applications.
Python’s Origins
• Python’s development started in the late 1980s.
• Invented by Guido van Rossum.
• Successor of ABC programming language.
• Some features is from Modula-3.
• Implementation of Python started in late 1989.
• The language was named after the popular
British television show, Monty Python’s Flying
Circus.
• Python 1.0 was released in 1994.
• Python 2.0 was released in 2000.
• Version 3.0 came out in 2008 and promised to
solve inherent issues with the older versions.
Today, Python is one of the
most popular programming
languages in the world.
Python’s Key Features
Python’s popularity has plenty to do with its
features.
 Easy-to-Use
 Interpreted
 High-level
 Dynamically-Typed
 Expressive
 Extensible
 Available Libraries
 Support for GUI
 Cross-platform Development
 Free and Open-source
Python’s Uses and
Applications
Here are just some of its uses and
applications today.
 Web Applications
 Data and Analytics
 Research
 Artificial Intelligence (AI) and Machine
Learning (ML)
 Business and Enterprise
 Game Development
 Internet-of-Things
Lesson 2: Installing Python and PyCharm
• Now that we are acquainted with Python and its features as a programming
language, let’s begin using it. In this lesson, we will install Python and the PyCharm
IDE on a computer running on a Windows operating system.
After studying this lesson, you should be able to:
• download the Python and PyCharm installers;
• install Python and PyCharm; and
• go over PyCharm’s features and GUI.
Objectives
Installing and Downloading Python
To download Python, visit
https://python.org.
Running the Installer
Select the file, right-click, and choose
Run as Administrator.
A User Account Control
prompt message will
likely pop up. If it does,
choose Yes.
The Python installation will start.
Choose Install Now.
The installer will copy the necessary
files into your system.
Professional Community
PyCharms Community version’s key features
include: • Code Assistance
• Developer Tools
Installing and Downloading PyCharm
To download PyCharm, visit
https://www.jetbrains.com/
pycharm/download/
Installing PyCharm
Select the file, right-click, and choose
Run as Administrator.
A User Account Control
prompt message will
likely pop up. If it does,
choose Yes.
The PyCharm installer will start.
Click Next.
Select the appropriate installation
options for your computer, then click
Next.
You can check your Windows properties (in Windows
Explorer right-click on Computer > Properties) to see your
system type.
You can also set the Start Menu
folder in which the PyCharm
shortcut will be placed. Click Install.
The PyCharm installer will start copying
the files into your system.
Running PyCharm for the First Time
A wizard will start, allowing
you to set some settings.
Clicking Next will bring up Featured Plugins.
Since you are just learning Python, let’s skip
this for now and click Start using Pycharm.
PyCharm will ask you what you want
to do. Click on New Project.
It defaults to a location within your
Windows user directory. Click
Create.
The PyCharm
GUI
IDLE
To launch IDLE, just click on
the Windows Start menu >
Python > IDLE.
To open the editor, click File
> New File or press Ctrl + N.
IDLE also supports syntax highlighting, autocompletion, and smart indent.
You can save your Python (.py) files and run them within IDLE.
Hello, World!
Enter this line of code:
Click the Run button.
Notice how PyCharm automatically shifts focus to the Run tool window.
• Comments are lines of code that are meant to provide information to yourself or
your fellow programmers who would want to see how your code works.
• Comments are indicated by the hash (#).
Lesson 3: Understanding Data
• We’ve already set up our computers to run Python and PyCharm. In this lesson, we
will be discussing fundamental concepts in programming, particularly how data
works in Python.
After studying this lesson, you should be able to:
• learn how data is represented in Python,
• list the common data types,
• specify data, and
• perform basic operations.
Objectives
Using the
Interpreter
Launching IDLE opens up the Python Shell.
In PyCharm, the Python
Shell can be accessed
readily from within
PyCharm through the
Python Console tool
window.
To restart the console, press Ctrl + F6 in IDLE or press Ctrl + F5 in PyCharm.
Data as Objects
To write effective code, you need to know how the programming language handles and
manages data.
Python follows this “data as objects” analogy
and treats data accordingly. Each object bears
the following information:
• an identity (or ID), which tells it apart from
other objects (usually the object’s location in
the computer’s memory)
• a type, which determines what kind of value
it can have
• a corresponding value
Try this out in the
interpreter. Enter each
of the following lines:
id() function When using functions, we place the object we want to be processed
within the parentheses.
Run the following lines: The interpreter should return an
integer value for each, signifying
their location in your memory.
Data Types
Here is a list of the common data types and their respective uses.
In the interpreter, enter:
Python should return the data types of each i.e. x is a string and y is an integer.
Example 1 Example 2
Mutability
refers to whether the
value of the object can
be changed (mutable) or
not (immutable). Integer,
float, string, Boolean,
tuple, and frozenset data
are immutable.
Let’s try changing the data of one of the variables. Enter the following code.
Check what data x contains using the print() function.
Let’s check the IDs of the following: Now let’s try doing something similar to a
mutable data type such as a list. Let’s create
a simple list and assign it to a variable.
Check the IDs of both a and b.
Let’s try changing the value of the list by “popping” one
element out of it with the pop() method.
Check the value
of both a and b
variable, then
check their IDs.
Why does mutability
matter?
Specifying Data Values
A literal is a direct way to
specify a value.
Variables are among the
fundamental programming
concepts that you must grasp.
We do not have to declare a
variable’s data type explicitly
when creating one in Python.
Python has several rules on
how you can name a variable:
 Must begin with a letter or underscore and not a digit
 May only contain the following characters
{ Lower case letters (a-z)
{ Uppercase letters (A-Z)
{ Digits (0-9)
{ Underscore (_)
 Is case-sensitive, meaning var, VAR, and Var would be
considered unique names
 Can’t be one of Python’s keywords
To get a list of Python’s keywords, run help(‘keywords’) in the interpreter.
To assign a variable to an object,
we use the equal sign (=).
We can also reassign variable
names.
Lesson 4: Numbers and Strings
• Data are essential building blocks of any computer program. In this lesson, we will
be exploring numerical values, Boolean values, text strings, lists, tuples, and sets.
After studying this lesson, you should be able to:
• list the number data types in Python;
• work with text strings; and
• create sets and lists.
Objectives
Numbers
Integers are made up of whole numbers, their negative
counterparts, and zero.
Try entering the following lines in the interpreter:
Negative integers are specified by starting the sequence with a
minus sign.
You can’t start
with a zero (digit).
An exception to this is when you use another base
You also will not be able to include commas in your
specification. If you try to enter commas in a
sequence of digits, you will get a tuple.
You can insert underscores within the sequence
as digit separators, and they will be ignored by
the interpreter.
You can perform mathematical operations on integers.
Enter the following lines in the interpreter and see their results.
See what happens when you try to divide by zero.
You can assign
variables names to
integer objects.
Note that Python arithmetic follows PEMDAS
precedence rules.
Before entering the following code in the
interpreter, try to figure out what the result will
be.
Floating-point numbers or
floats are numerical values
with decimal points.
Floats can also take
underscores to
separate the digits.
Like integers, you can perform
mathematical operations on floats
and the variables assigned to them.
When you perform an
operation between a
float and an integer
value, the result will be
a float.
You can also convert
the specified values
of variables from
integers to floats
and vice
versa using the
float() and int()
functions.
Let’s try converting a
variable’s referenced
value from float to
integer.
Note that these functions do
not affect an object’s
mutability. The specified
values do not change IDs.
A Boolean value is either True or False.
• Boolean values of other data types
using the bool() function.
• Nonzero numbers are treated as
True.
• Zero-valued numbers are treated as
False.
Try these lines in the interpreter:
Strings are composed of a sequence of
characters. They are specified by enclosing
characters in quotation marks. You can use
either single (‘) or double (“) quotes.
Example 1
Example 2
Multiline Strings
When you want to include quotation marks
as part of your string. You can use the single
quotes within double quotes and vice versa.
You can also specify multi-line strings
using three quotation marks. To move to
the next line in the interpreter, press
Shift + Enter.
Escape and Whitespace Characters
Here are some other escape characters
that you can use in strings:
• n - new line
• r - carriage return
• t - tab
•  ‘ - single quote
•   - backslash
Example
Concatenation and Multiplication
You can also perform some “operations” with
strings. Using + concatenates or joins string
values together.
You can also multiply strings. What it does
is:
Offset and Slice
You can also get a specific character within a string based on its position in the
sequence using offset[].
Keep in mind that the index starts at 0, so if you want to get the third character, you
use 2 as offset.
Like offset, you can define a slice using
brackets.
[:] - gets the entire sequence from start to end
[start :] - gets all the characters from the start
point of the slice until the end of the sequence
[: end] - gets all the characters until before the
chosen endpoint
[start : end] - gets characters from the start until
before the endpoint
[start: end: step] - gets characters from start
until before the endpoint, skipping every number
of characters set by the step
Length
len() function counts the number of characters and returns the result as an integer value.
The strip() method is a procedure for strings.
strip() - Strips whitespace characters on both sides
lstrip() - Strips whitespace characters on the left
rstrip() - Strips whitespace characters on the right
Example
Try checking the variable and see
that the associate value remains
the same.
You can also indicate a sequence of
characters as an argument.
Split and Join
The split() method can create a list out of a string value. It helps if there is something in
the string that can be used as a separator.
Let’s try this example with
different whitespace characters
and see how the split() method
will turn the string value into a list.
You can also bring together list items to form a string value using the join()
method.
Replace
The replace() method is another handy string method. The method can take on three
arguments:
• the string you want to be replaced,
• the string you want to replace it with,and
• (optional) the number of times the replacement would occur.
If you do not set the optional parameter, it will replace all instances it can find.
Case
We can also change the case of the characters in the
string using the following methods:
• capitalize() - Capitalizes the first word of the string
• title() - Capitalizes the first letter of each word
• upper() - Capitalizes all the letters in the string
• lower() - Converts the letters to lowercase
• swapcase() - Changes the case from upper to
lowercase and vice versa
Lesson 5: Tuples and Lists
• In this lesson, we will be exploring collection data types in Python. This time, we
will be looking at tuples and lists, which are sequences of objects.
After studying this lesson, you should be able to:
• define tuples and lists;
• manipulate them using functions and methods; and
• explore the uses of these data types.
Objectives
Tuples are the first type of sequence structure we will be discussing. If you are
wondering how it is pronounced, it can either be “tue-pull” (as in “Tuesday”) or
“tuppull” (as in “Tupperware”). Both are considered acceptable.
Specifying Tuples
To specify a tuple, you enter each element and use a comma to
separate them.
Example 1
Example 2
To create a tuple with just one
element, use a comma at the end
of the first (and only) element.
You can also have tuples with
elements of mixed data types.
You can reference a specific element by
referencing its offset.
Unpacking a
Tuple
Creating Tuples Out of Other Types
Python has a tuple() function, which allows you to convert other data types.
Tuple “Operations”
Using the + operator combines two tuples
together.
Using the * operator duplicates the
specified element.
Comparing Tuples
Comparison Operators
Lists are the second type of sequence structure in Python. Unlike tuples, lists are
mutable, meaning their values can be changed.
Specifying Lists
To specify a list, you need to
enclose elements using square
brackets [] and use the comma as
the separator for the elements.
Creating Lists Out of Other Types
You can even create lists using data types that have offsets, like strings, for instance.
Strings can be split using the split()
method to create a list.
Keep in mind that the join()
method takes on the list as its
parameter.
Adding and Inserting Items
Instead of assigning a new variable name for the combined sequence, you
can also use an existing variable name.
The extend() method works similarly. It takes on the additional list as a parameter.
The * operator, like in tuples, multiplies the elements in the list
You can add items to the end of the list with the append() method.
You can also insert an element within the list using the insert() method.
Comparing Lists
Deleting Values
You can delete an element from the list using the del keyword and the offset of
the element.
Another way you can delete
an element is by using the
remove() method and
indicating the value of the
element.
A third way to remove an
element from a list is using
the pop() method.
You can delete all items in
a list by using the clear()
method.
Finding Information
Using in returns a Boolean
value.
Using the index() method.
The len() function returns
the number of elements in
a list.
Using the count()
method.
Copying Values
You can create copies of lists using
the copy() method. It works best if
all the values of list elements are
immutable.
But what if we have something mutable
like a whole list as a list element?
let’s delete an element from the additional list
and see how this affects the other lists that
contain it.
To copy the actual values from one list to another and not just the reference, we can
use Python’s copy module. Let’s use deepcopy().
Reordering Elements
• The sort() method rearranges values of the list in itself.
• The sorted() function creates a sorted copy of a list.
What are the difference between
Tuples and Lists?
Lesson 6: Sets and Dictionaries
• In this lesson, we will be learning more about collection data types, particularly
unordered sets (sets and frozensets) and dictionaries.
After studying this lesson, you should be able to:
• define sets and dictionaries;
• manipulate these data types; and
• explore the uses of these data types.
Objectives
Set is a collection data type made up of unordered elements. Just think of your lessons
on sets in math class. Python sets function much like the sets you studied in math.
Specifying Tuples
To specify a set, you can use the curly braces {}. Try these out in the
interpreter.
Example
To create an empty set,
you must use the function.
Creating Sets Out of Other Types
the set() function can be used to create sets
out of strings, lists, tuples, and dictionaries.
Using the len() function.
Notice how this is also the
case for the other data types
which include multiple
elements with similar values.
Adding and Deleting Elements
To add an element, you need to use the
add() method.
You can also delete an element by using
the remove() method.
Finding Information
Set Operators
Let’s check out how they work.
Define two sets in the interpreter
Try using the operators and methods.
Frozensets are basically sets with immutable values.
To specify a frozenset or create a
frozenset out of other data types, you
use the frozenset() function.
To see if the values really are immutable, try using the add() or remove() methods.
A dictionary is a collection data type that consists of key and value pairs.
Specifying Dictionaries
To specify a dictionary, you can use either curly brackets ({}) with
key and value pairs that use the colon (:) separated by commas
(,).
You can also use the dict() function
Creating Dictionaries Out
of Other Types
Combine two lists into a dictionary using the dict() and zip() functions.
Adding and Changing Elements
To add a value, simply specify a key in the offset and assign a value.
To change a value, simply refer to a key and assign a new value. If the key does not
exist, a new element will be added.
Delete elements from the dictionary by using the del keyword
To delete all items in a dictionary, use the clear() method.
Finding Information
Using len() function
You can get the value
associated to a key by
entering the key.
If you try to get a value for a key
that does not exist, Python will
return an error.
To check if a key exists. You can also get the value of
a key using the get()
method.
You can get the keys from a dictionary using the keys() method.
You can turn the result of the keys() method into a list using the list() function. Doing
so creates a copy of the keys.
If you can get keys, you can also get values. You can use the values() method.
You can also make a list out of this result.
Combining Dictionaries
You can combine or
merge two dictionaries
using **.
You can also use the update()
method to insert dictionary
values into an existing one.
Comparing Dictionaries
You can compare dictionaries but only
using the equality operators (==) and
(!=).
Python compares elements one by one regardless of sequence or order. If they match,
Python will return a True value.
Lesson 7: Conditionals, Loops, and Input
• In this lesson, we are moving on to some of the more exciting concepts in
computer programming. We will learn about conditionals, loops, and the input()
function.
After studying this lesson, you should be able to:
• define what conditionals and loops are;
• use conditionals and loops; and
• allow user input in your programs.
Objectives
IDLE Editor
Click File > New File or Ctrl + N. To run a program, press F5.
PyCharm Editor 1. Click the project root in the Project tool
window > New > Python File.
2. Select Python file from the popup window,
and then type the new filename.
3. Run the program (Shift-Alt-F10)
Conditionals allow you to execute lines of code if particular conditions are met.
Syntax Output
Nesting Conditions
You can place other conditional statements within conditions.
Syntax Output
We can further refine the code using the elif keyword so we can check for more than
one condition.
Syntax Output
Logical Operators
Syntax Output
Comparing with the in Keyword
Say we want to check a letter if it is a vowel
or not. We can manually set multiple
conditions using if, elif, and else:
A shorter version of this uses the or
keyword.
You can also use the in keyword.
Loops
The while keyword allows us to execute code over and over until a condition is met.
Syntax Output
Assignment Operators We can also create loops using the for
and in keywords. Let’s say we want to
print each letter in the string “kerfuffle”
Syntax
Output
Iterating through Collections
Tuples
Syntax Output
Lists
Sets
Dictionaries
Break and Continue
The break keyword is used when you want to loop something indefinitely until a
condition is met.
Syntax Output
The continue keyword skips running the code for an iteration.
Syntax Output
The range() function creates a sequence
of numbers. It takes on three arguments:
• start - The start of the sequence
• stop - The end of the sequence
• step - How much the range
increments
Input
• The input() function allows us to show a prompt and have the user to provide
some information.
• The function takes on a parameter for a prompt.
Syntax
Output
Simple Guessing Game
Lesson 8: Functions, Classes, and Objects
• In this lesson, we will be learning how to create and use functions, classes, and
objects.
After studying this lesson, you should be able to:
• define functions, classes, and objects;
• create samples of functions, classes, and objects; and
• use them in programs.
Objectives
Functions
• allow us to perform various tasks without having to code the instructions over and
over. All we have to do is to call the function and pass on some arguments for us to
get some form of result.
Defining and Calling Functions
To define a function, we use the def keyword. We specify the function name, its
input parameters in parentheses (if needed), and a colon (:).
Syntax Output
Arguments and Parameters
Let’s create a function called times_five(), which multiplies any value passed into it
through the argument “number” by five.
Syntax Output
Let’s try converting the vowel checker program that we had in the previous unit
into a function. The function takes on the argument “letter”.
Syntax Output
Positional arguments pass on values based on their position.
Syntax
Output
Keyword arguments allows you to indicate the argument names and their corresponding
parameters.
Syntax
Output
What if you forget to add providing a
value for an expected argument?
A way to prevent this is by immediately assigning a value in the def statement.
Syntax Output
What if we need our function to be flexible and be able to take on a
variable number of arguments?
Syntax Output
You can also use **kwargs to create a dictionary from the arguments.
Syntax Output
Global vs. Local Variables
Global variables are accessible throughout the program. Local variables are only
accessible within the function in which they are declared.
To Declare To Call
Output
Objects and Classes
• Object-Oriented Programming (OOP) is a programming paradigm where
software is designed based on real-world objects rather than simply as
sequences of instructions and logic.
• Objects in OOP are data structures that have attributes and methods.
• Class is the characteristic of an object.
Example:
Dog > Bantay > brown fur and four legs
Defining Classes
To create a class, we use the class keyword.
• The __init__ method is what is called a
constructor in OOP.
• The self keyword allows us to access the
attributes and methods that we will be
creating for the class.
Creating Objects
To create an object from a class, we call
the class and assign it to a variable.
We can access the attribute values of
dog1 by using dot notation.
Output
Adding and Using Methods
Next, we will add an ability to our
Dog class.
This allows all dog objects to bark and can be triggered by calling the bark() method
of our object.
Changing Object Properties
Output
Deleting an Object
Child Classes and Inheritance
Let’s create an object
based on this Pug class
Overriding Using Child Classes
Syntax Output
Lesson 9: Modules
• In this lesson, we will be exploring Python’s extensibility using modules. We willl
learn how to download them, import them into our programs, and use their
functionalities.
After studying this lesson, you should be able to:
• explore built-in modules available in Python;
• download and import modules; and
• use modules to build programs.
Objectives
Modules and Packages
Creating Modules
In PyCharm, you can do this by
rightclicking on the project tool
window and selecting New >
Python File. Name it vowel_
checker.py. Then copy the code
below.
Go back to main.py and enter the following
code:
Importing Modules
To import an entire module, we can use the import keyword.
Example: What this does basically translates to:
Installing Third-Party Packages
The easiest way to install these third-party packages is by using Python’s package
installer or pip.
In PyCharm, simply bring up the Terminal tool
window. In the command line, enter:
In the terminal, type:
Working with Modules and Packages
Random allows us to generate “random” numbers and randomize from a set of
elements.
Three of its commonly-used methods are:
Turtle graphics is another interesting Python module. It simulates a digital turtle
drawing lines on the screen as it moves.
Setting Up the Screen
Create our turtle object.
Drawing a Square Drawing a Circle
This tells the turtle to
draw a circle with a
radius of 50 pixels.
This way, we get a
circle with a diameter
of 100 pixels.
Drawing a Triangle
More Methods
Try out these other Turtle methods and see
how they work.
• setposition()
• home()
• undo()
• pendown()
• penup()
• pensize()
• color()
• pencolor()
• fillcolor()
• filling()
• begin_fill()
• end_fill()
• showturtle()
• hideturtle()
Tkinter is a built-in module in Python used for building GUI based applications.
Lesson 10: Python Project
• In this lesson, we will be putting all we have learned in the course together to
create different projects using Python.
After studying this lesson, you should be able to:
• create a Bato Bato Pik (rock, paper, scissors) game;
• build a word counter app; and
• make a price checker app.
Objectives
Bato Bato Pik is our local version of Rock,
Paper, Scissors.
A player has three choices:
1) rock (bato),
2) paper (papel), or
3) scissors (gunting).
The opponent (in this case, the
computer) also makes a play based on
the same choices. The outcome depends
on these choices. Rock crushes scissors.
Paper covers rock. Scissors cut paper. A
player can win, lose, or draw.
Word Counter
a tiny app that counts the number of
words in a text box.
Price Checker
It is a grocery price
checker. It allows you to click on
a product, and the app will
display its price.
END OF SLIDES

Python PPT.pptx

  • 3.
    Lesson 1: PythonOverview • In this lesson, we will explore the Python programming language, its origin, its features, and its uses. After studying this lesson, you should be able to: • get acquainted with Python and its history; • list the features of Python; • differentiate between the versions of Python; and • list the uses of Python. Objectives
  • 4.
    • Computers aremachines, and they only understand binary or sequences of ones and zeroes. • Programming languages allow us to write instructions in a way that is understandable to humans. • A compiler or an interpreter is then used to translate these instructions into binary. • The process of writing instructions using a programming language is called coding.
  • 5.
    Introducing Python Python isan interpreted general-purpose programming language that can be used in a wide array of applications.
  • 6.
    Python’s Origins • Python’sdevelopment started in the late 1980s. • Invented by Guido van Rossum. • Successor of ABC programming language. • Some features is from Modula-3. • Implementation of Python started in late 1989. • The language was named after the popular British television show, Monty Python’s Flying Circus. • Python 1.0 was released in 1994. • Python 2.0 was released in 2000. • Version 3.0 came out in 2008 and promised to solve inherent issues with the older versions. Today, Python is one of the most popular programming languages in the world.
  • 7.
    Python’s Key Features Python’spopularity has plenty to do with its features.  Easy-to-Use  Interpreted  High-level  Dynamically-Typed  Expressive  Extensible  Available Libraries  Support for GUI  Cross-platform Development  Free and Open-source Python’s Uses and Applications Here are just some of its uses and applications today.  Web Applications  Data and Analytics  Research  Artificial Intelligence (AI) and Machine Learning (ML)  Business and Enterprise  Game Development  Internet-of-Things
  • 8.
    Lesson 2: InstallingPython and PyCharm • Now that we are acquainted with Python and its features as a programming language, let’s begin using it. In this lesson, we will install Python and the PyCharm IDE on a computer running on a Windows operating system. After studying this lesson, you should be able to: • download the Python and PyCharm installers; • install Python and PyCharm; and • go over PyCharm’s features and GUI. Objectives
  • 9.
    Installing and DownloadingPython To download Python, visit https://python.org.
  • 10.
    Running the Installer Selectthe file, right-click, and choose Run as Administrator. A User Account Control prompt message will likely pop up. If it does, choose Yes. The Python installation will start. Choose Install Now. The installer will copy the necessary files into your system.
  • 11.
    Professional Community PyCharms Communityversion’s key features include: • Code Assistance • Developer Tools
  • 12.
    Installing and DownloadingPyCharm To download PyCharm, visit https://www.jetbrains.com/ pycharm/download/
  • 13.
    Installing PyCharm Select thefile, right-click, and choose Run as Administrator. A User Account Control prompt message will likely pop up. If it does, choose Yes. The PyCharm installer will start. Click Next.
  • 14.
    Select the appropriateinstallation options for your computer, then click Next. You can check your Windows properties (in Windows Explorer right-click on Computer > Properties) to see your system type.
  • 15.
    You can alsoset the Start Menu folder in which the PyCharm shortcut will be placed. Click Install. The PyCharm installer will start copying the files into your system.
  • 16.
    Running PyCharm forthe First Time A wizard will start, allowing you to set some settings. Clicking Next will bring up Featured Plugins. Since you are just learning Python, let’s skip this for now and click Start using Pycharm.
  • 17.
    PyCharm will askyou what you want to do. Click on New Project. It defaults to a location within your Windows user directory. Click Create.
  • 18.
  • 19.
    IDLE To launch IDLE,just click on the Windows Start menu > Python > IDLE. To open the editor, click File > New File or press Ctrl + N. IDLE also supports syntax highlighting, autocompletion, and smart indent. You can save your Python (.py) files and run them within IDLE.
  • 20.
    Hello, World! Enter thisline of code: Click the Run button. Notice how PyCharm automatically shifts focus to the Run tool window.
  • 21.
    • Comments arelines of code that are meant to provide information to yourself or your fellow programmers who would want to see how your code works. • Comments are indicated by the hash (#).
  • 22.
    Lesson 3: UnderstandingData • We’ve already set up our computers to run Python and PyCharm. In this lesson, we will be discussing fundamental concepts in programming, particularly how data works in Python. After studying this lesson, you should be able to: • learn how data is represented in Python, • list the common data types, • specify data, and • perform basic operations. Objectives
  • 23.
    Using the Interpreter Launching IDLEopens up the Python Shell. In PyCharm, the Python Shell can be accessed readily from within PyCharm through the Python Console tool window. To restart the console, press Ctrl + F6 in IDLE or press Ctrl + F5 in PyCharm.
  • 24.
    Data as Objects Towrite effective code, you need to know how the programming language handles and manages data. Python follows this “data as objects” analogy and treats data accordingly. Each object bears the following information: • an identity (or ID), which tells it apart from other objects (usually the object’s location in the computer’s memory) • a type, which determines what kind of value it can have • a corresponding value Try this out in the interpreter. Enter each of the following lines:
  • 25.
    id() function Whenusing functions, we place the object we want to be processed within the parentheses. Run the following lines: The interpreter should return an integer value for each, signifying their location in your memory.
  • 26.
    Data Types Here isa list of the common data types and their respective uses.
  • 27.
    In the interpreter,enter: Python should return the data types of each i.e. x is a string and y is an integer. Example 1 Example 2 Mutability refers to whether the value of the object can be changed (mutable) or not (immutable). Integer, float, string, Boolean, tuple, and frozenset data are immutable.
  • 28.
    Let’s try changingthe data of one of the variables. Enter the following code. Check what data x contains using the print() function. Let’s check the IDs of the following: Now let’s try doing something similar to a mutable data type such as a list. Let’s create a simple list and assign it to a variable. Check the IDs of both a and b.
  • 29.
    Let’s try changingthe value of the list by “popping” one element out of it with the pop() method. Check the value of both a and b variable, then check their IDs. Why does mutability matter?
  • 30.
    Specifying Data Values Aliteral is a direct way to specify a value. Variables are among the fundamental programming concepts that you must grasp. We do not have to declare a variable’s data type explicitly when creating one in Python. Python has several rules on how you can name a variable:  Must begin with a letter or underscore and not a digit  May only contain the following characters { Lower case letters (a-z) { Uppercase letters (A-Z) { Digits (0-9) { Underscore (_)  Is case-sensitive, meaning var, VAR, and Var would be considered unique names  Can’t be one of Python’s keywords
  • 31.
    To get alist of Python’s keywords, run help(‘keywords’) in the interpreter.
  • 32.
    To assign avariable to an object, we use the equal sign (=). We can also reassign variable names.
  • 33.
    Lesson 4: Numbersand Strings • Data are essential building blocks of any computer program. In this lesson, we will be exploring numerical values, Boolean values, text strings, lists, tuples, and sets. After studying this lesson, you should be able to: • list the number data types in Python; • work with text strings; and • create sets and lists. Objectives
  • 34.
    Numbers Integers are madeup of whole numbers, their negative counterparts, and zero. Try entering the following lines in the interpreter: Negative integers are specified by starting the sequence with a minus sign. You can’t start with a zero (digit). An exception to this is when you use another base
  • 35.
    You also willnot be able to include commas in your specification. If you try to enter commas in a sequence of digits, you will get a tuple. You can insert underscores within the sequence as digit separators, and they will be ignored by the interpreter.
  • 36.
    You can performmathematical operations on integers.
  • 37.
    Enter the followinglines in the interpreter and see their results. See what happens when you try to divide by zero. You can assign variables names to integer objects. Note that Python arithmetic follows PEMDAS precedence rules. Before entering the following code in the interpreter, try to figure out what the result will be.
  • 38.
    Floating-point numbers or floatsare numerical values with decimal points. Floats can also take underscores to separate the digits. Like integers, you can perform mathematical operations on floats and the variables assigned to them. When you perform an operation between a float and an integer value, the result will be a float.
  • 39.
    You can alsoconvert the specified values of variables from integers to floats and vice versa using the float() and int() functions. Let’s try converting a variable’s referenced value from float to integer. Note that these functions do not affect an object’s mutability. The specified values do not change IDs.
  • 40.
    A Boolean valueis either True or False. • Boolean values of other data types using the bool() function. • Nonzero numbers are treated as True. • Zero-valued numbers are treated as False. Try these lines in the interpreter:
  • 41.
    Strings are composedof a sequence of characters. They are specified by enclosing characters in quotation marks. You can use either single (‘) or double (“) quotes. Example 1 Example 2 Multiline Strings When you want to include quotation marks as part of your string. You can use the single quotes within double quotes and vice versa. You can also specify multi-line strings using three quotation marks. To move to the next line in the interpreter, press Shift + Enter.
  • 42.
    Escape and WhitespaceCharacters Here are some other escape characters that you can use in strings: • n - new line • r - carriage return • t - tab • ‘ - single quote • - backslash Example Concatenation and Multiplication You can also perform some “operations” with strings. Using + concatenates or joins string values together. You can also multiply strings. What it does is:
  • 43.
    Offset and Slice Youcan also get a specific character within a string based on its position in the sequence using offset[]. Keep in mind that the index starts at 0, so if you want to get the third character, you use 2 as offset. Like offset, you can define a slice using brackets. [:] - gets the entire sequence from start to end [start :] - gets all the characters from the start point of the slice until the end of the sequence [: end] - gets all the characters until before the chosen endpoint [start : end] - gets characters from the start until before the endpoint [start: end: step] - gets characters from start until before the endpoint, skipping every number of characters set by the step
  • 44.
    Length len() function countsthe number of characters and returns the result as an integer value. The strip() method is a procedure for strings. strip() - Strips whitespace characters on both sides lstrip() - Strips whitespace characters on the left rstrip() - Strips whitespace characters on the right Example
  • 45.
    Try checking thevariable and see that the associate value remains the same. You can also indicate a sequence of characters as an argument. Split and Join The split() method can create a list out of a string value. It helps if there is something in the string that can be used as a separator.
  • 46.
    Let’s try thisexample with different whitespace characters and see how the split() method will turn the string value into a list. You can also bring together list items to form a string value using the join() method.
  • 47.
    Replace The replace() methodis another handy string method. The method can take on three arguments: • the string you want to be replaced, • the string you want to replace it with,and • (optional) the number of times the replacement would occur. If you do not set the optional parameter, it will replace all instances it can find.
  • 48.
    Case We can alsochange the case of the characters in the string using the following methods: • capitalize() - Capitalizes the first word of the string • title() - Capitalizes the first letter of each word • upper() - Capitalizes all the letters in the string • lower() - Converts the letters to lowercase • swapcase() - Changes the case from upper to lowercase and vice versa
  • 49.
    Lesson 5: Tuplesand Lists • In this lesson, we will be exploring collection data types in Python. This time, we will be looking at tuples and lists, which are sequences of objects. After studying this lesson, you should be able to: • define tuples and lists; • manipulate them using functions and methods; and • explore the uses of these data types. Objectives
  • 50.
    Tuples are thefirst type of sequence structure we will be discussing. If you are wondering how it is pronounced, it can either be “tue-pull” (as in “Tuesday”) or “tuppull” (as in “Tupperware”). Both are considered acceptable. Specifying Tuples To specify a tuple, you enter each element and use a comma to separate them. Example 1 Example 2
  • 51.
    To create atuple with just one element, use a comma at the end of the first (and only) element. You can also have tuples with elements of mixed data types. You can reference a specific element by referencing its offset. Unpacking a Tuple
  • 52.
    Creating Tuples Outof Other Types Python has a tuple() function, which allows you to convert other data types. Tuple “Operations” Using the + operator combines two tuples together. Using the * operator duplicates the specified element.
  • 53.
  • 54.
    Lists are thesecond type of sequence structure in Python. Unlike tuples, lists are mutable, meaning their values can be changed. Specifying Lists To specify a list, you need to enclose elements using square brackets [] and use the comma as the separator for the elements. Creating Lists Out of Other Types
  • 55.
    You can evencreate lists using data types that have offsets, like strings, for instance. Strings can be split using the split() method to create a list. Keep in mind that the join() method takes on the list as its parameter.
  • 56.
    Adding and InsertingItems Instead of assigning a new variable name for the combined sequence, you can also use an existing variable name.
  • 57.
    The extend() methodworks similarly. It takes on the additional list as a parameter. The * operator, like in tuples, multiplies the elements in the list You can add items to the end of the list with the append() method.
  • 58.
    You can alsoinsert an element within the list using the insert() method. Comparing Lists Deleting Values You can delete an element from the list using the del keyword and the offset of the element.
  • 59.
    Another way youcan delete an element is by using the remove() method and indicating the value of the element. A third way to remove an element from a list is using the pop() method. You can delete all items in a list by using the clear() method.
  • 60.
    Finding Information Using inreturns a Boolean value. Using the index() method. The len() function returns the number of elements in a list. Using the count() method.
  • 61.
    Copying Values You cancreate copies of lists using the copy() method. It works best if all the values of list elements are immutable. But what if we have something mutable like a whole list as a list element? let’s delete an element from the additional list and see how this affects the other lists that contain it.
  • 62.
    To copy theactual values from one list to another and not just the reference, we can use Python’s copy module. Let’s use deepcopy().
  • 63.
    Reordering Elements • Thesort() method rearranges values of the list in itself. • The sorted() function creates a sorted copy of a list.
  • 64.
    What are thedifference between Tuples and Lists?
  • 65.
    Lesson 6: Setsand Dictionaries • In this lesson, we will be learning more about collection data types, particularly unordered sets (sets and frozensets) and dictionaries. After studying this lesson, you should be able to: • define sets and dictionaries; • manipulate these data types; and • explore the uses of these data types. Objectives
  • 66.
    Set is acollection data type made up of unordered elements. Just think of your lessons on sets in math class. Python sets function much like the sets you studied in math. Specifying Tuples To specify a set, you can use the curly braces {}. Try these out in the interpreter. Example To create an empty set, you must use the function.
  • 67.
    Creating Sets Outof Other Types the set() function can be used to create sets out of strings, lists, tuples, and dictionaries. Using the len() function. Notice how this is also the case for the other data types which include multiple elements with similar values.
  • 68.
    Adding and DeletingElements To add an element, you need to use the add() method. You can also delete an element by using the remove() method. Finding Information
  • 69.
  • 70.
    Let’s check outhow they work. Define two sets in the interpreter Try using the operators and methods.
  • 71.
    Frozensets are basicallysets with immutable values. To specify a frozenset or create a frozenset out of other data types, you use the frozenset() function. To see if the values really are immutable, try using the add() or remove() methods.
  • 72.
    A dictionary isa collection data type that consists of key and value pairs. Specifying Dictionaries To specify a dictionary, you can use either curly brackets ({}) with key and value pairs that use the colon (:) separated by commas (,). You can also use the dict() function
  • 73.
    Creating Dictionaries Out ofOther Types Combine two lists into a dictionary using the dict() and zip() functions.
  • 74.
    Adding and ChangingElements To add a value, simply specify a key in the offset and assign a value. To change a value, simply refer to a key and assign a new value. If the key does not exist, a new element will be added.
  • 75.
    Delete elements fromthe dictionary by using the del keyword To delete all items in a dictionary, use the clear() method. Finding Information Using len() function You can get the value associated to a key by entering the key.
  • 76.
    If you tryto get a value for a key that does not exist, Python will return an error. To check if a key exists. You can also get the value of a key using the get() method. You can get the keys from a dictionary using the keys() method.
  • 77.
    You can turnthe result of the keys() method into a list using the list() function. Doing so creates a copy of the keys. If you can get keys, you can also get values. You can use the values() method. You can also make a list out of this result.
  • 78.
    Combining Dictionaries You cancombine or merge two dictionaries using **. You can also use the update() method to insert dictionary values into an existing one.
  • 79.
    Comparing Dictionaries You cancompare dictionaries but only using the equality operators (==) and (!=). Python compares elements one by one regardless of sequence or order. If they match, Python will return a True value.
  • 80.
    Lesson 7: Conditionals,Loops, and Input • In this lesson, we are moving on to some of the more exciting concepts in computer programming. We will learn about conditionals, loops, and the input() function. After studying this lesson, you should be able to: • define what conditionals and loops are; • use conditionals and loops; and • allow user input in your programs. Objectives
  • 81.
    IDLE Editor Click File> New File or Ctrl + N. To run a program, press F5.
  • 82.
    PyCharm Editor 1.Click the project root in the Project tool window > New > Python File. 2. Select Python file from the popup window, and then type the new filename. 3. Run the program (Shift-Alt-F10)
  • 83.
    Conditionals allow youto execute lines of code if particular conditions are met. Syntax Output
  • 84.
    Nesting Conditions You canplace other conditional statements within conditions. Syntax Output
  • 85.
    We can furtherrefine the code using the elif keyword so we can check for more than one condition. Syntax Output
  • 86.
  • 87.
    Comparing with thein Keyword Say we want to check a letter if it is a vowel or not. We can manually set multiple conditions using if, elif, and else: A shorter version of this uses the or keyword. You can also use the in keyword.
  • 88.
    Loops The while keywordallows us to execute code over and over until a condition is met. Syntax Output
  • 89.
    Assignment Operators Wecan also create loops using the for and in keywords. Let’s say we want to print each letter in the string “kerfuffle” Syntax Output
  • 90.
    Iterating through Collections Tuples SyntaxOutput Lists Sets Dictionaries
  • 91.
    Break and Continue Thebreak keyword is used when you want to loop something indefinitely until a condition is met. Syntax Output The continue keyword skips running the code for an iteration. Syntax Output
  • 92.
    The range() functioncreates a sequence of numbers. It takes on three arguments: • start - The start of the sequence • stop - The end of the sequence • step - How much the range increments
  • 93.
    Input • The input()function allows us to show a prompt and have the user to provide some information. • The function takes on a parameter for a prompt. Syntax Output
  • 94.
  • 95.
    Lesson 8: Functions,Classes, and Objects • In this lesson, we will be learning how to create and use functions, classes, and objects. After studying this lesson, you should be able to: • define functions, classes, and objects; • create samples of functions, classes, and objects; and • use them in programs. Objectives
  • 96.
    Functions • allow usto perform various tasks without having to code the instructions over and over. All we have to do is to call the function and pass on some arguments for us to get some form of result. Defining and Calling Functions To define a function, we use the def keyword. We specify the function name, its input parameters in parentheses (if needed), and a colon (:). Syntax Output
  • 97.
    Arguments and Parameters Let’screate a function called times_five(), which multiplies any value passed into it through the argument “number” by five. Syntax Output Let’s try converting the vowel checker program that we had in the previous unit into a function. The function takes on the argument “letter”. Syntax Output
  • 98.
    Positional arguments passon values based on their position. Syntax Output Keyword arguments allows you to indicate the argument names and their corresponding parameters. Syntax Output
  • 99.
    What if youforget to add providing a value for an expected argument? A way to prevent this is by immediately assigning a value in the def statement. Syntax Output
  • 100.
    What if weneed our function to be flexible and be able to take on a variable number of arguments? Syntax Output You can also use **kwargs to create a dictionary from the arguments. Syntax Output
  • 101.
    Global vs. LocalVariables Global variables are accessible throughout the program. Local variables are only accessible within the function in which they are declared. To Declare To Call Output
  • 102.
    Objects and Classes •Object-Oriented Programming (OOP) is a programming paradigm where software is designed based on real-world objects rather than simply as sequences of instructions and logic. • Objects in OOP are data structures that have attributes and methods. • Class is the characteristic of an object. Example: Dog > Bantay > brown fur and four legs
  • 103.
    Defining Classes To createa class, we use the class keyword. • The __init__ method is what is called a constructor in OOP. • The self keyword allows us to access the attributes and methods that we will be creating for the class. Creating Objects To create an object from a class, we call the class and assign it to a variable. We can access the attribute values of dog1 by using dot notation. Output
  • 104.
    Adding and UsingMethods Next, we will add an ability to our Dog class. This allows all dog objects to bark and can be triggered by calling the bark() method of our object.
  • 105.
    Changing Object Properties Output Deletingan Object Child Classes and Inheritance Let’s create an object based on this Pug class
  • 106.
    Overriding Using ChildClasses Syntax Output
  • 107.
    Lesson 9: Modules •In this lesson, we will be exploring Python’s extensibility using modules. We willl learn how to download them, import them into our programs, and use their functionalities. After studying this lesson, you should be able to: • explore built-in modules available in Python; • download and import modules; and • use modules to build programs. Objectives
  • 108.
    Modules and Packages CreatingModules In PyCharm, you can do this by rightclicking on the project tool window and selecting New > Python File. Name it vowel_ checker.py. Then copy the code below. Go back to main.py and enter the following code:
  • 109.
    Importing Modules To importan entire module, we can use the import keyword. Example: What this does basically translates to: Installing Third-Party Packages The easiest way to install these third-party packages is by using Python’s package installer or pip.
  • 110.
    In PyCharm, simplybring up the Terminal tool window. In the command line, enter: In the terminal, type:
  • 111.
    Working with Modulesand Packages Random allows us to generate “random” numbers and randomize from a set of elements. Three of its commonly-used methods are:
  • 112.
    Turtle graphics isanother interesting Python module. It simulates a digital turtle drawing lines on the screen as it moves. Setting Up the Screen Create our turtle object.
  • 113.
    Drawing a SquareDrawing a Circle This tells the turtle to draw a circle with a radius of 50 pixels. This way, we get a circle with a diameter of 100 pixels. Drawing a Triangle
  • 114.
    More Methods Try outthese other Turtle methods and see how they work. • setposition() • home() • undo() • pendown() • penup() • pensize() • color() • pencolor() • fillcolor() • filling() • begin_fill() • end_fill() • showturtle() • hideturtle()
  • 115.
    Tkinter is abuilt-in module in Python used for building GUI based applications.
  • 116.
    Lesson 10: PythonProject • In this lesson, we will be putting all we have learned in the course together to create different projects using Python. After studying this lesson, you should be able to: • create a Bato Bato Pik (rock, paper, scissors) game; • build a word counter app; and • make a price checker app. Objectives
  • 117.
    Bato Bato Pikis our local version of Rock, Paper, Scissors. A player has three choices: 1) rock (bato), 2) paper (papel), or 3) scissors (gunting). The opponent (in this case, the computer) also makes a play based on the same choices. The outcome depends on these choices. Rock crushes scissors. Paper covers rock. Scissors cut paper. A player can win, lose, or draw.
  • 118.
    Word Counter a tinyapp that counts the number of words in a text box.
  • 119.
    Price Checker It isa grocery price checker. It allows you to click on a product, and the app will display its price.
  • 120.

Editor's Notes

  • #6 Discuss how essential the computer before introducing python.
  • #8  Python’s Key Features Easy-to-Use. Python is an easy programming language to learn. It reads just like simple English. Interpreted. Python’s interpreter is platform-independent. It can run Python programs on Windows, macOS, or Linux. Interpreted languages are also easy to debug. If the interpreter catches errors, an exception is thrown. You can review the error messages to see which parts of the code are causing issues. High-level. High-level programming languages take care of the many tedious tasks in programming and development. In lower-languages, you have to do manual memory management, which can be painstaking to do. You can focus on creating your program. Dynamically-Typed. You do not have to specify the type of a variable before you can use it. The interpreter will do it for you. Expressive. In computer science, expressiveness refers to how much can be done by the code. Python is an expressive language. You can accomplish more with fewer lines of code compared to other languages. Extensible. Developers can write modules using other languages like C and C++, allowing Python to interface with libraries written in these languages. Available Libraries. Python’s standard library contains hundreds of modules. This means that you can readily incorporate these available functionalities, making it ideal for building applications quickly. There are also over 100,000 third-party libraries that you can use. Support for GUI. It also has a library of graphical user interface (GUI) tools to help you build applications with visual interfaces. Cross-platform Development. You can develop with Python using Windows, Mac, Linux, and even Android devices. Free and Open-source. You do not have to pay anything to use or run Python. Everyone can also view its source code. Python’s Uses and Applications Web Applications. Python features libraries for handling Internet protocols and web data in HTML, XML, and JSON formats. It can process emails and parse feeds like Atom and RSS. Several popular frameworks for rapid web application development, such as Django, Flask, Tornado, and web2py, use Python. Data and Analytics. Researchers and data teams are using data and analytics to make sense of all the millions of gigabytes of data we generate daily. Python has become a popular data science tool, thanks to data processing and analysis libraries such as Pandas and TensorFlow. Libraries like Seaborn and Matplotlib can help data teams visualize their data through histograms, charts, and graphs. Research. Python is also a popular tool for research in various fields. Python libraries like NumPy for numerical computation and SciPy for scientific computation are widely used in mathematics and scientific research. Python also has libraries for text scraping and natural language processing (NLP), making it a versatile tool for linguistic research, sentiment analysis, and even market research. Artificial Intelligence (AI) and Machine Learning (ML). Various projects that are working on AI and ML are also using Python. The PyBrain library, for example, allows programmers to build and develop ML algorithms. Python also has libraries for signal processing and image recognition, allowing developers to create programs that can analyze and learn from images and sounds. Business and Enterprise. Python is also being used in business and finance, especially in enterprise applications and solutions. Companies can quickly develop programs to address emerging concerns. Python can be integrated with solutions built using other languages and databases, addressing backward and cross-compatibility issues. Because of its flexibility and the range of available libraries, Python covers a wide range of applications, including automation, e-commerce, marketing, and finance. Game Development. Python is also being used in game development. Libraries and frameworks also provide functionalities such as level design, controls, media, and game rules. The language is also capable of handling both 2D and 3D graphics. Some popular titles that have used Python are World of Tanks, Battlefield 2, and Civilization IV. Internet-of-Things. Devices are becoming increasingly connected. Aside from computing devices such as desktops, laptops, and mobile devices, even household appliances, vehicles, and industrial machineries are now able to connect to the Internet. Python is used to create embedded systems and programs to run on these devices.
  • #10 Demonstrate how to download the python by going to its website.
  • #11 Demonstrate
  • #12  PyCharm is developed by JetBrains, a Czech software development company that makes tools for software development teams. PyCharm works on multiple platforms such as Windows, macOS, and Linux versions. There are two editions of PyCharm available for download on the JetBrain’s website: Community and Professional. The Community edition is a free and open-source tool but has limited features. The Professional edition is commercial and provides more features, including support for web frameworks. For this course, we will be using the Community edition.
  • #13 Demonstrate how to download the pycharm by going to its website.
  • #14 Demonstrate
  • #15 Demonstrate
  • #16 Demonstrate
  • #17 Demonstrate
  • #19 Discuss and demonstrate Main Menu - Provides access to most of the functionalities in PyCharm. Commands are grouped into File, Edit, View, Navigate, Code, Refactor, Run, Tools, VCS, Window, and Help. Toolbar - Provides quick access to the most commonly accessed tools such as Open, Save, Run, and Debug. If this is not available in your first run, you can enable it by clicking View > Appearance > Toolbar. Editor - The space where you work on your code. Navigation Bar - Allows you to navigate the files and folder of your project. Tool Window Bars - Located at the edges of the GUI. Can be toggled to show the various tools including Project, Favorites, Problems, Structure, Services, Event Log, Python Console, Terminal, and TODO. Status Bar - Displays information about the project including errors and warnings.
  • #20  PyCharm can be a large download for some users. Some older and slower computers may have problems using the IDE. Fortunately, Python already comes with its own development environment called IDLE (short for Integrated Development and Learning Environment).
  • #27  Any data that you will be working within Python will have a corresponding data type.
  • #29  We may have been able to change to which data or object a variable may be assigned (x is now associated with 2), but the object (1) remains unchanged after it is created within the program.
  • #30  Why does mutability matter? It is good to know how these properties can affect the program. For instance, immutable objects are considered “thread-safe” in cases when the computer is capable of multithreading or running multiple processes at once. This ensures that the code will work even if the objects are passed on across threads. Immutability also promotes clarity and exactness in the code, as every immutable object is guaranteed to remain the same as the program runs.
  • #31  We can specify data values in Python through either literal values and variables.
  • #35  We have already started working with numerical data in the previous unit. Let’s get to know more about them. The most common numerical data types you will likely use in your programming journey are integers and floating-point numbers.
  • #38  Enter the following lines in the interpreter and see their results. Floating-point division will result in a float value (with a decimal point) if the result is not an exact integer. Floor (or integer) division basically leaves out the decimal values. Modulo returns the remainder of a division.
  • #41  We will be using Boolean values later on when we try to do some logical operations and check the truth value of certain expressions.
  • #43  Notice how there are a bunch of “\n” in the string. The backslash ( \ ) is an escape character. It is used to insert whitespace characters to the string. “\n” creates a new line. To display the value in a more human-friendly format, use the print() function.
  • #51  Tuples are immutable data types, meaning you will not be able to modify their values once you have specified them.
  • #52  You can assign the elements of a tuple into variables. This is also called unpacking a tuple.
  • #54  This compares the element of each tuple with the other. So, since superhero[0] is not equal in value to epic_hero[0] right from the start, the comparison fails, and the output is False.
  • #57  Since lists are mutable, you can change their values in several ways. To start, you can use the + and * operators on lists too. You can use the + to add two lists together. Just be sure to assign the operation to a variable first.
  • #58  Keep in mind that the append() method only adds a single element to the end of the list. If you try to append a list, the whole list will be appended as a single element in another. If that is what you want to achieve, it is better to use the + operator instead.
  • #59  You need to indicate the offset before which an item will be added and the item’s value. Indicating an offset of 0 inserts the element at the start of the list.
  • #63  Modules extend Python’s capabilities. The copy module gives us access to the deep copy operation. We will learn more about modules in a later unit.
  • #64  By default, the method arranges the values in ascending order. The method can take on an argument. Using reverse = True will sort the list elements in descending order.
  • #65 Ask the students
  • #67  Unlike with lists, the sequences of elements do not matter in sets. And another thing that differentiates sets from lists is that sets are also made up of unique elements. They can’t have duplicate values. Sets are useful when you simply need to store a set of unique values.
  • #68  When passing on string values, the set() function takes each character and creates an element out of it. However, it only takes one of each. The string “alphabet” technically has eight (8) characters but let’s check the length of the set using the len() function. The string “alphabet” has two “a” characters, but only one is included in the set.
  • #72  Frozensets do not support methods that modify values. If you try using them, Python will return error messages.
  • #73  Keys are unique identifiers and are usually composed of strings, but they can be made up of other Python’s immutable data types. Dictionaries are mutable, meaning you can change its elements and values by adding, deleting, or changing its key or value contents.
  • #74  The dict() function can also be used to create dictionaries from other types but you need to have two-value sequences.
  • #77  Notice how the method returns dict_keys() which is a dictionary view object that supports iteration. The keys are in the order in which they appear in the list.
  • #79  Keep in mind that if there are similar keys, the value of the second dictionary will be kept.
  • #82  Now, we are actually writing multiple lines of code. To test this, we will be using the editor for our code and using the Run option (in both IDLE and PyCharm) rather than typing lines within the interpreter.
  • #84  Let’s take a look at the example. It uses the if keyword to indicate a conditional statement. First, we specified a value for the variable winner. Then, we checked it for two conditions. First, if the value assigned to it is True, then we execute the print(‘Hooray!’) function. Second, if it is not (as indicated by the else keyword), then we execute the print(‘Boo!’) function. Other programming languages use special characters like parentheses, braces, and semi-colons to organize code. Python uses white space characters to indicate which lines are part of the conditional, loop, function, etc. In this case, we use four spaces to indent the next line. This is based on the PEP-8 style guide (https://www. python.org/dev/peps/pep-0008/). The PyCharm IDE allows you to press the tab key, and it will automatically insert the four spaces for you instead of inserting a tab white space character. In fact, PyCharm also warns you of any PEP-8 style inconsistencies in your code. These appear in the Problems tool window.
  • #85  And, you can also test them using the various comparison operators that we discussed.
  • #88 Ask the students , what is the output? Output: That is a vowel!
  • #89 Introduce loops by giving some examples. 1-5 then 1-200
  • #95 Let’s try to make a simple guessing game: Instruct the students to type the displayed syntax and let them try it. Explain the For this program, we had to import the random module, which allows us to generate numbers randomly. We also had to convert the number (which is generated as an integer) to a string since the input() function specifies numeric inputs as strings.
  • #97  To use our newly created function, we “call” it by its name. It runs the instructions it contains. In this case, it prints the string “Hello!” Note that PEP-8 advises us to insert two new lines after a function definition. We can also create functions that return a value. def gimme_five(): return 5 print(gimme_five())
  • #98  We can also define functions that take in arguments. The values indicated in the argument are passed on to the corresponding parameter within the function.
  • #99  By using keyword arguments, you’d be assured that the values get assigned to the proper parameters.
  • #101  What if we need our function to be flexible and be able to take on a variable number of arguments? Fortunately, Python allows us to do this by using *args, which generates a tuple as values. Note that the sequence of tuple elements will be based on the order of positional arguments you indicate when you call the function. Also, using “args” has just become a common practice among Python coders. You can use another name such as “fruits” in your argument and use “fruits” in your function parameters. What is important is to use the unpacking operator (\).
  • #104  The __init__ method allows the class to create an object and initialize the attributes that the object can take.
  • #106  Python also allows you to create child classes which can inherit or share attributes and methods from its parent class. Ask the students what will be the output after adding the pug class. As you can see, we were able to create an object, assign values, and even call a method that were all only defined in our Dog class. But since our Pug class is a child of the Dog class, it inherits the attributes and methods from the parent class.
  • #109  Technically, a module can be any file with Python code. You can import the classes, functions, and definitions the file contains and use them in your main module (main. py). Python also has built-in modules that you can import to perform a variety of specialized functionalities. You can also get modules from repositories and libraries from the Internet. Let the students try it.
  • #112 Ask the students to do the Coin flipping or Head or Tails found in the book Python Coding Essentials Page 107 -108
  • #113 Remind the students If you are using a code editor (either IDLE or PyCharm), be sure to insert the following code as the last line in your code to prevent the window from closing when you run your program. turtle.done()
  • #114 Ask the students to draw the square using loop: import turtle window = turtle.Screen() window.title = ‘Turtle’ window.bgcolor(‘light blue’) mike = turtle.Turtle() number = 1 while number <= 4: mike.forward(100) mike.left(90) number += 1 turtle.done() Ask the students to draw the triangle using loop: import turtle window = turtle.Screen() window.title = ‘Turtle’ window.bgcolor(‘light blue’) mike = turtle.Turtle() number = 1 while number <= 3: mike.forward(100) mike.left(120) number += 1 turtle.done()
  • #116 Explain how the code works.
  • #118 Ask the students to create a bato bato pik game. They can use the Python Coding Essentials Book to be their reference.
  • #119 Ask the students to create a TINY APP. They can use the Python Coding Essentials Book to be their reference.
  • #120 Ask the students to create a Price Checker. They can use the Python Coding Essentials Book to be their reference.