0% found this document useful (0 votes)
20 views

Programming Quarter 2 Python

Uploaded by

izraelcatolico
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Programming Quarter 2 Python

Uploaded by

izraelcatolico
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 87

Python

Python is an interpreted programming


language, this means that as a
developer you write Python (.py) files
in a text editor and then put those files
into the python interpreter to be
executed.
What is Python?
Python is a popular programming language. It was
created by Guido van Rossum, and released in
1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
Why Python?

• Python works on different platforms (Windows, Mac,


Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English
language.
• Python has syntax that allows developers to write
programs with fewer lines than some other
programming languages.
Python Syntax compared to
other programming languages
• Python was designed for readability, and has
some similarities to the English language with
influence from mathematics.
• Python uses new lines to complete a command,
as opposed to other programming languages
which often use semicolons or parentheses.
Python Install

• Many PCs and Macs will have python already installed.

• To check if you have python installed on a Windows PC,


search in the start bar for Python or run the following on
the Command Line (cmd.exe):
YOUR FIRST LINE OF CODE
• https://www.programiz.com/python-programming/online-compiler/

• OR OPEN VISUAL STUDIO CODE when using laptop/desktop


Python Indentation

• Indentation refers to the spaces at the beginning of a


code line.

• Where in other programming languages the indentation


in code is for readability only, the indentation in Python
is very important.

• Python uses indentation to indicate a block of code.


ExampleGet yo
• if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:

• if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same
block of code, otherwise Python will give you an error:

if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

• Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables

Variables in Python:
•x = 5
y = "Hello, World!"

Python has no command for declaring a variable.


Comments
• Python has commenting capability for the purpose of in-
code documentation.
• Comments start with a #, and Python will render the
rest of the line as a comment:

Example
Comments in Python:
#This is a comment.
print("Hello, World!")
A comment does not have to be text that explains the
code, it can also be used to prevent Python from
executing code:

Example
#print("Hello, World!")
print("Cheers, Mate!")

print("Hello, World!") #This is a comment

#This is a comment
print("Hello, World!")
Multiline Comments
• Python does not really have a syntax for multiline comments.
• To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
• Since Python will ignore string literals that are not
assigned to a variable, you can add a multiline string
(triple quotes) in your code, and place your comment
inside it:

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python Variables
Variables are containers for storing data values.
• A variable is created the moment you first assign a
value to it.
Example
x = 5
y = "John"
print(x)
print(y)
• Variables do not need to be declared with any particular type,
and can even change type after they have been set.

Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

• You can get the data type of a variable with the type() function.
x = 5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
• x = "John"
# is the same as
x = 'John'
Case-Sensitive
Example
This will create two variables:

a=4
A = "Sally"
#A will not overwrite a
Variable Names

• A variable can have a short name (like


x and y) or a more descriptive name
(age, carname, total_volume).
Rules for Python variables:
• A variable name must start with a letter or the
underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE
are three different variables)
• A variable name cannot be any of the Python keywords.
Multi Words Variable Names
Camel Case
• Each word, except the first, starts with a capital letter:

myVariableName = "John“

Pascal Case
• Each word starts with a capital letter:

MyVariableName = "John"
Snake Case
• Each word is separated by an underscore character:

my_variable_name = "John"
Python Variables - Assign Multiple
Values
Python allows you to assign values to
multiple variables in one line:

x, y, z
= "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One Value to Multiple Variables
And you can assign the same value to multiple variables
in one line:

x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
• If you have a collection of values in a list, tuple etc.
Python allows you to extract the values into variables.
This is called unpacking.
Example
Unpack a list:
• fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
PYTHON - OUTPUT VARIABLES
• The Python print() function is often used to output variables.
• In the print() function, you output multiple variables, separated by a
comma:
Example
• x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
• You can also use the + operator to output multiple variables:

Example
• x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

• Notice the space character after "Python " and "is ", without them the
result would be "Pythonisawesome".
• For numbers, the + character works as a mathematical
operator:
x = 5
y = 10
print(x + y)

In the print() function, when you try to combine a string and a number
with the + operator, Python will give you an error:
Example
x = 5
y = "John"
print(x + y)
• The best way to output multiple variables in
the print() function is to separate them with
commas, which even support different data
types:

Example:
x = 5
y = "John"
print(x, y)
GLOBAL VARIABLES
• Variables that are created outside of a function are known as
global variables.
• Global variables can be used by everyone, both inside of
functions and outside.
Example
Create a variable outside of a function, and use it inside the
function
x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()
• If you create a variable with the same name inside a function,
this variable will be local, and can only be used inside the
function. The global variable with the same name will remain
as it was, global and with the original value.
Example
• Create a variable inside a function, with the same name as the global
variable
x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)
THE GLOBAL KEYWORD
• To create a global variable inside a function, you can use the global
keyword.
Example
• If you use the global keyword, the variable belongs to the global scope:

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
To be continued in Data Types
chapter:
• DITO NA ANG LESSON (NEWTON)
PYTHON DATA TYPES
Built-in Data Types
• In programming, data type is an
important concept.
• Variables can store data of different
types, and different types can do
different things.
Python has the following data types built-in
by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
Getting the Data Type
• You can get the data type of any object by using the type()
function:

Example
Print the data type of the variable x:

x=5
print(type(x))
Setting the Data Type
• In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", frozenset
"cherry"})
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Setting the Specific Data Type
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list

x = tuple(("apple", "banana", "cherry")) tuple

x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set

x = frozenset(("apple", "banana", frozenset


"cherry"))
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Python Numbers
There are three numeric types in Python:

int
float
complex
Variables of numeric types are created when
you assign a value to them:

Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
Int
• Int, or integer, is a whole number, positive or
negative, without decimals, of unlimited length.

Example
Integers:
x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or
negative, containing one or more decimals.

Example
Floats:
x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers
with an "e" to indicate the power of 10.
Example
• Floats:
• x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))
Complex
• Complex numbers are written with a "j" as the imaginary
part:

Example
• Complex:
x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and
complex() methods:
Example
• Convert from one type to another:
• x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))
Random Number
• Python does not have a random() function to make a
random number, but Python has a built-in module
called random that can be used to make random
numbers:
Example
• Import the random module, and display a random
number between 1 and 9:
import random

print(random.randrange(1, 10))
Python Casting
Specify a Variable Type

• There may be times when you want to


specify a type on to a variable. This can be
done with casting. Python is an object-
orientated language, and as such it uses
classes to define data types, including its
primitive types.
Casting in python is therefore done using
constructor functions:
• int() - constructs an integer number from an integer
literal, a float literal (by removing all decimals), or a
string literal (providing the string represents a whole
number)
• float() - constructs a float number from an integer
literal, a float literal or a string literal (providing the
string represents a float or an integer)
• str() - constructs a string from a wide variety of data
types, including strings, integer literals and float
literals
Example your own Python Server
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
PYTHON STRINGS
Python Strings
• Strings in python are surrounded by either single quotation
marks, or double quotation marks.
• 'hello' is the same as "hello".
• You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')
Quotes Inside Quotes
• You can use quotes inside a string, as long as
they don't match the quotes surrounding the
string:

Example
print("It's alright")
print("He is called 'Johnny’”)
print('He is called "Johnny"')
Assign String to a Variable

• Assigning a string to a variable is done with the variable


name followed by an equal sign and the string:

Example
a = "Hello"
print(a)
Multiline Strings
• You can assign a multiline string to a variable by using
three quotes:

Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Or three single quotes:
a = '''Lorem ipsum dolor sit
amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna
aliqua.'''
print(a)
Strings are Arrays
• Like many other popular programming
languages, strings in Python are arrays of
bytes representing unicode characters.
• However, Python does not have a character
data type, a single character is simply a
string with a length of 1.
• Square brackets can be used to access
elements of the string.
Example
Get the character at position 1
(remember that the first character has
the position 0):

a = "Hello, World!"
print(a[1])
Looping Through a String

• Since strings are arrays, we can loop through the characters in a


string, with a for loop.
Example
• Loop through the letters in the word "banana":

for x in "banana":
print(x)
String Length
To get the length of a string, use
the len() function.

Example
The len() function returns the length of a
string:
a = "Hello, World!"
print(len(a))
Check String

To check if a certain phrase or character is present


in a string, we can use the keyword in.

Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
Use it in an if statement:
Example
Print only if "free" is present:

• txt = "The best things in life are


free!"
if "free" in txt:
print("Yes, 'free' is present.")
Check if NOT
To check if a certain phrase or character is NOT
present in a string, we can use the keyword not
in.

Example
Check if "expensive" is NOT present in the
following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Use it in an if statement:

Example

print only if "expensive" is NOT present:


• txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT
present.")
Slicing Strings
• You can return a range of characters by using the slice
syntax.
• Specify the start index and the end index, separated by
a colon, to return a part of the string.
Example
• Get the characters from position 2 to position 5 (not
included):
b = "Hello, World!"
print(b[2:5])

Note: The first character has index 0.


Slice From the Start

Example
Get the characters from the start to position
5 (not included):

b = "Hello, World!"
print(b[:5])
Slice To the End
• By leaving out the end index, the range will go to the
end:

Example
Get the characters from position 2, and all the way to the
end:

b = "Hello, World!"
print(b[2:])
Negative Indexing
• Use negative indexes to start the slice from the end of
the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):

• b = "Hello, World!"
print(b[-5:-2])
Python - Modify Strings

•Python has a set of built-


in methods that you can
use on strings.
UPPER CASE

Example

• The upper() method returns the string in upper


case:

a = "Hello, World!"
print(a.upper())
LOWER CASE

Example

The lower() method returns the string


in lower case:

a = "Hello, World!"
print(a.lower())
Remove Whitespace
• Whitespace is the space before and/or after the actual
text, and very often you want to remove this space.

Example
• The strip() method removes any whitespace from the beginning or
the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"
REPLACE STRING
Example

The replace() method replaces a


string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))
SPLIT STRING
• The split() method returns a list where the text between the specified
separator becomes the list items.

EXAMPLE
• The split() method splits the string into substrings if it finds instances
of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', '
World!']
STRING CONCATENATION
• To concatenate, or combine, two strings you can use the
+ operator.

EXAMPLE
Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c = a + b
print(c)
Example
To add a space between them, add a " ":

a = "Hello"
b = "World"
c = a + " " + b
print(c)
Python - Format - Strings
String Format
• As we learned in the Python Variables chapter, we
cannot combine strings and numbers like this:

Example
• age = 36
txt = "My name is John, I am " + age
print(txt)

• But we can combine strings and numbers by using f-


strings or the format() method!
F-Strings
• To specify a string as an f-string, simply put an f in
front of the string literal, and add curly brackets {} as
placeholders for variables and other operations.
Example
• Create an f-string:

• age = 36
txt = f"My name is John, I am {age}"
print(txt)
Placeholders and Modifiers
• A placeholder can contain variables, operations,
functions, and modifiers to format the value.

Example
• Add a placeholder for the price variable:

price = 59
txt = f"The price is {price} dollars"
print(txt)
Python - Escape Characters
• To insert characters that are illegal in a string, use
an escape character.

• An escape character is a backslash \ followed by


the character you want to insert.

• An example of an illegal character is a double


quote inside a string that is surrounded by double
quotes:
Example
You will get an error if you use double quotes inside a
string that is surrounded by double quotes:

txt = "We are the so-called "Vikings" from the


north."

Example
To fix this problem, use the escape
character \":

txt = "We are the so-called \"Vikings\" from the


north."
Escape Characters
CODE RESULT
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
String Methods
Python has a set of built-in methods that you can use on
strings.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a
string

encode() Returns an encoded version of the string


endswith() Returns true if the string ends with the specified value
Continuation
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and
returns the position of where it was found

format() Formats specified values in a string


format_map() Formats specified values in a string
index() Searches the string for a specified value and
returns the position of where it was found

isalnum() Returns True if all characters in the string are


alphanumeric
isalpha() Returns True if all characters in the string are in
the alphabet
isascii() Returns True if all characters in the string are ascii
characters
isdecimal() Returns True if all characters in the string are
decimals
isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier


islower() Returns True if all characters in the string are lower
case
isnumeric() Returns True if all characters in the string are
numeric
isprintable() Returns True if all characters in the string are
printable
isspace() Returns True if all characters in the string are
whitespaces
istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are


upper case
join() Joins the elements of an iterable to the end of the
string
ljust() Returns a left justified version of the string

lower() Converts a string into lower case


lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in
translations
partition() Returns a tuple where the string is parted into
three parts
replace() Returns a string where a specified value is
replaced with a specified value
rfind() Searches the string for a specified value and
returns the last position of where it was found

rindex() Searches the string for a specified value and


returns the last position of where it was found
rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into


three parts
rsplit() Splits the string at the specified separator, and
returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and
returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string


swapcase() Swaps cases, lower case becomes upper case and vice
versa
title() Converts the first character of each word to upper case

translate() Returns a translated string


upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the
beginning
Python Boolea
ns

You might also like