[go: up one dir, main page]

0% found this document useful (0 votes)
15 views142 pages

Python DSC551 (Auto-Saved) (Auto-Saved)

The document serves as an introductory guide to Python programming for data science, covering fundamental topics such as variables, data types, input/output operations, selection statements, loops, functions, and object-oriented programming. It highlights Python's versatility and popularity in various fields, including web development and machine learning. Additionally, it provides examples and syntax for basic operations and data structures like lists, dictionaries, and tuples.

Uploaded by

2024963861
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views142 pages

Python DSC551 (Auto-Saved) (Auto-Saved)

The document serves as an introductory guide to Python programming for data science, covering fundamental topics such as variables, data types, input/output operations, selection statements, loops, functions, and object-oriented programming. It highlights Python's versatility and popularity in various fields, including web development and machine learning. Additionally, it provides examples and syntax for basic operations and data structures like lists, dictionaries, and tuples.

Uploaded by

2024963861
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 142

Getting

Started With
Python
Programming For Data
Science (DSC551)

Universiti Teknologi MARA (UiTM)


Cawangan Negeri Sembilan
Topics
Introduction to Python Variables and Data Types in
Programming Language Python

Input and Output Operations Selection Statements

Loops Statements Functions

Object-Oriented
Programming
Introduction To Python Programming Languages
• Python has found numerous applications in various industries,
including:
• Web Development
• Data Analysis and Visualization
• Machine Learning and Artificial Intelligence:
• Scripting and Automation
• Game Development
Introduction To Python Programming Languages
• Python is a versatile and powerful programming language .
• Popular language
• Code readability and simplicity
• Excellent choice for both beginners and experienced developers.
Introduction To Python Programming Languages
• List of the five most popular and best programming languages
that will be in demand in 2023:
1. Javascript
2. Python
3. Go
4. Java
5. Kotlin
Introduction To Python Programming Languages
• Examples of games developed using Python
Introduction To Python Programming Languages
• Examples of apps developed using Python
Introduction To Python Programming Languages
• Pyhton vs Java
Python
score = int(input("Enter the score: "))

Java
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the score: "); int
score = scanner.nextInt();
Introduction To Python Programming Languages
• Comment is python precedes by the hash symbol (#)

• Example
#This program receives two numbers as input

n1 = int(input('Enter the first number : ')


n2 = int(input('Enter the second number : ')
sum = n1 + n2 # compute the sum
Introduction To Python Programming Languages
Introduction To Python Programming Languages
Introduction To Python Programming Languages
Topics
Variables and Data Types in
Introduction to Python
Python and Arithmetic
Programming Language
Operations

Input and Output Operations Selection Statements

Loops Statements Functions

Object-Oriented
Programming
Variables and Data Types

Basic Data Type Container


• Integer • List
• Float • Tuple
• Boolean • Dictionaries
• String
Variables and Data Types
• No variable declarations statement but it must be initialized or assigned with specific.

• Everything in Python is object


• Dynamic type of data for each variable

n = 5 n = 5 5
n = 7
n
n 5 7
Arithmetic Operations
• Python has numerous operators that can be used to perform mathematical calculations
as shown in the following table:
Symbol Operation Description

+ Addition Add two numbers

- Subtraction Subtract one number from another

* Multiplication Multiplies one number by another

/ Division Divides one number by another and gives the result as a floating-
point number
// Integer Division Divides one number by another and gives the result as an integer

% Remainder Divides one number by another and gives the remaining

** Exponent Raises a number to a power


Variables and Data Types : String
• Most common types of data processed by Python are string and numbers

• String literals in python are enclosed either by single quote ('String’) or double quotes
(“String”).
• String declaration:

place = ‘Danau Koalin’

0 1 2 3 4 5 6 7 8 9 10 11
‘D’ ‘a’ ‘n’ ‘a’ ‘u’ ‘ ‘ ‘K’ ‘a’ ‘o’ ‘l’ ‘i’ ‘n’
Variables and Data Types : String
• String functions
Methods Example Description

len len(str) Count the length of a string

upper str1.upper() Uppercases every alphabetical character

lower str1.lower() lowercases every alphabetical character

count str1.count('x') or Count the number of non-overlapping occurrences pf the


str1.count('th') substring
capitalize 'coDe'.capitalize Capitalizes the first letter and lowercases the rest

title 'ben huR'.title() Capitalizes the first letter of each word and lowercases the
rest
rstrip 'ab ‘.rstrip() Remove spaces from the right side of the string
Variables and Data Types : List

• A list is a sequence of data values called items or elements.


• An item can be any type of data.
• A list is written as a sequence of data values separated by commas and enclosed in square
brackets([ and ]).
• Examples of list declarations:
place = [‘Besut’, ‘Dungun’, ‘Kemaman’]
number = [5,6,7,8]
student = [[‘Aina’, ‘1234’, 3.99], [‘Ahmad’, ‘1235’, 3.45]]
Variables and Data Types : List
• Given the following list declaration:
number = [34,56,87,25,1,689]

• Each element in the list has a unique index starting from 0 the length - 1 as per illustrated the
following figure:
Variables and Data Types : List
• Creating a list using range keyword:

series = list(range(1,5))

[0] [1] [2] [3]


1 2 3 4
series
Variables and Data Types : List
• A list may contain item from various type of data as follows:
student = ['Abdullah', 1.65, 65]

[0] [1] [2]


‘Abdullah’ 1.65 65
student
Variables and Data Types : List

• Slicing the list

Slice Notation Meaning


newList = list[m:n] List consisting of the items of list having
n-1 indices m through n - 1
newlist = list[:] A new list containing the same items in list
newlist = list[m:] List consisting of the items of list from list[m]
through the end of the list
newlist = list[:m] List consisting of the items of list from
beginning to the element having index m-1.
Variables and Data Types : List

• Split method
message = "Welcome to Bukit Keluang Beach Resort"
word = message.split(" ")
print(word)

output:
['Welcome', 'to', 'Bukit', 'Keluang', 'Beach', 'Resort']
Variables and Data Types : List

• Join method
greet = " ".join(word)
print(greet)

output:

'Welcome to Bukit Keluang Beach Resort'


Variables and Data Types : List

• Copying the Lists list1 ‘a’ ‘b’


list2

Correct Method
Variables and Data Types : List

• Sorting the list


Variables and Data Types : List

The following examples demonstrate the use


several functions to manipulate the list
Variables and Data Types : List
Variables and Data Types : List
Variables and Data Types : List
adding
Variables and Data Types : List
Variables and Data Types : List
Variables and Data Types : List

o l 2

1 2 3
Variables and Data Types : List
Variables and Data Types : List

0 1 2 3 4

(remove)

- 68
Variables and Data Types : List
Variables and Data Types : List

column
r
o
w
Variables and Data Types : List

[row] (column] ??
show

43000
-
0
O
Mambay 20000
I Rantay 18000
Variables and Data Types : List 2 Remban 45000

0 1 2

O 1 2

- row
without position 1

it (20000) 118000) 1215000)


Variables and Data Types : List

o 1 2

0
2
Variables and Data Types : List

- position

0
2

0 l Z
Variables and Data Types : List
Variables and Data Types : Dictionary
• A dictionary is an object that stores a collection of data.

• Each element in a dictionary has two parts:


A key
A value

• A key is used to locate a specific value

• Examples:
To store information about employee’s id and employee’s name or person’s name and person’s phone
number.
permanent data
Variables and Data Types : Tuples

• Tuples are ordered sequence of items


• The tuples cannot be modified directly such as delete
the item in tuple, adding the new element or update
existing element.
• However we can slice, concatenate and repeats
existing tuple into new tuple.
Variables and Data Types : Tuples

• Examples of tuple declarations:


Example 1:

Example 2:
Variables and Data Types : Dictionary
name Phone number
Abu Bakar 019-4533454
Umar 014-3234345
Uthman 012-334545
Ali 012-3345456

phonebook = {'Abu Bakar':'019-4533454', 'Umar':'014-


3234345','Uthman':'012-334545','Ali':'012-3345456'}
Variables and Data Types : Dictionary

Retrieving a Value from a Dictionary


Syntax:
dictionary_name[key]

Examples:
Variables and Data Types : Dictionary

O
Using the in and not in Operators
• in and not in operators can be used to test the value in a dictionary.

in Operator not in Operator


Variables and Data Types : Dictionary
Adding Elements to an Existing Dictionary
• Dictionary are mutable object. So, you can add new elements to an existing dictionary using
the following syntax:

dictionary[key] = value
• Examples:
Variables and Data Types : Dictionary
Deleting Elements
• Syntax

del dictionary[key]

• Examples:
Variables and Data Types : Dictionary
Getting the number of elements in a Dictionary
• Syntax

len(dictionary)
• Examples:
Variables and Data Types : Dictionary
List as a data Types in a Dictionary
• Example:

Name Test 1 Test 2


Sophie 45 78
Luis 89 34
Ethan 90 23
Variables and Data Types : Dictionary
Mixing Data Types in a Dictionary
• The value in a dictionary can be objects of any type, but the keys must be immutable objects.

• Example:
Value Value Value

Key Key Key


Variables and Data Types : Dictionary
Creating an Empty Dictionary
• Syntax:

dictionary_name = {}

• Example:
students = {}
Variables and Data Types : Dictionary
Using loops to Iterate over a Dictionary
• You can use the for loop in the following general format to iterate over all the keys in a dictionary:
ikat data
for var in dictionary:
statement_1
statement_2
..
statement_n
Variables and Data Types : Dictionary
Using loops to Iterate over a Dictionary
• Example:
Variables and Data Types : Dictionary
Example of Using loops to Iterate over a Dictionary

This loop iterates once for each element of the phonebook This loop iterates once for each element of the phonebook
dictionary. Each time the loop iterates, the key is assigned to dictionary. Each time the loop iterates, the key is assigned
the variable. The print() function is called to print the value the key variable. The print() function is called to print the
of the key variable. value of the key variable and its associated value.


Variables and Data Types : Dictionary
• There are several methods can be applied to a dictionary. The following list shows some useful
methods.
Method Description

clear Clears the contents of a dictionary

get Gets the value associated with a specified key. If the key is not found, the method does not
raise an exception. Instead, it returns a default value.

items Returns all the keys in a dictionary and their associated values as a sequence of tuples

keys Returns all the keys in a dictionary as s sequence of tuples

pop Returns all the values associated with specified key and removes that key-value pair from
the dictionary. If the key is not found, the method returns a default value.

popitem Returns a randomly selected key-value pair as a tuple from the dictionary and removes that
key-value pair from the dictionary.

values Returns all the values in the dictionary as a sequence of tuples.


Some Dictionary Methods
• clear
Some Dictionary Methods
• get
Some Dictionary Methods
• items
Some Dictionary Methods
• keys
Some Dictionary Methods
• pop - to remove certain element from Dic
Some Dictionary Methods
to the list
- remove last item added
• popitem
Some Dictionary Methods
• values - to print belong to die
Topics
Introduction to Python Variables and Data Types in
Programming Language Python

Input and Output Operations Selection Statements

Loops Statements Functions

Object-Oriented
Programming
Input and Output Operations
• Print function

• General Syntax:
print(output1, output2, … outputN)

• Examples:
print('The sum is : ', sum)
Input and Output Operations
• Input function
• Syntax:
variable = input('Prompt message : ')

• Examples
var = input('Enter an input : ')
amount = float(input('Enter an fee RM:'))
score = float(input('Enter the score :'))
Topics
Introduction to Python Variables and Data Types in
Programming Language Python

Input and Output Operations Selection Statements

Loops Statements Functions

Object-Oriented
Programming
Decision Structure

Selection statement allow a program


to decide on a course of actions based
of whether a certain condition is true
of% false.
Decision Structure

Types of selection statement:


• if
else if
• If..else
• If..elif..if
• Nested Selection
Decision Structure : if-else statement

if condition:
indented block of statements
else:
indented block of statements
Decision Structure : if-else statement
Decision Structure : Nested if statement

if condition:
if condition:
indented block of statements
else:
indented block of statements
else:
if condition:
indented block of statements
else:
indented block of statements
Decision Structure : Nested if statement
Decision Structure : elif clause

if condition1:
indented block of statements if condition1 is True

elif condition2:
indented block of statements if condition2 is True

elif condition3:

indented block of statements if condition2 is True

else:
indented block of statements if non of the above

conditions are true


Decision Structure : elif clause
Decision Structure : Examples
Decision Structure : Examples
Topics
Introduction to Python Variables and Data Types in
Programming Language Python

Input and Output Operations Selection Statements

Loops Statements Functions

Packages
14/4/2025- Monday

Repetition Structure : for statement

• Syntax:
for var in sequence:
indented block of statements
Repetition Structure : for statement
Repetition Structure : for statement

•Looping through an arithmetic


progression

for num in range(m,n):


indented block of statements
Repetition Structure : for statement

• Looping through an arithmetic progression


Repetition Structure : for statement
•Example:
• This program print a series of square and cube of number 1
to 10.
Repetition Structure : for statement

•Step values for the range

for num in range(m,n,s)


indented block of statements
Repetition Structure : for statement

•Step values for the range


Repetition Structure : for statement

•Looping through string


Repetition Structure : for statement

•Looping through list or tuple

for item in listORtuple:


indented block of statements
Repetition Structure : for statement

•Looping through list or tuple


Repetition Structure : for statement

• Looping through the lines of a text file

infile = open(“filename.txt”,’r’)
for line in infile:
indented block of statements
infile.close()
Repetition Structure : for statement

•Looping through the lines of a text


file
Repetition Structure : for statement
• Populating a list with the content of a text file

dataList = []
infile = open(“Data.txt”, ‘r’)
for line in infile:
datalist.append(line.strip())
infile.close()
Repetition Structure : while statement
While Statement

General format:
Conditio False
n
while condition:
statement
True
statement
statement Statement(s)
Repetition Structure : while statement
While Statement count  0

General format:
False
count < 5
count = 0
while count < 5: True
print(‘Hello World’) Print
count = count + 1 ‘Hello World’

Add 1 to count
Topics
Introduction to Python Variables and Data Types in
Programming Language Python

Input and Output Operations Selection Statements

Loops Statements Functions

Packages
18/4/2025

What is a function?
• A group of statements that exists within a program for the purpose of performing a specific
task.

• A long program is broken into several small manageable parts.


• Benefits of modularizing a program with functions
1. Simple code
2. Code reuse
3. Better Testing
4. Faster Development
5. Easier Facilitation of Teamwork
What is a function?
statement
statement
statement def function():
statement statement
statement statement
statement statement
statement
statement
statement def function():
This program is statement
one long,
statement
statement
In this program the task has
statement
statement been divided into smaller task,
complex statement

sequence of
statement Modularise each of which is performed by a
statement
statements statement
def function(): Separate function.
statement
statement
statement
statement
statement
statement
Statement
statement def function():
statement statement
statement statement
statement statement
statement
Defining and calling a function
• The code for a function is known as a function definition.

• Function call is a statement to execute the function.

Function Definition Function Call

Example:
Defining and Calling a function

2
The interpreter jumps to 4
the message() function and
begins executing the When the message()
statements in its block. function ends, the
interpreter jumps back to
the part of the program
that called it and resumes
3 execution from that points

1
The interpreter jumps to
the main() function and When the main() function
begins executing the ends, the interpreter
statements in its block. jumps back to the part of
the program that called it.
If there is no statements,
the program will end
Local Variables
• A local variable is created inside a function and cannot be accessed by the statement that
are outside the function.

• Different function can have local variables with the same names because the function cannot
see each other’s local variables.

• A variable’s scope is the part of a program in which the variable may be accessed.

• A variable is visible only to statements in the variable’s scope.


• A local variable’s scope is the function in which the variable is created.
Local Variables

texas()

birds 5000
local (
var.
california()

birds 8000
Passing Arguments to Functions
• An argument is any piece of data that is passed into a function when the function is called.

• A parameter is a variable that receives an arguments that is passed into a function.


• All statements inside the function can access the parameter variable, but no statement
outside the function can access it.
main()
Passing Arguments to Functions
value 5

number
5

result 10

show_double()

10
screen
The sum of 12 and 45 is 57
The sum of 12 and 45 is 57

Passing Multiple Arguments to Functions


main()

12 45

num1 num2
12 45
result 57

show_sum()

The sum of 12 and 45 is 57

screen
Keyword Arguments
• Python allows you to write an argument in the following format:

parameter_name = value
main()

34 50

num1 num2
34 50
result 84

show_sum()
• Write a function called computeSum() that receive two integers as parameter, and this
function will compute and display the sum of these numbers.

• Create a main function that declares the following variables:


num1 = 50

num2 = 80

The main function will call computeSum() function and sent num1 and num2 as arguments.
Global Variables
my_value
• A global variable is accessible to all function in a program file.
34

show_value()

print (my_value)

34
screen

*Avoid using global variables whenever possible


Global Constant
• A global constant is a global that references a value that cannot be changed.

• Python does not allow you to create true global constants, but you can simulate them with
global variable.
• Usually, global constant is declared using capital letter as follows:

GST_RATE = 0.05
Question
VALUE RETURNING FUNCTION
• A value returning function is a function that returns a value back to the part of the program
that called it.
VALUE RETURNING FUNCTION
Topics
Introduction to Python Variables and Data Types in
Programming Language Python

Input and Output Operations Selection Statements

Loops Statements Functions

Object-Oriented
Programming
2/5/2025

Writing Text to a file


Writing number to a file
Reading Numbers from a file
Some Files Operations
METHOD PURPOSE
open(pathname, mode) Opens a file at the given pathname and returns a file object.
The mode can be 'r', 'w', 'rw' or 'a'.
The last two values, 'rw’ and 'a', mean rea/write and append,
respectively.
f.close() Closes an output file. Not needed for input files.
f.write(aString) Output aString to a file.
f.read() Inputs the contents of a file and returns them as a single string.
Return '' if the end of the file is reached.
f.readline() Inputs a line of text and returns it as a string, including the newline.
Return '' if the end of the file is reached.
Object-Oriented Programming
• After completing this chapter, you will be able to:
1. Determine the attributes and behavior of a class of objects required by a program.
2. List the methods, including their parameters and returns types, that realize the behavior of a class of
objects
3. Choose the appropriate data structures to represents the attributes of a class of objects
4. Define a constructor, instance variables, and methods for a class objects
5. Recognize the need for a class variable and define it
6. Define a method that returns the string representation of an object
Design With Classes
• A first example: The Student Class
29/4/2025- Tuesday

JSON
• JSON (JavaScript Object Notation) is a lightweight data interchange
format that is easy for humans to read and write, and easy for
machines to parse and generate.
• Primarily used to transmit data between a server and a web
application as an alternative to XML.
• JSON structures data in key-value pairs, making it a popular choice for
APIs and configuration files.
JSON
• In Python, JSON is supported natively through the json module, which
provides functions to work with JSON data.
• This allows Python developers to easily convert Python objects (like
dictionaries and lists) to JSON format and vice versa.
• The process of converting a Python object into JSON is known
as serialization, while converting JSON back into a Python object is
called deserialization.
JSON
• Serialization: This is the process of converting a Python object
(typically a dictionary) into a JSON-formatted string.
• For example, a Python dictionary can be transformed into a JSON
string that can be easily stored or transmitted
• In Python, this can be done using the json.dumps() function,
which takes a Python object and returns a JSON string.
JSON
• Deserialization: This is the reverse process, where a JSON-
formatted string is converted back into a Python object.
• This can be accomplished using the json.loads() function, which
takes a JSON string and returns the corresponding Python object
JSON
• In summary, JSON serves as a bridge for data exchange between
different programming environments, and Python's built-in
capabilities for serialization and deserialization make it
straightforward to work with JSON data.
JSON (Example 1: Simple Object)
JSON (Example 2: Array of Objects)
JSON (Example 3: Nested Objects)
JSON (Example 1: Serializing a Simple Dictionary)
convert Python object into seen data

JSON (Example 2: Serializing a List)


JSON (Example 3: Serializing a Nested Dictionary)
JSON (Example 4: Serializing Custom Objects)
JSON (Example 5: Serializing with Indentation)
You can also format the JSON output for better readability by using the indent parameter.
JSON (Example 6: Serializing with Indentation and
writing to a file)
Ssm i no pytron object
convert

JSON (Example 1: Deserializing a Simple JSON Object)


JSON (Example 2: Deserializing a JSON Array)
JSON (Example 3: Deserializing Nested JSON Objects)

type (data)
JSON (Example 4: Deserializing JSON with Mixed Data Types)
JSON (Example 5: Deserializing JSON into Custom Objects)
Packages : matplotlib
• Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in
Python. Matplotlib makes easy things easy and hard things possible.

• Create publication quality plots.


• Make interactive figures that can zoom, pan, update.

• Customize visual style and layout.

• Export to many file formats.

• Embed in JupyterLab and Graphical User Interfaces.

• Use a rich array of third-party packages built on Matplotlib.


Design With Classes
• Programmers who use objects and classes know several
things:
1. The interface or set of methods that can be used with a class of
objects.
2. The attributes of an object that describe its state from the user’s
point of view
3. How to instantiate a class to obtain an object
Design With Classes
• A class definition is act as a blue print for each of the object
of that class. This blueprint contains the following items:
1. Definitions of all of the methods that its object recognize
2. Description of the data strrc

You might also like