Basicpython
Basicpython
Python is
• Open-source programming language
created by Guido van Rossum in late ‘80
and released in early ‘91.
• High-level programming language.
Reading and writing Python codes is just
like reading and writing simple English
statement.
• An object-oriented programming (OOP)
language.
3
สาธุ 99
Guido van Rossum
(คีโด ฟั น โรสซึม)
4
Works with Python
Python
Python Software
Developer Engineer
•Font and Back •Testing and
End debugging code Quality
Assurance Machine
•Optimizing data •Code Data Product
algorithms documentation Engineer Data Analyst Learning Educator
scientist Manager
•data analytics •Etc. Engineer
problems (QA Eng.)
•data security and
protection
•Etc.
5
Works with Python C
C++ JavaScript
TypeScript
PHP
HTML/CSS
C#
Bash/Shell/PowerShell
SQL
Java
Python
6
Works with Python C
C++ JavaScript
TypeScript
PHP
HTML/CSS
C#
Bash/Shell/PowerShell
SQL
Java
Python
7
Developer, embedded
Data or business analyst
applications or devices
System administrator
Developer, back-end
Designer
Database administrator
DevOps specialist
Developer, mobile
Developer, full-stack
Developer, front-end
8
Organization with Python
รู ปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-NC-ND รู ปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-SA-NC รูปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-SA
9
Organization with Python
รู ปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY รูปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-SA
10
รู ปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-SA รูปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-NC-ND
How to install Python [Link]
• Python IDLE
11
How to install Python
12
How to install Python
14
How to install Python
15
How to install Python
16
How to install Python
17
How to install Python
18
How to install Python
2
1
Python IDLE
Python shell
19
How to install Python [Link]/products/distribution
• Anaconda Jupyter
20
How to install Python
21
How to install Python
1 2
22
How to install Python
4 5
23
How to install Python
นานนิดหนอย
7 8
24
How to install Python
9 10
25
How to install Python
• Open Anaconda
26
How to install Python
27
How to install Python
28
How to install Python
29
How to install Python
30
How to install Python
31
How to install Python
32
How to install Python
33
Agenda
• Introduction
• Input and Display
• Data types of Python
• Conditions
• Loops
34
Introduction
• No semicolon
35
Introduction
variable operating
36
Introduction
Block 2
Block 3
Block 3
Block 2, continuation
Block 1, continuation
37
Introduction
1. Identifiers can be a combination of letters in lowercase (a-z) or uppercase (A-Z) or digits (0-9)
or an underscore (_).
E.g. 4variable
4. Identifiers can’t be the reserved very keywords and it’s case sensitive.
E.g. a, this_is_my_variable_name_and_it_can_be_this_long 38
Introduction
• Python’s Keywords
and del from None raise
• input() function
• It has a return variable. So, we need to have a variable to store it !
x = input() E.g.
x = input('Enter your name:’) age = int(input(“How old are you : ”))
print(age, type(age))
>> How old are you : 20
20 <class ‘int’>
40
Input and Display
• print() function
• This function displays data or result on the screen.
41
Input and Display
• print() function
print()
print(2+5)
print(“Hello”)
print(“num” + “ber”)
print(“str :”, variable)
print(“My name is ”, name, “\nHow are you.”)
7
Hello
number
str : variable
My name is name
How are you.
42
Input and Display
• print(“Letters”.format(…))
Argument 0 Argument 1
43
Input and Display
• print(“Letters”.format(…))
44
Input and Display
• print(“Letters”.format(…))
45
Input and Display
46
Data types of Python
• Numeric
• Boolean
• Operators
• String
• List
• Tuple
• Set
• Dictionary
47
Data types of Python
• Numeric
• Integers dec bin oct hex
E.g. 0, -1, 1028, 0b1011, bin(13), 0o13, oct(18), 0xcf, hex(125), etc.
• Floating point numbers
E.g. 1., 0.01, 15.025, 3.14, 15E-3, etc.
• Complex numbers
E.g. 5.5+2j, -4.5+3j
A + bj
Real Imaginary
Complex numbers
48
Data types of Python
• Numeric
49
Data types of Python
• Numeric
50
Data types of Python
• Numeric
51
Data types of Python
52
Data types of Python
• Operators
• Arithmetic operators
Operator mean E.g. Result
+ Addition 7+2 9
- Subtraction 7-2 5
* Multiplication 7*2 14
/ Division 7/2 3.5
% Modulos 7%2 1 (เพราะ 7 หาร 2 เหลือเศษ 1)
** Exponetial 7**2 49
3 (เพราะ 7 หาร 2 ได้ 3.5 จึงปั ดเศษออก
// Floor division 7//2
เหลือ 3)
53
Data types of Python
• Operators
• Arithmetic operators
Numeric Operator Iterable Operator
A=A+3 A += 3
A=A-3 A -= 3
A=A*3 A *= 3
A=A/3 A /= 3
A = A ** 3 A **= 3
A=A%3 A %= 3
54
Data types of Python
• Operators
• Logical operators
A B and or not A not B
True True True True False False
True False False True False True
False True False True True False
False False False False True True
55
Data types of Python
• Operators
• Comparison operators
56
Data types of Python
• String
+
H e l l o
-
ค่า index แบบบวก 0 1 2 3 4
• String
58
Data types of Python
• String Escape
Code Result
\’ Single Quote
\” Double Quote
\\ Backlash
\n New Line
\t Tab
\b Backspace
59
Data types of Python
• List
• List is a data type in Python that is mutable and changeable.
• A list can contain any type and number of element.
• It can hold one data type or a combination of several data types.
Name_list = [ ]
E.g.
List with integers : int_list = [1, 2, 3, 4]
List with strings : string_list = [‘day’, ‘month’, ‘year’, ‘time’]
List with mixed data types : mixed_list = [10, ‘ten’, 3.14]
List with nested list : nested_list = [“finger”, [1, 2, 3, 4]]
60
Data types of Python
61
Data types of Python
>> weekday[0]
“Monday”
>> week[3]
8
62
Data types of Python
>> nested_list[0]
“finger”
>> nested_list[1]
[1, 2, 3, 4]
>> nested_list[1][1]
2
>> nested_list[1][-1]
4
63
Data types of Python
>> weekday[-1]
“Friday”
>> week[-3]
0.45
64
Data types of Python
>> weekday[0:4]
[“Mon”, “Tue”, “Wed”, “Thurs”]
>> weekday[4:]
[“Fri”, “Sat”, “Sun”]
>> weekday[:2]
[“Mon”, “Tue”]
>> weekday[:-2]
[“Mon”, “Tue”, “Wed”, “Thurs”, “Fri”]
>> weekday[:]
[“Mon”, “Tue”, “Wed”, “Thurs”, “Fri”, “Sat”, “Sun”] 65
Data types of Python
66
Data types of Python
[Link](index, element)
num_list = [1, 2, 4, 8, 9, 10]
num_list.insert(2, 3) [1, 2, 3, 4, 8, 9, 10]
print(num_list)
67
Data types of Python
E.g. 1
num_list = [10, 20, 30, 40, 50]
num_list[0] = 0 [0, 20, 30, 40, 50]
print(num_list)
E.g. 2
num_list = [10, 20, 30, 40, 50]
num_list[0:3] = [0, 1, 2] [0, 1, 2, 40, 50]
print(num_list)
68
Data types of Python
69
Data types of Python
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
70
Data types of Python
[Link](index)
num_list = [1, 2, 4, 8, 9, 10]
num_list.pop(2) [1, 2, 8, 9, 10]
print(num_list)
71
Data types of Python
Trick
num_list = [1, 2, 4, 8, 9, 10]
num_list[:] = [ ] []
print(num_list)
72
Data types of Python
>> 40 in num_list
True
>> 50 not in num_list
False
>> “Fri” in weekday
True
>> “Sun” not in weekday
True 73
Data types of Python
• Other
• [Link]()
• [Link]()
• [Link](element)
• len(list)
• max(list)
• min(list)
• sum(list)
74
Data types of Python
• Tuple
• Tuple is an immutable list.
• List’s methods and functions are all applicable for tuple except the methods
those change the list like append(), remove(), reverese(), sort().
Name_tuple = ( )
E.g.
Tuple with integers : int_tuple = (1, 2, 3, 4)
Tuple with strings : string_tuple = (‘day’, ‘month’, ‘year’, ‘time’)
Tuple with mixed data types : mixed_tuple = (10, ‘ten’, 3.14)
Tuple with nested list : nested_tuple = (“finger”, [1, 2, 3, 4])
75
Data types of Python
• Set
• Set is an group of unique elements.
• It works like mathematical sets.
• It can contain elements of different types except the mutable element like list,
dictionary, or set.
Name_set = set( ) or Name_set = { }
76
Data types of Python
E.g.
Set with integers : int_set = {1, 2, 3, 3, 4, 5} => {1, 2, 3, 4, 5}
Set with strings : string_set = {‘a’, ‘e’, ‘i’, ‘o’, ‘a’, ‘i’} => {‘a’, ‘e’, ‘i’, ‘o’}
Set with mixed data types : mixed_set = {10, ‘ten’, (7, 8, 9)}
Set created from list : my_set = set([1, 2, 3, 4, 4]) => {1, 2, 3, 4}
Set created from tuple : my_set = set((1, 2, 3, 4)) => {1, 2, 3, 4}
77
Data types of Python
[Link](list of elements)
num_set = {2, 4, 8, 9, 10}
num_set.update([1, 3, 5, 6]) {1, 2, 3, 4, 5, 6, 8, 9, 10}
print(num_set)
78
Data types of Python
[Link]()
num_set = {2, 4, 8, 9}
num_set.clear() {}
print(num_set)
79
Data types of Python
• Dictionary
• Dictionary is a collection of key-value pairs which are separates by colon.
• It can contain values with any data type.
• However, its keys are immutable(string, tuple, or number only).
• The values in a dictionary can be accessed using keys only.
E.g.
My_dictionary = {“name” : “Keith”, “subject” : “Python”, “score” : 97.50, “ranking” : 1}
80
Data types of Python
>> my_dict[“name”]
“Keith”
>> my_dict.get(“name”)
“Keith”
81
Data types of Python
>> my_dict[“score”] = 98
>> print(my_dict)
{“name” : “Keith”, “subject” : “Python”, “score” : 98, “ranking” : 1, “result” : “pass”}
82
Data types of Python
>> my_dict.pop(“subject”)
>> print(my_dict)
{“name” : “Keith”, “score” : 97.50, “ranking” : 1}
83
Data types of Python
• Clear Dictionary
>> my_dict.clear()
>> print(my_dict)
{}
84
Data types of Python
• Updating Dictionary
my_dict1 = {“name” : “Keith”, “subject” : “Python”, “score” : 97.50, “ranking” : 1}
my_dict2 = {“surname” : “Williams”, “Grade” : 5, “score” : 98}
>> my_dict1.update(my_dict2)
>> print(my_dict1)
{“name” : “Keith”, “subject” : “Python”, “score” : 98, “ranking” : 1, “surname” :
“Williams”, “Grade” : 5}
85
Conditions
• If statement
• If-else statement
• If-elif-else statement
• nested-if statement
86
Conditions
False
Cond
• If statement True
if condition:
statement(s)
direct1
direct2
87
Conditions
False
Cond
direct3
88
False
Conditions Cond
1
True Cond
False
2
• If-elif-else direct1 False
True Cond
if condition: 3
statement(s) direct2 True
elif condition:
statement(s) direct3 direct4
else:
statement(s)
direct5
89
if
Conditions Cond elif
1
Cond else
• nested-if if 2
90
Loops
91
Loops
x = start
range(x, y, z) y = to y-1
z = step
for i in range(5):
print(”*” * (i+1))
Out: *
**
***
****
***** 93
Loops
95
Loops
• While loop
while condition:
statement(s)
user_input = ‘ ‘
while user_input != ‘unlock’:
user_input = input((‘What is the password? : ’))
print(‘Yes, the password is ’ + user_input + ‘. You may enter.’)
Out: What is the password? : a
What is the password? : password
What is the password? : unlock
Yes, the password is unlock. You may enter.
96
Loops
• Break statement
break
week = [‘mon’, ‘tue’, ‘wed’, ‘thurs’, ‘fri’, ‘sat’, ‘sun’] Out: mon is a weekday.
for day in week : tue is a weekday.
if day == ‘sat’ : wed is a weekday.
break thurs is a weekday.
print(day, ‘Is a weekday.’) fri is a weekday.
print(‘These are all weekday !’) These are all weekday !
97
Loops
• Continue statement
continue
week = [‘mon’, ‘tue’, ‘wed’, ‘thurs’, ‘fri’, ‘sat’, ‘sun’] Out: Today is mon !
for day in week : Today is tue !
if day == ‘sat’ : Today is wed !
continue Today is thurs !
print(‘Today is’, day, ‘!’) Today is fri !
print(‘What day is missing? !’) Today is sun !
What day is missing? !
98
Loops
• Infinite loop
while True:
statement(s)
user_input = ‘ ‘
while True:
user_input = input((‘What is the password? : ’))
if user_input == ‘unlock’ :
break
print(‘Yes, the password is ’ + user_input + ‘. You may enter.’)
Out: What is the password? : a
What is the password? : password
What is the password? : unlock
Yes, the password is unlock. You may enter.
99
Loops
• Pass statement
pass
100
Python 001
Department of Electrical Engineering
En-tech Silpakorn University
Day 2
Agenda
102
Error and Exceptions
• Syntax Error
• Runtime Error
• Logic Error
103
Error and Exceptions
• Syntax Error
104
Error and Exceptions
• Runtime Error
105
Error and Exceptions
106
Error and Exceptions
107
Error and Exceptions
108
Error and Exceptions
109
Error and Exceptions
110
Error and Exceptions
111
Function
def function_name(arguments):
Input : arguments statement(s) Output : values
return(values)
112
Function
Main code
return values to main code
113
Function
114
Function
Main code
return values to main code
116
Function
• Local Variable
• Local variable is variable defined inside a function and dose not exist outside the
function.
• In this case, we don’t have to worry whether the variable names in the function
are also used in other functions because it’s local that particular function only!
117
Function
• E.g.
def celcius2fahrenheit(celsiusTemp):
temp = (celsiusTemp*9/5)+32
return temp
def fahrenheit2celcius(fahrenheit):
temp = (fahrenheit-32)*5/9
return temp
118
Function
• Gobal Variable
• Global variable is variable that is available to every part of the code (global scope).
• In this case, it’s one to many concept: one variable that can be used in many parts
of the code, both inside and outside the function.
119
print(‘global a =', a)
Function func1()
print(‘global a =', a)
func2()
• E.g. print(‘global a =', a)
func3()
a=1 print(‘global a =', a)
def func1():
print('Inside func1() a =', a)
def func2(): global a = 1
a=2 Inside func1() a = 1
print('Inside func2() a =', a) global a = 1
def func3(): Inside func2() a = 2
global a global a = 1
a=3 Inside func3() a = 3
print('Inside func3() a =', a) global a = 3
120
Lambda
• Lambda Function
• Lambda function is used for defining anonymous function (function without
name).
121
Lambda
122
Lambda
• Map() function performs task of the function and returns a new list containing
all elements returned from the original list.
• E.g.
num_list = [1, 2, 3, 4, 5]
square_list = map(lambda x: x*x, num_list)
print(list(square_list))
123
Lambda
• Filter() function performs task of the function and returns a new list containing
elements from the original list that meet the condition (True).
• E.g.
num_list = [1, 2, 3, 4, 5]
square_list = filter(lambda x: (x%2 == 0), num_list)
print(list(square_list))
[2, 4]
124
Modules
125
Modules
[Link]
127
Modules
• from
128
Modules
• Import Statement
8 5
129
Modules
• From Statement
from random import randint, choice from random import randint as rint
a = randint(1, 10) a = rint(1, 10)
list = [1, 2, 3, 4, 5]
B = choice(list)
5
8
3 130
Modules
• From Statement
8
3 131
Modules: Random
132
Modules: Math
• [Link](x), [Link](x):
return ceiling or floor value of x
• [Link](x):
return square root value of x
from math import sqrt
print(‘Square root value of 100 is ’, sqrt(100))
• From Statement
8
3 134