Week 3 – Introduction to
Python
Learning Objectives:
• Write your first Python program
• Learn what happens when you run a program with an error
• Learn how to declare a variable and inspect its value
• Learn how to write comment
What is Python?
• Python is a general purpose programming language
that is often applied in scripting roles.
• Python is a programming language as well as
scripting language
• Python is an interpreted, object-oriented, high-
level programming language.
Programming vs. Scripting
Language
• Program • Scripting
• A program is executed (i.e. the • A script is interpreted.
source is first compiled and the • A “script” is code written in a
result of the compilation is scripting language. A scripting
expected) language is nothing but a type of
• A “program” in general, is a programming language in which
sequence of instructions written we can write code to control
so that a computer can perform another software application.
certain task.
History
• Invented in the Netherlands, early 90s by Guido van Rossum
• Python was conceived in the late 1980s and its implementation was
started in December 1989
• Guido Van Rossum is a fan of “Monty Python’s Flying Circus”, this is
famous TV show in Netherlands
• Named after Monty Python
• Open sourced from the beginning
Why Use Python?
• It is known for its simplicity, readability, and ease of use
• Can create the following
• Systems programming
• Graphical User Interface Programming
• Database Programming
• Component Integration
• Gaming, Images, XML, Robotics
• Web Applications
• For Data Science and Data Visualization
• Machine Learning
• Script for Vulnerability Testing
5 of the many reasons to use Python
1. Easy to Learn and Use
2. Versatile
3. Large and Active Community
4. Cross-Platform Compatibility
5. Open-source
Who Uses Python Today…
• Python is being applied in real revenue-generating products by real
companies. For instance:
• Google makes extensive use of Python in its web search system, and
employs Python’s creator.
• Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use
Python for hard testing.
• ESRI uses Python as end-user customization tool for its popular GIS
mapping products.
• The YouTube video sharing is largely written in Python.
Requirements
• Python 3 Interpreter or above
• IDE Options
• Offline
• Pycharm
• Anacoda/Jupyter Notebook
• Online:
• onlinegdb.com
• colab.google
• replit.com
• online-python.com/online_python_compiler
Installing Python
• Download the latest version of python from
https://www.python.org/downloads/
Installing Python
Once you start the
installation process,
you will see the
following pop-up:
Installing Python
Once this process is
completed, open Python
from the start menu and
click on Python version that
you have installed to launch
python command line. It is
prompt with >>> where you
write your single line
command
Using PyCharm
• Download the installer (.exe) preferably the community edition.
• Run the installer and follow the wizard steps.
• Mind the following options in the installation wizard
• 64-bit launcher: Adds a launching icon to the Desktop.
• Open Folder as Project: Adds an option to the folder context menu that will allow opening the
selected directory as a PyCharm project.
• .py: Establishes an association with Python files to open them in PyCharm.
• Add launchers dir to the PATH: Allows running this PyCharm instance from the Console without
specifying the path to it.
• To run PyCharm, find it in the Windows Start menu or use the desktop shortcut. You
can also run the launcher batch script or executable in the installation directory under
bin.
Create a Python project
When you open PyCharm for the first
time, you are presented with the
Welcome Screen. In PyCharm, the next
step is to create Project. The project is
your central view for running code,
debugging code, Python console, system
terminal, tests, coverage, profiling,
version control, databases, frontends...
Etc. If you’ve already worked on a project,
the welcome screen will look a bit
different. It will have a list of your recent
projects in the center but the options will
stay the same.
Create a Python project
• Although you can create projects of various types in
PyCharm, in this tutorial let's create a simple Pure Python
project. This template will create an empty project.
• Choose the project location. Click the Browse button in the
Location field and specify the directory for your project.
• Python best practice is to create a dedicated environment
for each project. In most cases, the default Project venv will
do the job, and you won't need to configure anything.
• Still, you can switch to Custom environment to be able to
use an existing environment, select other environment
types, specify the environment location, and modify other
options.
• Click Create when you are ready.
Create a Python file
• In the Project tool window, select the project root (typically,
it is the root node in the project tree), right-click it, and
select File | New ....
Create a Python file
• Select the option Python File from the
context menu, and then type the new
filename.
Create a Python file
• PyCharm creates a new Python file and
opens it for editing.
Running Python (Using Command
line)
• Once you’re inside the
Python interpreter, type in
commands such as
>>>print (“Hello World”)
After this line, press Enter and
this command will print out
Hello World
Running Python (Using PyCharm)
• Use either of the following ways
to run your code:
• Right-click the editor and select
Run <file> from the context
menu .
• Press Ctrl+Shift+F10
• Since this Python script contains
a main function, you can click in
the gutter.
• You'll see the popup menu of the
available commands. Choose Run
<file>
Python Code Execution
• Python’s traditional runtime execution model: source code you type is
translated to byte code, which is then run by the Python Virtual
Machine. Your code is automatically compiled, but then it is
interpreted.
• Source code of python extension is .py
• Byte code extension is .pyc (compiled python code)
Indentation Matters
• Unlike many other languages, indentation is crucial in Python. It
defines code blocks instead of curly braces.
• Consistent indentation (usually 4 spaces) is essential for proper
program flow and to avoid errors.
Comments in Python
• Comments in Python are the lines in
the code that are ignored by the
interpreter during the execution of the
program.
• Also, Comments enhance the
readability of the code and help the
programmers to understand the code
very carefully.
• # Single line
• ‘’’ Multiline ‘’’
Keywords in Python
and False nonlocal
as finally not
Keywords in Python
assert for or
are reserved words
break from pass
that can not be used
class global raise
as a variable name,
continue if return
function name, or any
def import True
other identifier.
del is try
elif in while
else lambda with
except None yield
print Command
• print : Produces text output on the console.
• Syntax:
• print("Message“)
• print(Expression)
• Prints the given text message or expression value on the console, and moves the cursor down to the next line.
• print(Item1, Item2, ..., ItemN)
• Prints several messages and/or expressions on the same line.
• Elements separated by commas print with a space between them
• A comma at the end of the statement will not print a newline character
• Examples:
• print("Hello, world!“)
• age = 45
• print("You have", 65 - age, "years until retirement“)
Expressions
• expression: A data value or set of operations to • precedence: Order in which operations are computed.
compute a value.
/ % ** have a higher precedence than + -
• Examples: 1+4*3
42
1 + 3 * 4 is 13
• Arithmetic operators we will use:
+ addition
• Parentheses can be used to force a certain order of
- subtraction/negation
evaluation.
* multiplication
/ division
// floor division or integer division (1 + 3) * 4 is 16
% modulus, a.k.a. remainder
** exponentiation
Real Numbers or Floating Point
• Python can also manipulate real numbers.
• Examples: 6.022 -15.9997 42.0 2.143e17
• The operators + - * / % ** ( ) all work for real numbers.
• The / produces an exact answer: 15.0 / 2.0 is 7.5
• The same rules of precedence also apply to real numbers: Evaluate ( )
before * / % before + -
• When integers and reals are mixed, the result is a real number.
• Example: 1 / 2.0 is 0.5
• The conversion occurs on a per-operator basis.
What will be output of the following
• print(3+12) • print(1+2*3**2-4)
• print(12-3) • print(5/2)
• print(9+5%2-15+12) • print(5//2)
• print(4-3*2%3) • print(5//2.0)
• print(12/3)
• print(12.0/3.0)
• print(11.0/3.0)
Answers
• print(3+12) = 15 • print(1+2*3**2-4) = 15
• print(12-3) = 9 • print(5/2) = 2.5
• print(9+5%2-15+12) = 7 • print(5//2) = 2
• print(4-3*2%3) = 4 • print(5//2.0) = 2.0
• print(12/3) = 4.0
• print(12.0/3.0) = 4.0
• print(11.0/3.0) = 1.666667
Math Commands
• Python has useful commands (or called functions) for performing
calculations.
To use many of these commands, you
must write the following at the top of
your Python program:
from math import * or import math
from math import * vs import math
from math import *
This imports all the names from the math module
directly into your current namespace. You can then use
functions and constants from math without the math.
prefix. While this may seem convenient, it's generally
discouraged.
import math
Use import math for clear and safe access to functions
and constants from the math module. It promotes
explicit use of the math module, making code more
readable and maintainable. It helps prevent naming
conflicts by keeping the math module separate from
your local variables.
Relational expressions
• Relational expressions in Python are used for comparisons between values.
They evaluate to a boolean value (True or False) based on the condition being
compared.
• Relational Operators:
• Python provides several relational operators to compare values:
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Examples
• print(2>3) False
• print(4!=3) True
• print(3>1) True
• print(5==4) False
• print(10<=11) True
Logical expressions
• Logical expressions in Python are used to combine conditions and
evaluate to True or False based on the overall logic. They are essential
for making decisions and controlling the flow of your program.
• Logical Operators:
• Python provides three primary logical operators:
• and Returns True only if both operands are True.
• or Returns True if at least one operand is True.
• not Reverses the logical value of an operand (True becomes False, False
becomes True).
Examples
Operator Precedence
• Python has a defined order of operations. Here's a simplified table
(highest to lowest precedence):
• Exponentiation ()**
• Multiplication (*) and Division (/), Floor Division (//) (evaluated left-to-right)
• Addition (+) and Subtraction (-) (evaluated left-to-right)
• Comparison Operators (==, !=, <, >, <=, >=)
• Logical Operators (not, and, or)
• Parentheses can be used to override the default precedence order.
Any expression within parentheses is evaluated first.
Variables
• Variable - A named piece of memory that can store a value. Variables don't require
explicit declaration of data type in most cases. You simply assign a value to a variable
name, and Python infers the type.
• Usage:
• Compute an expression's result,
• store that result into a variable,
• and use that variable later in the program.
• Assignment statement = Stores a value into a variable.
• Syntax: name = value
• Examples: x = 5 gpa = 3.14 name = “Juan Dela Cruz” isDigit = True
• A variable that has been given a value can be used in expressions. x + 4 is 9
Rules for Python variables
• A Python variable name must start with a letter or the underscore
character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ ).
• Variable in Python names are case-sensitive (name, Name, and NAME
are three different variables).
• The reserved words(keywords) in Python cannot be used to name the
variable in Python.
Example
# An integer assignment
age = 45
# A floating point Output
salary = 1456.8 45
1456.8
John
# A string
name = "John"
print(age)
print(salary)
print(name)
Data Types
• Data types are classifications for the kind of data a variable can hold. They determine the values a
variable can store and the operations that can be performed on those values. Note: Python is
dynamically typed. The data type of a variable is determined at runtime based on the assigned
value. This allows for flexibility but can sometimes lead to runtime errors if you assign an
incompatible type.
• Numeric Types:
• Integers (int): Represent whole numbers, positive, negative, or zero (e.g., -5, 0, 1024).
• Floats (float): Represent decimal numbers (e.g., 3.14, -9.25).
• Complex Numbers (complex): Represent numbers with a real and imaginary part (e.g., 3+5j,
where j represents the imaginary unit).
• Text Type:
• Strings (str): Represent sequences of characters enclosed in single or double quotes (e.g.,
"Hello, world!", 'This is a string').
Data Types
• Logical Type:
• Booleans (bool): Represent logical values, True or False.
• Collection Types:
• Lists (list): Ordered, mutable collections of elements enclosed in square brackets []
(e.g., [1, 2, "apple", 3.4]).
• Tuples (tuple): Ordered, immutable collections of elements enclosed in parentheses
() (e.g., (10, "hello", True)).
• Sets (set): Unordered collections of unique elements enclosed in curly braces {}
(e.g., {1, 2, "apple", 2}).
• Dictionaries (dict): Unordered collections of key-value pairs enclosed in curly braces
{}. Keys must be unique and immutable (e.g., {"name": "Alice", "age": 30}).
Choosing the Right Data Type
• Selecting the appropriate data type is crucial for efficient memory usage
and code clarity. Here are some general guidelines:
• Use integers for whole numbers (counting, indexing).
• Use floats for decimal numbers (calculations involving measurements, currency).
• Use strings for text data (names, addresses, user input).
• Use booleans for logical conditions (True/False statements).
• Use lists for ordered sequences of elements that may change.
• Use tuples for ordered sequences that shouldn't change after creation.
• Use sets for collections of unique elements where order doesn't matter.
• Use dictionaries for storing key-value pairs where efficient retrieval by key is
needed.
Example
• String “All is well”
• Integer 10
• Float 3.1416
• Boolean True
• List [“John”,”Paul”,”George”, “Ringo”]
Python can tell us about types using the type() function:
print(type(“National”)) Output: <class 'str'>
Casting
• Converting one data type into another is known as casting
input()
• input : Reads a number from user input.
• You can assign (store) the result of input into a variable.
• Example:
• age = input("How old are you? ")
• print "Your age is", age
• print "You have", 65 - age, "years until retirement"
Example
Example
This program will
compute the area of
circle with the
formula of Area = πr²
Strings
• String is a series or characters interpreted as text.
• Strings in python are surrounded by either single quotation marks, or
double quotation marks.
• You can display a string literal with the print() function
Strings Placeholders
• String placeholders serve as container for strings and numbers
• {}
•%
•F
Strings Placeholders {}
Strings Placeholders {}
Strings Placeholders %
The percent sign (%) placeholder
• The percent sign (%) in Python used to be the primary way to format strings, but it's
been largely replaced by f-strings (formatted string literals) introduced in Python 3.6.
However, understanding the older formatting method with % can be helpful in some
contexts.
• Formatting Characters with %:
• While f-strings are generally preferred, here's a breakdown of some common
formatting characters used with the modulo operator (%):
• %d: Used for integers (e.g., "%d" % 10 prints "10").
• %f: Used for floats (e.g., "%f" % 3.14159 prints a formatted float value).
• %s: Used for strings (e.g., "%s" % "Hello" prints "Hello").
• %c: Used for single characters (e.g., "%c" % 'A' prints "A").
• Modifiers: You can combine these characters with modifiers to control formatting details:
Modifiers
• - (left-align): Aligns the value to the left within the specified width
(e.g., "%-10d" % 5 prints "5 ").
• (space): Pads numbers with spaces on the left (e.g., "% 5d" % 3 prints
" 3").
• 0 (zero): Pads numbers with zeros on the left (e.g., "%05d" % 123
prints "00123").
• .<precision> (precision for floats): Specifies the number of decimal
places for floats left (e.g., "% .2f" % 12.3234 prints “12.32").
Example
Strings Placeholders F String and {}
Strings Placeholders F String and {}
Example
String Formatting Functions
• upper() - Converts a string into upper case
• lower() - Converts a string into lower case
String Formatting Functions
• capitalize() - Converts the first character to uppercase
• title() - Converts the first character of each word to uppercase
String Formatting Functions
• split() - Splits the string at the specified separator, and returns a list
String Formatting Functions
• replace() - replaces a specified phrase/character with another
specified phrase/character
String Formatting Functions
• len() - Count characters in a string or number of items in an object
NUMBER Formatting Functions
• Number data types store numeric values. They are immutable data
types, means that changing the value of a number data type results
in a newly allocated object.
• round() - this function returns a floating point number that is a
rounded version of the specified number, with the specified number
of decimals.
NUMBER Formatting Functions
• ceil() - this method rounds a number UP to the nearest integer
• floor() - this method rounds a number DOWN to the nearest integer
NUMBER Formatting Functions
• pow() - The pow(x, y) function returns the value of x to the power of
y (x ).
PROBLEM SET 1
• Create a simple python program that will allow the user to enter Item Name,
Quantity, and Unit Cost.
• Display the Total Cost of the item using String Placeholder format of your choice.
PROBLEM SET 2
• Create a simple python program that will allow the user to enter his/her First
Name, Last Name, and his/her Current Age, respectively.
• Then display a greeting concatenated with his/her First Name and Last Name.
• Lastly, display his/her age 10 years from now concatenated with "Your age 10
years from now is "
PROBLEM SET 3
• Create a simple python program that declare variables for three different data
types:
• A string variable to store your favorite food.
• An integer variable to store your lucky number.
• A boolean variable set to True if you prefer cats or False for dogs (or any two
categories).
• Print the values of each variable with a descriptive label (e.g., "Favorite Food:
[food name]").
PROBLEM SET 4
• Create a simple python program that ask the user for a distance value (float) and
a unit (string, e.g., "miles" or "kilometers").
• Convert the distance to the other unit (1 mile = 1.609 kilometers).
• Print the converted distance with the appropriate unit label (e.g., "[original
distance] miles is equal to [converted distance] kilometers").
PROBLEM SET 5
• Create a simple python program that takes a user's weight in kilograms and
converts it to pounds. Store the converted weight in a variable named
"weight_in_pounds" and print it.
PROBLEM SET 6
• Create a simple python program that ask the user to takes three test scores as
input from the user and calculates their average. Store the average in a variable
named "average_score" and print it.
PROBLEM SET 7
• Create a simple python program that ask the user for the cost of a meal (float)
and the sales tax percentage (float).
• Calculate the amount of sales tax by multiplying the meal cost by the tax
percentage.
• Calculate the total bill amount by adding the meal cost and the sales tax.
• Print a formatted output showing the meal cost, sales tax amount, and total bill
amount with appropriate labels and currency symbols.
PROBLEM SET 8
• Create a simple python program that ask the user to input a number and
calculates the sum of all its digits. Store the result in a variable named
"total_sum" and print it.
PROBLEM SET9
• Create a simple python program that accepts Student Name, School Name, and
GWA.
• Display the student name in all Upper Case, concatenated with a greeting.
• Count and display the number of characters of his/her school name.
• Lastly, display his/her rounded UP GWA
THANK YOU
77