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

Week1 2

This document outlines a course on computer programming for sciences using Python. It discusses computational thinking, problem solving, algorithms, data types and structures in Python. It also covers scientific applications of Python in areas like chemistry, physics, geoscience and more.

Uploaded by

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

Week1 2

This document outlines a course on computer programming for sciences using Python. It discusses computational thinking, problem solving, algorithms, data types and structures in Python. It also covers scientific applications of Python in areas like chemistry, physics, geoscience and more.

Uploaded by

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

WELCOME

SIC1006
Computer Programming for the Sciences

Pengaturcaraan Komputer untuk Sains


Part 1 (Core Python Language)

Dr. Tang Wai Kit, Alfred

wktang.um.edu.my
1
Outlines

➢ Introduction to Python and Computer Programming

➢ Data Types, Variables, Basic Input-Output Operations, Basic Operators

➢ Boolean Values, Conditional Execution, Loops, Lists and List Processing, Logical and Bitwise
Operations

➢ Functions, Tuples, Dictionaries, and Data Processing

➢ String and List Methods, Exceptions and Working with Files

➢ The Object-Oriented Approach: Classes, Methods, Objects, and the Standard Objective Features;
Exception Handling, and Modules, Packages

➢ Scientific Programming in Python


Assessments:

• 40%
• Assignment (10% +10%), Quiz (10%) and MicroPython project (10%)

• 60% Final Exam


Computation ??
Concepts /
Data structures
Knowledges Iteration, recursion
Abstraction, etc

How to computation ??
Programming
Skill Organize, modularize,
Classes of algorithm (library)

Apply computation
Solve scientific Design your Python codes
problem that suit your needs

5
What is Computation?
• Data management
• Analysis
• Visualization
• Statistics
• web development

Calculation Output
You Computer Physical Results

Human interaction with computer

6
Human & Computer

How Human and


Computer understand
each other ?????

Computational
thinking
You Computer Calculation Output
Physical Results
Computational language
• Bridge between human and computer
• Compiler – c++, fortran, python

• Source code compiler executable program


(human) (computer)
Why we need computation ?
Computational chemistry
• use computer to study reaction, spectroscopy

Computer You Physical Computational physics


• Material development -> solar panel
Science Science
Computational biology
• Bioinformatios ->understand biological systems
and relationships

Weather forecast
Applied • Numerical weather prediction (mathematic model)
Mathematics
Computational Geoscience
• seismology and seismic hazards
• Underground activity
Human Limitation
Problem solved efficiently – Chemistry, Physics, Geoscience, Management, more!!

NOT limited to science ONLY


Behavior of user, stock market prediction, data visualization

WHY ?!!?!?!

• Too much number to remember !!

• Too much arithmetic to handle !!


Computation Mechanism
Memory

CPU

Processor
Input Control Unit Logic Unit Output
Arithmetic

Source code compiler executable program


The power of computation
• Calculations faster (billion calculations per second!!)
• Can remember many numbers (gigabytes of storage)
Programming Language

Computer

Source code executable program


Python Computation

Why ??
• Easy productivity & efficiency ▪ Social media networking

• Visualization ‒ Web / mobile development ▪ Entertainment

• Statistics Data analysis ▪ Search engine

▪ Cloud service
• machine learning / AI customer favorite
Python in Science (Analysis & Visualization)

• Water structure analysis


• Seismic analysis & prediction
• Chemical state characterization
Computational Thinking

“Computational thinking is the thought processes involved

in formulating a problem and expressing its solution(s) in

such a way that a computer (machine) can effectively carry

out” – Wing 2014


How Human and
Computer understand
each other ?????

Computational
You thinking Computer Calculation
Output
Computation Fundamental
• Computational thinking (Behavior or thinking before programming)
➢ Logical thinking

➢ Algorithmic thinking
➢ Sequence of clearly defined steps to describe a process with start and end points

➢ Decomposition
➢ Characterize the problem
➢ Break the complex problem into simpler parts
Computation Fundamental
• Computational thinking (Behavior or thinking before programming)
➢ Pattern generalization
➢ Look for pattern (things repeat)

➢ Abstraction
➢ Simplify the code from large dataset
➢ Reduce complexity and increase efficiency
Problem to Problem
How to convert the chemical problem to computational problem??
Chemical / Geoscience

Develop a computational thinking


is a must !!!
Mathematic description

▪ quantum chemistry
Computational problem ▪ iSALE hydrocode
▪ multi-phase computational fluid dynamics

solution
Chemical / Geoscience
How to Computational ??
Mathematics into computational
√50 = ?? √50 = ?? √50 = ??

algorithm

7.071067811 7.071067811
19
Computational Thinking

Computational problem / interest


➢ Mathematics
Computational
b b*b a/b (b+a/b)/2
thinking !!
3 9 16/3 4.17 Computer
4.17 17.36 3.837 4.0035

Your problem / interest 4.0035 16.0277 3.997 4.00002


➢ Finding square root of a
number (math)
coding

√a = b
ancient Babylon √150 = ? Your problem solved !!
• Find any root of a number at
17th century BC !! guess b = 10 any guess from user
How to Computational ??
Algorithm

Declarative knowledge √a = b
• Statement of facts b2 = a

Imperative knowledge Finding square root – approximation


• Objective
assume a=16, b=3
• A series of operation/steps
b b*b a/b (b+a/b)/2
• Flow or control
3 9 16/3 4.17
• Determine to stop / re-do 4.17 17.36 3.837 4.0035
• Objective done / solved 4.0035 16.0277 3.997 4.00002
Mathematics into computational
• Physics into computational – computational physics

• Chemistry into computational – computational chemistry

• Biology into computational – computational biology & bioinformatics

• Computational Geosciences

22
Computational Problem
Computational problem / interest
➢ Physics
➢ Chemistry
➢ Mathematics
➢ Management Computer
Computational ➢ Customer (selection)
thinking !! ➢ Game

Your problem / interest convert


➢ Physics Your problem solved !!
➢ Chemistry • Data analysis
➢ Mathematics • Chemical mechanism
➢ Management • Dynamic collapse model
➢ Customer (selection) • Impact simulation
➢ Game
• Data visualization

Convert your problem into computer task and let the computer calculate for you !!
Python Programming
Object
Class
• Program manipulate class, object (element of a class)
Blueprint of object

• Class
• declare and create objects object
• group of similar objects (classify or a group)
• No memory allocation
• Example: car

• Object
• physical entity; attributes, method
• Allocated with memory
• Access data members and functions of the class
• Example: myvi, persona, BMW, Vios, honda city
• float, int

• Scalar or non-scalar Ignore this at the moment if


you don’t understand
Data Type
Data type Description Value stored

int integers 1, 3, 5
float floating point (decimal) 3.142
complex real and imaginary 2.3 + 5j
bool Booleans True or False
str Strings - character, name “hello” ‘python’
list Lists - ordered sequence of objects [33.3, ”abc”, 10, 10]
dict dictionaries – key:value pairs {“key1”:”value1”, “name”:”Alfred”}
tup tuples - ordered (immutable) sequence (33.3, ”abc”, 10, 10)
set set – unorder collection of unique object {“33.3, ”abc”, 10}
Mechanical Problem Clothes Problem Surgery Problem

Different Concept and different rules to use it

Mechanic Tool – Data Type A Sewing Tool – Data Type B Surgery Tool – Data Type C
Different function in each Different function in each Different function in each
Attendance Math Calculation Electronic Circuit

Intensive data handling, Arithmetic operation, +, Flow control,


formatting, revising -x/ conditional execution
Numbering

Data Type Data Type Data Type


str, list int, float, complex bool, int, float
… … …
Data Type
Data Type - Number
number data type
➢ Integer (exact)
>>> int (7)
1, 100, 50, 68
7
>>> 0.0001
➢ Floating point (not exact)
0.0001
0.235879, 3.142
>>> int (3.142)
15 - 16 precision
3
➢ Complex number
Real and imaginary part >>>4/3
4+0.5j 1.3333333333333333

>>>print(format(4/3, ".30f"))
1.333333333333333259318465024990

default decimal is scientific tolerable


Data Type - Number
Check your number data type Number Conversion

>>> type (4.86) • Convert a object to another type


float
>>> int (3.2) “round down”
>>> type (50) 3
int
>>> float (9) “give decimal”
>>> type (3 +4j) 9.0
complex
>>> complex(3.)
(3+0j)

Not easy in some programming language


Variable Assignments
int (30528) located into memory address (RAM)

>>>id(30528)
1787924957680 specific of memory location

>>>30528+6
30534

>>>30528*2
91584
How many times you want to type 30528 ??!?!?!?!?
Variable Assignments
a = 30528

a can be reused/recall in the coding

Rules for variable names


• Cannot start with a number
• No space in the name
• Cannot use symbols
:”<>/?|\()!@#$%^&*~-+
• Best practice – lowercase
• Python reserved keywords
type list str int
Variable Assignments
Dynamic Typing
• Reassignment of the same variables
with different data types
• other language statically-typed

Pros
• Easy to work throughout coding
• Fast and flexible – replace/overwrite the same variable

Cos
• May cause bugs for unexpected data types
• Need to consistently check variable with type()
Data Type - Number
Check your number data type Number Conversion

>>> type (4.86) • Convert a object to another type


float
>>> int (3.2) “round down”
>>> type (50) 3
int
>>> float (9) “give decimal”
>>> type (3 +4j) 9.0
complex

LIFE IS MUCH EASIER !!


Input / Output
Input – Capture input from keyboard – input

Output – Print something to screen – print

Command ask python capture the user input from keyboard

Direct display the result after capture


NOT REALLY USEFUL !!

Assign into a variable, then you can use it in later !!

What is the data type of “a” here ??


Input / Output
Assign it into another variable so, it can become a int type

Remember, everything captured by input () function default in the form of string !!

print () – prints the user specified text (within the parenthesis) to the screen

print (object(s), sep=separator, end=end, file=file, flush=flush)

print (“Welcome to Python course”)

print (“Welcome to “,“Python course”)

print (“Welcome to “,“Python course”,sep=“@@@”)


Output display by syntax/command/order

???

Output given to you who working on the code ONLY


Detect separator “,” single space default

Detect separator “,” and replace with the desired character

Print variable

Something at behind of print () function

end allow continue execution


print () can have extra function in different version of python
Number formatting

syntax
print({format_field}.format(value))
Operator - Arithmetic >>>10/5
2.0
>>>10//5
• Create expressions (combinations of objects and binary operators) 2
• Expression return a value
• Syntax
• <operand> <operator> <operand> >>>50%3
2
a + b → sum + addition
a − b → subtraction − subtraction >>>5**2
a * b → multiplication * multiplication 25
a / b → division / division (return floating point)
a // b → division // division (return integer)
a % b → remainder % remainder
>>>10 * 3.1
a ** b → exponentiation ** exponentiation
31.0
Both are int, return in int type >>>10*3
Either of both are floating point, return in float type 30
Operator and Mathematical Function

Which operation go first ??


>>>18 / 3 / 2
3.0
() highest
>>> 18 / (3 / 2)
Without parentheses 12.0
** (highest precedence) >>>(3**2)**3 Equivalent to 9**3
*, /, //, % 729
+, − (lowest precedence)
>>>3**2**3 Equivalent to 3**8
6561
Equal precedence – left to right
Two mathematical functions provide by default

abs() return absolute value


round() return rounded number

>>>abs(-7.8) >>>round(-7.8) >>>int(-7.8)


7.8 -8 ??
>>>abs(5+12j)
13.0 “sqrt(5**2+12**2)” >>>round(4.5) >>>int(4.5)
Polymorphism !! 4 ??

int (parameters)
default in Python
float (parameters)

Not mathematical functions


+=
Compound Assignment Operator
-+ Syntax
variable += value
*=
Perform operation based on the arithmetic operator
/= and store the result of operation into the left operand

a += 10
//=
a = a + 10
**=
1. Carry out the addition
%=
2. Replace the value in a

44
Simple Module math
• Convenient – functionality -> modules/packages

• import modules (beginning of code)

• import math – ask python to import the math module and functionality inside

• How ?? -> math.attribute


math.sqrt(object)
• import math as sic1006
math.cos(object)

math.exp(object)

math.degree(object)

Text book -> Page 14

You might also like