0% found this document useful (0 votes)
17 views132 pages

Basicpython

Uploaded by

sorapon8024
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)
17 views132 pages

Basicpython

Uploaded by

sorapon8024
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/ 132

Hello Python

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, desktop or enterprise


applications

Developer, front-end

8
Organization with Python

รู ปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-SA


รูปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-NC-ND รูปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY
รู ปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY

รูปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-SA

รูปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-SA-NC


รูปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ CC BY-NC

รู ปถ่ายนี โดย ไม่ทราบผูเ้ ขียน ลิขสิทธิ ของ 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

1 เลือก Add Python to PATH


13
How to install Python

14
How to install Python

15
How to install Python

waiting for end…

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

กด NEXT ไปเรื่อย ๆ จนถึงหนา Advanced Installation Options

1 2
22
How to install Python

4 5
23
How to install Python

เลือก Register Anaconda3 as my default Python แลวจึงกด Install

นานนิดหนอย

7 8
24
How to install Python

กด Next และ Finish

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

• Close Anaconda  Ctrl + C

33
Agenda

• Introduction
• Input and Display
• Data types of Python
• Conditions
• Loops

34
Introduction

• Python Syntax & Structure


• Python syntax is UNIQUE

• No semicolon

• Space matters at the beginning of lines

Time = int(input(‘This is Real Time : ’))


print(‘Time is : ’ ,Time)

35
Introduction

variable operating

Time = int(input(‘This is Real Time : ’))


print(‘Time is : ’ ,Time)
Indentation

36
Introduction

• Python Syntax & Structure


Block 1

Block 2

Block 3

Block 3

Block 2, continuation

Block 1, continuation
37
Introduction

• Python Syntax & Structure


• 5 rules for writing identifier

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. a, C, My_var, variable4

2. Identifiers can’t start with digit.

E.g. 4variable

3. Identifiers can’t contain special symbols like +, -, *, /, %, @, &, #, $ etc.

4. Identifiers can’t be the reserved very keywords and it’s case sensitive.

5. Identifiers can be any length.

E.g. a, this_is_my_variable_name_and_it_can_be_this_long 38
Introduction

• Python’s Keywords
and del from None raise

as elif global nonlocal return

assert else if not True

break except import and try

class False in or while

continue finally as pass with

def for lambda print yield 39


Input and Display

• input() function
• It has a return variable. So, we need to have a variable to store it !

name = input() or name = input(“Letters”)

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.

print(), print(variable), print(“Letters”) or print(“Letters”, variable), etc.

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(…))

print(“Hello, my name {}, I am {} years old.”.format(“Je”, 25))

Argument 0 Argument 1

Hello, my name Je, I am 25.0 years old.

43
Input and Display

• print(“Letters”.format(…))

print(“Hello, my name {0}, I am {1} years old.”.format(“Je”, 25))

Hello, my name Je, I am 25.0 years old.

44
Input and Display

• print(“Letters”.format(…))

print(“Hello, my name {1}, I am {0} years old.”.format(“Je”, 25))

Hello, my name 25.0, I am Je years old.

45
Input and Display

• print(“Letters”, sep = ‘…..’, end = ‘…..’)

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

• Boolean (Output is True of False)


a=6 True <class ‘bool’>
b=7 False <class ‘bool’>
c=3>2 True <class ‘bool’>
d=5<1
e=a<b
print(c, type(c))
print(d, type(d))
print(e, type(e))

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

Operator mean E.g. Result


== Equal 7==2 False
!= Not equal 7!=2 True
> Greater than 7>2 True
< Less than 7<2 False

>= Greater than or equal 7>=2 True


to
<= Less than or equal to 7<=2 False

56
Data types of Python

• String
+
H e l l o
-
ค่า index แบบบวก 0 1 2 3 4

ค่า index แบบลบ -5 -4 -3 -2 -1


x y z
ค่า index แบบบวก 0 1 2

ค่า index แบบลบ -3 -2 -1


57
Data types of Python

• 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

• Accessing Elements of a List


• Indexing
• Nested indexing
• Negative indexing
• Slicing

61
Data types of Python

• Accessing Elements of a List


• Indexing
E.g. 1
weekday = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”]
E.g. 2
week = [1, “Tuesday”, 0.45, 8, “Friday”]

>> weekday[0]
“Monday”
>> week[3]
8
62
Data types of Python

• Accessing Elements of a List


• Nested indexing
E.g. 1
nested_list = [“finger”, [1, 2, 3, 4]]

>> 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

• Accessing Elements of a List


• Negative indexing
E.g. 1 -5 -4 -3 -2 -1
weekday = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”]
E.g. 2
week = [1, “Tuesday”, 0.45, 8, “Friday”]

>> weekday[-1]
“Friday”
>> week[-3]
0.45
64
Data types of Python

• Accessing Elements of a List


• Slicing
E.g. 1
weekday = [“Mon”, “Tue”, “Wed”, “Thurs”, “Fri”, “Sat”, “Sun”]

>> 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

• Adjust Elements of a List


• Adding elements
• Changing elements
• Concatenating lists
• Repeating list
• Deleting elements
• Clear elements
• Checking membership

66
Data types of Python

• Adjust Elements of a List


• Adding elements
[Link](element)
num_list = [10, 20, 30, 40, 50]
num_list.append(60) [10, 20, 30, 40, 50, 60]
print(num_list)

[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

• Adjust Elements of a List


• Changing elements

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

• Adjust Elements of a List


• Concatenating lists
E.g. 1
weekday = [“Mon”, “Tue”, “Wed”, “Thurs”, “Fri”]
weekend = [“Sat”, “Sun”]
week = weekday + weekend
print(week)

[“Mon”, “Tue”, “Wed”, “Thurs”, “Fri”, “Sat”, “Sun”]

69
Data types of Python

• Adjust Elements of a List


• Repeating list
num_list = [1, 2, 3, 4, 5]*3
print(num_list)

[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

70
Data types of Python

• Adjust Elements of a List


• Deleting elements
[Link](element)
num_list = [10, 20, 30, 40, 50]
num_list.remove(20) [10, 30, 40, 50]
print(num_list)

[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

• Adjust Elements of a List


• Clear elements
[Link]()
num_list = [10, 20, 30, 40, 50]
num_list.clear() []
print(num_list)

Trick
num_list = [1, 2, 4, 8, 9, 10]
num_list[:] = [ ] []
print(num_list)

72
Data types of Python

• Adjust Elements of a List


• Checking membership
num_list = [10, 20, 30, 40, 50]
weekday = [“Mon”, “Tue”, “Wed”, “Thurs”, “Fri”]

>> 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

• Adjust Elements of a Set


• Adding elements
[Link](element)
num_set = {10, 30, 40, 50}
num_set.add(20) {10, 20, 30, 40, 50}
print(num_set)

[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

• Adjust Elements of a Set


• Deleting elements
[Link](element)
num_set = {10, 20, 30, 40, 50}
num_set.remove(20) {10, 30, 40, 50}
print(num_set)

[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.

Name_dict = {key1 : value1, key2 : value2, …, keyN : valueN}

E.g.
My_dictionary = {“name” : “Keith”, “subject” : “Python”, “score” : 97.50, “ranking” : 1}

80
Data types of Python

• Accessing Elements of a Dictionary

my_dict = {“name” : “Keith”, “subject” : “Python”, “score” : 97.50, “ranking” : 1}

>> my_dict[“name”]
“Keith”

>> my_dict.get(“name”)
“Keith”

81
Data types of Python

• Adding and Changing key-value pair to a Dictionary

my_dict = {“name” : “Keith”, “subject” : “Python”, “score” : 97.50, “ranking” : 1}

>> my_dict[“result”] = “pass”


>> print(my_dict)
{“name” : “Keith”, “subject” : “Python”, “score” : 97.50, “ranking” : 1, “result” : “pass”}

>> my_dict[“score”] = 98
>> print(my_dict)
{“name” : “Keith”, “subject” : “Python”, “score” : 98, “ranking” : 1, “result” : “pass”}

82
Data types of Python

• Deleting Key-value Pair from a Dictionary

my_dict = {“name” : “Keith”, “subject” : “Python”, “score” : 97.50, “ranking” : 1}

>> my_dict.pop(“subject”)
>> print(my_dict)
{“name” : “Keith”, “score” : 97.50, “ranking” : 1}

83
Data types of Python

• Clear Dictionary

my_dict = {“name” : “Keith”, “subject” : “Python”, “score” : 97.50, “ranking” : 1}

>> 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

• If-else statement True


if condition:
statement(s) direct1 direct2
else:
statement(s)

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

if condition: Cond elif


1.1
if condition:
statement(s) Cond else
1.2 Direct 2.1 Direct 2.2
elif condition:
statement(s)
else:
statement(s) Direct 1.2 Direct 1.3
elif condition:
statement(s) Direct 1.1
else:
statement(s)

90
Loops

• A loop allows us to execute the repetitive statement(s).


• Structures and statements to deal with loop:
• For loop
• While loop
• Break statement
• Infinite loop
• Continue statement
• Pass statement

91
Loops

• For loop with Range function

x = start
range(x, y, z) y = to y-1
z = step

Statement Generated Result


range(5) 0, 1, 2, 3, 4
range(1, 5) 1, 2, 3, 4
range(0, 10, 2) 0, 2, 4, 6, 8
range(10, 0, -2) 10, 8, 6, 4, 2
92
Loops

• For loop with Range function


for variable in range(x, y, z):
statement(s)

for i in range(5):
print(”*” * (i+1))
Out: *
**
***
****
***** 93
Loops

• For loop with List/Tuple


for variable in list/tuple:
statement(s)
week = [‘monday’, ‘tuesday’, ‘wednesday’, ‘thursday’, ‘friday’, ‘saturday’, ‘sunday’]
for day in week:
print(”It’s”, day, “!”)
Out: It’s monday !
It’s tuesday !
It’s wednesday !
It’s thursday !
It’s friday !
It’s saturday !
It’s sunday !
94
Loops

• For loop with String


for variable in string:
statement(s)
for letter in ‘python’:
print(letter)
Out: p
y
t
h
o
n

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

weekday = [‘monday’, ‘tuesday’, ‘wednesday’, Out: Today is saturday !


‘thursday’, ‘friday’] Today is sunday !
weekend = [‘saturday’, ‘sunday’]
for i in weekday :
pass
for day in weekend :
print(‘Today is’, day, ‘!’)

100
Python 001
Department of Electrical Engineering
En-tech Silpakorn University

Day 2
Agenda

• Error and Exceptions


• Function
• Lambda function
• Modules
• Workshop

102
Error and Exceptions

• Syntax Error

• Runtime Error

• Logic Error

Input : arguments System Output : values

103
Error and Exceptions

• Syntax Error

104
Error and Exceptions

• Runtime Error

105
Error and Exceptions

• try & except


• The try block lets you test a block of code for errors.

• The except block lets you handle the error.

106
Error and Exceptions

• try & except

107
Error and Exceptions

• try & except (Case 1)

108
Error and Exceptions

• try & except (Case 2)

109
Error and Exceptions

• try & except (Case 3)

110
Error and Exceptions

• try & except (Case 4)

111
Function

• A function is a set of statements that perform a task and they


are grouped together as one.

def function_name(arguments):
Input : arguments statement(s) Output : values
return(values)

112
Function

run function Output values


Function code

Main code
return values to main code

113
Function

• To reduce code duplication and maximize the use of code.

• To have a nice block of code to deal with specific task.

• To hide details of implementation in the main function or task.

• To improve traceability & readability.

114
Function

arguments def function_name(arguments): Output values


statement(s)
return(values)

Main code
return values to main code

• def keyword: defines the beginning of the function.


• function_name: a unique name of a function.
• argument: are optional and used to pass input values to function.
• Colon (:)
• statement(s): defines the actions that the function will perform.
• return: are option and return values from a function. If the return statement
is not defined, the function will return None
115
Function

• Function without/within Argument(s)


def greeting():
print(“Hello, good morning”)

def greeting(name, day):


print(“Hello, ”, name, “!”, “Have a nice”, day)

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).

• It can take as many arguments as we want in expression.

• The expression is evaluated then returned.

lambda arguments: expression

121
Lambda

• What is the Difference between Function and Lambda function

Function: Lambda function:


def square(y): square = lambda y: y*y
return y*y
print(square(5))
print(square(5))
25
25

122
Lambda

• Map() function performs task of the function and returns a new list containing
all elements returned from the original list.

• Map() function takes a lambda function and a list as its arguments.

• E.g.

num_list = [1, 2, 3, 4, 5]
square_list = map(lambda x: x*x, num_list)
print(list(square_list))

[1, 4, 9, 16, 25]

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).

• Filter() function takes a lambda function and list as its arguments.

• 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

• Module is a simply a Python file (.py file). It can contain function,


classes, or variables.
• Why using module?
• Grouping related code into a module makes the code easier to understand
and usd.

• A module is considered as a Python object that you can use and


reference.
• The name of the Python file is the name of the module.

125
Modules

• We can discover the attributes, methods and classes in the


module by using dir() function.

import sys ['__breakpointhook__',


dir(sys) '__displayhook__', '__doc__',
'__excepthook__',
'__interactivehook__’, …,
'stderr', 'stdin', 'stdout',
'thread_info', 'version',
'version_info', 'warnoptions',
'winver']
126
Modules

[Link]

127
Modules

• How to use Modules?


• We can use a module by using one of the two statements
• import

• from

• Import statement: allows us to access and use the whole module as


it is.

• From statement: allows us to access and use particular function(s)


from the module.

128
Modules

• Import Statement

Syntax import moduleName

import random import random as rd


a = [Link](1, 10) a = [Link](1, 10)

8 5
129
Modules

• From Statement

Syntax from moduleName import functionName(s)

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

Syntax from moduleName import *

from random import *


a = randint(1, 10)
list = [1, 2, 3, 4, 5]
B = choice(list)

8
3 131
Modules: Random

• Random module contains functions to handle random numbers for instance.

• [Link](x, y): import random


return random integer print([Link](1, 10))
between x and y
3

• [Link](list): myList = [‘orange’, 109, False, 10.52, ‘blue’]


return random value print([Link](myList))
in the list
‘orange’

132
Modules: Math

• Math module contains Python’s mathematical functions. For instance,

• [Link](x), [Link](x):
return ceiling or floor value of x

import math import math as m


print(‘Ceiling value of 24.11 is ’, [Link](24.11)) print(‘Flooring value of 24.11 is ’, [Link](24.11))

Ceiling value of 24.11 is 25 Flooring value of 24.11 is 24

• [Link](x):
return square root value of x
from math import sqrt
print(‘Square root value of 100 is ’, sqrt(100))

Square root value of 100 is 10.0 133


Modules

• From Statement

Syntax from moduleName import *

from random import *


a = randint(1, 10)
list = [1, 2, 3, 4, 5]
B = choice(list)

8
3 134

You might also like