Programming Quarter 2 Python
Programming Quarter 2 Python
• 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!"
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!")
#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
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 = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
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
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
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
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
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
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:
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
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
Example
a = "Hello, World!"
print(a.upper())
LOWER CASE
Example
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.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)
• 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.
Example
To fix this problem, use the escape
character \":