You are on page 1of 51

Bài 1 - Lập trình căn bản với Python

Các khái niệm cơ bản về lập trình

TS. Đỗ Như Tài


Đại Học Kinh Tế TP.HCM
taidn@ueh.edu.vn
2

Nguyên tắc cơ bản về


máy tính
3

Nguyên tắc cơ bản về máy tính


1. Phần cứng và phần mềm
2. Phát triển chương trình
3. Môi trường lập trình
4

Phần cứng và phần mềm

Monitor
Houses processor,
and
memory, buses, etc.
speaker
(output)

 Set of instructions
Keyboard and to perform tasks to
mouse (input)
specifications
 Programs are
software

http://www.tutorialspoint.com/computer_fundamentals/computer_quick_guide.htm
5

Phần cứng và phần mềm

 (Computer) Program
 Sequence of instructions for a computer to
execute
 Programming languages
 Languages for writing programs
6

Các loại chương trình


 Machine code Program to which computer can respond
directly. Each instruction is a binary code
that corresponds to a native instruction.
Eg: 0001001101101110

 Assembly code Low-level language with strong (generally


one-to-one) correspondence between
assembly code and machine code
instructions.
Requires translation Eg: MIPS (add t1, t2, t3)

 High-level Detailed knowledge of the machine is not


required. High level of abstraction. Ease of
language program writing and understanding.
Eg: Java, C, C++, Python.
7

Biên dịch chương trình


 High-level language programs (eg: C) cannot be
executed directly by the computer
 Require a translation process called compilation
 A special program called compiler is used
 The original C program is called the source code
 The compiled program is the executable code or
machine code
 In general, executable codes generated on a certain
machine cannot be executed on another machine
with a different architecture
 The source code needs to be compiled on the new
machine
8

Chu trình chỉnh sửa, biên dịch và thực thi

Use a compiler
to translate the
Use an editor to
source code into
create/modify
the source code Edit Compile executable

Execute Execute/run the


executable code

Process is iterative
9

Chỉnh sửa mã nguồn C


 We use a text editor to create/modify this C
program first.c
#include <stdio.h>

int main(void) {
int a=27, b=6, c;

c = a%b;
printf("The value of c is %d.\n", c);

return 0;
}
10

Thực thi chương trình C


 We have gone through the Edit – Compile – Execute process
Source code
Edit produces
first.c
eg: vim first.c

Executable code
Compile produces
first.exe
eg: gcc first.c –o
%TEMP%\first.exe
Program output
Execute produces
eg: %TEMP%\first.exe The value of c is 3.
11

Ngôn ngữ thông dịch


• Interpreted
• Not compiled like Java/C++
• Code is written and then directly executed by an interpreter
• Type commands into interpreter and see immediate results

Java: Code Compiler


Runtime
Environment
Computer

Python: Code Interpreter Computer


12

So sánh các ngôn ngữ lập trình


• Tải các trình biên dịch và thông dịch của C++, Java, JavaScript và Python
• C++
• Kiểm tra: gõ lệnh where gcc (nếu chưa có thì cài Dev-C++)
• Search: Download Dev-C++  https://sourceforge.net/projects/orwelldevcpp/
• Đăng ký PATH: C:\Program Files (x86)\Dev-Cpp\MinGW64\bin
• Java
• Kiểm tra: gõ lệnh where javac (nếu chưa có thì cài jdk)
• Tải jdk: https://www.oracle.com/java/technologies/downloads/#jdk21-windows
• Đăng ký PATH: C:\Program Files\Java\jdk-21\bin
• Python:
• Kiểm tra Python: gõ lệnh where python (nếu chưa có cài python hoặc minianaconda)
• https://docs.conda.io/projects/miniconda/en/latest
• Đăng ký PATH:
C:\ProgramData\minianaconda3; C:\ProgramData\minianaconda3\Scripts
• JavaScript:
• Kiểm tra: where node
• Tải nodejs: https://nodejs.org/en/download/current (Window 64bits)
• Đăng ký PATH: C:\Program Files\nodejs
13

So sánh các ngôn ngữ lập trình


/* C: first.c ''' Python: first.py
gcc first.c -o %TEMP%\first.exe (compile) python first.py (interpret)
%TEMP%\first.exe (execute) */ '''
#include <stdio.h> if __name__ == "__main__":
a = 27
int main(void) { b = 6
int a=27, b=6, c;
c = a%b;
c = a%b; print("The value of c is %d.\n"% c)
printf("The value of c is %d.\n", c);

return 0; /* Java: First.java


} javac First.java (compile to bytecode)
java First (execute bytecode)
*/
/* JavaScript: first.js
import java.lang.*;
node first.js (interpret)
public class First {
*/
public static void main(String[] args) {
a = 27
int a = 27, b = 6, c;
b = 6
c = a % b;
c = a % b
System.out.println("The value of c is "+ c +".\n");
console.log("The value of c is "+ c +".\n");
}
}
14

So sánh các ngôn ngữ lập trình


// C++: helloworld.cpp # Python: helloworld.py
#include<stdio.h> if __name__ == "__main__":
int main() print("Hello, World");
{
printf("Hello, World!");
return 0; // Java: HelloWorld.java
import java.lang.*;
}
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
// JavaScript: helloworld.js }
console.log("Hello, World!"); }
15

Ngôn ngữ Python


• Created in 1991 by Guido van Rossum (now at Google)
• Named for Monty Python

• Useful as a scripting language


• script: A small program meant for one-time use
• Targeted towards small to medium sized projects

• Used by:
• Google, Yahoo!, Youtube
• Many Linux distributions
• Games and apps (e.g. Eve Online)
16

Cài đặt Python

Windows: Mac OS X:
• Download Python from • Python is already installed.
http://www.python.org • Open a terminal and run python or
• Install Python. run Idle from Finder.
• Run Idle from the Start Menu.

Linux:
• Chances are you already have Python
installed. To check, run python
from the terminal.
• If not, install from your distribution's
package system.
Note: For step by step installation instructions,
see the course web site.
17

Trình thông dịch Python


• Allows you to type commands one-at-a-time and see results
• A great way to explore Python's syntax
• Repeat previous command: Alt+P
18

Chương trình Python đầu tiên


• Python does not have a main method like Java
• The program's main code is just written directly in the file
• Python statements do not end with semicolons

hello.py
1 print("Hello, world!")
19

Câu lệnh print


print("text")
print() (a blank line)
• Escape sequences such as \" are the same as in Java
• Strings can also start/end with '

swallows.py
1 print("Hello, world!")
2 print()
3 print("Suppose two swallows \"carry\" it
4 together.")
print('African or "European" swallows?')
20

Ghi chú
• Syntax:
# comment text (one line)

swallows2.py
1 # Suzy Student, CSE 142, Fall 2097
2 # This program prints important messages.
3 print("Hello, world!")
4 print() # blank line
5 print("Suppose two swallows \"carry\" it
6 together.")
print('African or "European" swallows?')
21

Khai báo hàm


• Function: Equivalent to a static method in Java.
hello2.py
• Syntax:
def name(): 1 # Prints a helpful message.
statement
2 def hello():
3 print("Hello, world!")
statement 4
... 5 # main (calls hello twice)
statement 6 hello()
7 hello()

• Must be declared above the 'main' code


• Statements inside the function must be indented
22

Ý nghĩa của khoảng trắng


• Python uses indentation to indicate blocks, instead of {}
• Makes the code simpler and more readable
• In Java, indenting is optional. In Python, you must indent.

hello3.py
1 # Prints a helpful message.
2 def hello():
3 print("Hello, world!")
4 print("How are you?")
5
6 # main (calls hello twice)
7 hello()
8 hello()
23

Bài tập
• Rewrite the Figures lecture program in Python. Its output:
______
/ \
/ \
\ /
\______/
\ /
\______/
+--------+
______
/ \
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+
24

Bài giải

def egg(): def top():


top() print(" ______")
bottom() print(" / \\")
print() print("/ \\")
def cup():
bottom() def bottom():
line() print("\\ /")
print() print(" \\______/")

def stop(): def line():


top() print("+--------+")
print("| STOP |")
bottom() # main
print()
egg()
def hat(): cup()
top() stop()
line() hat()
print()
25

Algorithmic Problem
Solving
26

Algorithmic Problem Solving


1. Problem Solving Process
2. Algorithm
3. Control Structures
4. Examples of Pseudocodes
5. Euclid’s Algorithm
27

Quá trình giải quyết vấn đề​


Algorithmic
Determine
problem Analysis
features

Write algorithm
Iterative
Design process

Produce
code Implementation What is an
algorithm?
Check for
correctness and Testing
efficiency
28

Algorithm (1)
 An algorithm is a well-defined computational
procedure consisting of a set of instructions,
that takes some value or set of values as input,
and produces some value or set of values as
output.

Input Algorithm Output

‘Algorithm’ stems from ‘Algoritmi’, the Latin form of al-


Khwārizmī, a Persian mathematician, astronomer and geographer.
Source: http://en.wikipedia.org/wiki/Algorithm
29

Algorithm (2)
 An algorithm has these properties:
The algorithm
Each step must
must
be exact. (Or it will
not be precise.) terminate.
Exact Terminate (Or no solution will be
obtained.)

The
algorithm The algorithm
must be must be
Effective General
effective. general.
(i.e. it must solve the (Within the constraints of
problem.) the system/language.)
30

Algorithm (3)
 Ways of representing an algorithm:
Flowchart Pseudocode

lynda.com
31

Algorithm: Example #1
32

Algorithm: Example #2 (1)


 Find maximum and average of a list of numbers:
Terminator box
start
Flowchart
Process box
sum  count  0
max  0
Decision box

Yes end of
input?

No

Enter num
increment count
ave  sum/count sum  sum + num

print max, ave Yes


num > max? max  num

No
end
33

Algorithm: Example #2 (2)


 Find maximum and average of a list of numbers:
Pseudocode The need to initialise variables.
sum  count  0 // sum = sum of numbers
// count = how many numbers are entered?
max  0 // max to hold the largest value eventually
for each num entered,
count  count + 1
sum  sum + num
if num > max
then max  num The need to indent.
ave  sum / count

print max, ave

Are there any errors in this


algorithm?
34

Algorithm: Pseudocode
 We will write algorithms in pseudocode instead of
flowchart as the former is more succinct
 However, there are no standard rules on how
pseudocodes should look like
 General guidelines:
 Every step must be unambiguous, so that anybody is
able to hand trace the pseudocode and follow the
logic flow
 Use a combination of English (keep it succinct) and
commonly understood notations (such as  for
assignment in our previous example)
35

Control Structures (1/2)


 An algorithm is a set of instructions, which are
followed sequentially by default.
 However, sometimes we need to change the
default sequential flow.
 We study 3 control structures.
36

Control Structures (2/2)

Sequence • Default

True False
?
• Also called
Selection branching

False
Repetition • Also called loop
?

True
37

Data Representation
 Internal representation: bits (binary digits) 0 and 1
 1 byte = 8 bits
 In programming, we need variables to hold data. A
variable has an associated data type and occupies
memory space. In the following slides, variables are
shown as boxes.
 Some data types in Python
 Integers: int, short, long (int is most common)
 Real numbers: float, double
 Characters: char, string
38

Control Structures: Sequence (1)


 Task: Compute the average of three integers
A possible algorithm: Variables used:
enter values for num1, num2, num3 num1 num2 num3
ave  ( num1 + num2 + num3 ) / 3
print ave
ave

Another possible algorithm: Variables used:


num1 num2 num3
enter values for num1, num2, num3
total  ( num1 + num2 + num3 )
ave  total / 3 total
print ave
ave

Each box represents a variable.


Important concepts: Each variable has a
unique name and contains a value.
39

Control Structures: Sequence (2)


 Task: Compute the average of three integers
 How the program might look like
''' avg3num.py
Input Output
1 2 3 2
10 9 8 9 '''
num1 = float(input("Input num 1: "));
num2 = float(input("Input num 2: "));
num3 = float(input("Input num 3: "));
print("num1 = %.3f, num2 = %.3f, num3 = %.3f"%(num1, num2, num3));

avg = (num1 + num2 + num3) / 3.0


print("Average value is %.3f"%(avg));
40

Control Structures: Selection (1) True


?
False

 Task: Arrange two integers in ascending order (sort)


Algorithm A:
enter values for num1, num2
Variables
// Assign smaller number into final1,
used:
// and larger number into final2
if (num1 < num2) num2
num1
then final1  num1
final2  num2
final1 final2
else final1  num2
final2  num1
// Transfer values in final1, final2 back to num1, num2
num1  final1
num2  final2
// Display sorted integers
print num1, num2
41

Control Structures: Selection (2) True


?
False

 How the program might look like for Algorithm A


''' sort2num_va.py
Input Output
1 10 1 10
10 5 5 10
'''
num1 = float(input("Input num 1: "));
num2 = float(input("Input num 2: "));

if num1 < num2:


final1 = num1
final2 = num2
else:
final1 = num2
final2 = num1

num1 = final1
num2 = final2

print("num1 = %.3f, num2 = %.3f"%(num1, num2))


42

Control Structures: Selection (3) True


?
False

 Task: Arrange two integers in ascending order (sort)


Algorithm B:
enter values for num1, num2 Variables
// Swap the values in the variables if necessary used:
if (num2 < num1)
then temp  num1 num1 num2
num1  num2
num2  temp temp
// Display sorted integers
print num1, num2

Compare Algorithm A with Algorithm B.


43

Control Structures: Selection (4) True


?
False

 How the program might look like for Algorithm B


''' sort2num_vb.py
Input Output
1 10 1 10
10 5 5 10
'''
num1 = float(input("Input num 1: "));
num2 = float(input("Input num 2: "));

print("num1 = %.3f, num2 = %.3f"%(num1, num2))

# swap num1 num2


if num1 > num2:
temp = num1
num1 = num2
num2 = temp

print("num1 = %.3f, num2 = %.3f"%(num1, num2))


44

Control Structures: Repetition (1) False


?
True

 Task: Find sum of positive integers up to n (assume n>0)


Algorithm:
enter value for n
Variables
// Initialise a counter count to 1, and ans to 0
used:
count  1
ans  0
n
while (count <= n) do
ans  ans + count // add count to ans
count  count + 1 // increase count by 1 count

// Display answer
print ans ans

Initialisation is
very important!
45

Control Structures: Repetition (2) False


?
True

 Important to trace pseudocode to check its correctness


Algorithm: Assume user enters 3 for n.
enter value for n
(count <= n)? count ans
count  1
1 0
ans  0
while (count <= n) do true 2 1

ans  ans + count true 3 3

count  count + 1 true 4 6

// Display answer false

print ans
Output: 6
46

Control Structures: Repetition (3) False


?
True

 How the program might look like


''' sumn.py
+ Input: n = 4
+ Output: s = 1 + 2 + 3 + 4 = 10
'''
n = float(input("Input n: "));
count = 1
ans = 0
while count <= n:
ans = ans + count
count = count + 1

print("ans = %d"%(ans))
47

Euclid’s Algorithm (1)


 To compute the greatest common divisor
(GCD) of two integers
 First documented algorithm by Greek
mathematician Euclid in 300 B.C.
 Also known as Euclidean Algorithm
1. Let A and B be integers with A > B ≥ 0.
2. If B = 0, then the GCD is A and algorithm ends.
3. Otherwise, find q and r such that

A = q.B + r where 0 ≤ r < B


4. Replace A by B, and B by r. Go to step 2.
48

Euclid’s Algorithm (2)


 q is not important;
r is the one that matters.

 r could be obtained by A
modulo B (i.e. remainder of
A / B)

1. Let A and B be integers with A > B ≥ 0.  Assumption on A > B


2. If B = 0, then the GCD is A and algorithm ends. unnecessary
3. Otherwise, find q and r such that

A = q.B + r where 0 ≤ r < B  We will rewrite the algorithm

4. Replace A by B, and B by r. Go to step 2.


49

Euclid’s Algorithm (3)


 Euclid’s algorithm rewritten in modern form
// Assume A and B are non-negative
// integers, but not both zeroes. Let’s trace GCD(12, 42)
Algorithm GCD(A, B) { (B > 0)? r A B
while (B > 0) {
12 42
r  A modulo B
AB true 12 42 12
Br
true 6 12 6
}
result is A true 0 6 0
} false

Result: 6
50

Bài tập
• Sinh viên cài đặt thuật toán Euclid
51

CÁM ƠN ĐÃ LẮNG
NGHE!

You might also like