SlideShare ist ein Scribd-Unternehmen logo
1 von 89
Downloaden Sie, um offline zu lesen
Keep Calm and Code Python

Let’s Python

Department of Computing!
Faculty of Science!
Silpakorn University
Keep Calm and Code Python

Let’s Python

Department of Computing!
Faculty of Science!
Silpakorn University
Keep Calm and Code Python

Let’s Python

Department of Computing!
Faculty of Science!
Silpakorn University
Keep Calm and Code Python

Who am I ?
Kiattisak Anoochitarom!
Graduated from Computer Science at SU, 2013!
Software Developer at Charged Concept Co, LTD.!

!

Skill Sets: iOS, Rails, Node.js, Ruby, Python, Javascript, !
C++, C, Java, Badminton!

!

Contacts:!
macbaszii@gmail.com!
Twitter: @iMacbaszii!
http://www.facebook.com/baszii!
http://www.macbaszii.com!
Who Invented ?

❖

Guido van Rossum!

❖

Dutch!

❖

2005 - 2012 at Google inc.!

❖

2013 at Dropbox inc.
Langauge Characteristic
Langauge Characteristic
❖

Open Source (Python Software Foundation)
Langauge Characteristic
❖

Open Source (Python Software Foundation)

❖

Rapid Development
Langauge Characteristic
❖

Open Source (Python Software Foundation)

❖

Rapid Development

❖

Short and Readable Code
Langauge Characteristic
❖

Open Source (Python Software Foundation)

❖

Rapid Development

❖

Short and Readable Code

❖

Indentation!
Langauge Characteristic
❖

Open Source (Python Software Foundation)

❖

Rapid Development

❖

Short and Readable Code

❖

Indentation!

❖

Strong and Dynamic Typing
Langauge Characteristic
❖

Open Source (Python Software Foundation)

❖

Rapid Development

❖

Short and Readable Code

❖

Indentation!

❖

Strong and Dynamic Typing

❖

Interpreter Style
PEP - 8
Python Coding Style Guide
http://www.python.org/dev/peps/pep-0008/
Input & Output
Input & Output
name = raw_input()
print "Hello, %s" % (name)
print "Hello, " + name
x = input()
y = input()
print x * y
Input & Output
name = raw_input()
print "Hello, %s" % (name)
print "Hello, " + name
x = input()
y = input()
print x * y

Hands - on!!
Data Type
Dictionary

String
Integer

Boolean
Floating Point

List

Set
None

Class Instance
Data Type
Dictionary
sentence = 'this is a cat'

Integer
Boolean
Floating Point

List

Set
None

Class Instance
Data Type
Dictionary
sentence = 'this is a cat'
x = 20

Boolean
Floating Point

List

Set
None

Class Instance
Data Type
Dictionary
sentence = 'this is a cat'
x = 20
you_love_me = True

Floating Point

List

Set
None

Class Instance
Data Type
Dictionary
sentence = 'this is a cat'
x = 20
you_love_me = True

pi = 3.1415927

List

Set
None

Class Instance
Data Type
Dictionary
sentence = 'this is a cat'
x = 20
you_love_me = True

pi = 3.1415927

List

Set
nothing = None

Class Instance
Data Type
Dictionary
sentence = 'this is a cat'
x = 20
you_love_me = True

pi = 3.1415927

even_numbers = [2, 4, 6, 8, 10]

Set
nothing = None

Class Instance
Data Type
Dictionary
sentence = 'this is a cat'
x = 20
you_love_me = True

pi = 3.1415927

even_numbers = [2, 4, 6, 8, 10]

odd_numbers = {1, 3, 5, 7, 9}

nothing = None

Class Instance
Data Type
profile = { 'name': 'Bas',
'email': 'macbaszii@gmail.com'}
sentence = 'this is a cat'
x = 20
you_love_me = True

pi = 3.1415927

even_numbers = [2, 4, 6, 8, 10]

odd_numbers = {1, 3, 5, 7, 9}

nothing = None

Class Instance
Data Type
profile = { 'name': 'Bas',
'email': 'macbaszii@gmail.com'}
sentence = 'this is a cat'
x = 20
you_love_me = True

pi = 3.1415927

even_numbers = [2, 4, 6, 8, 10]

odd_numbers = {1, 3, 5, 7, 9}

nothing = None

my_car = Car('Lamborghini',
'Aventador LP 700-4', 'White')
Data Type
profile = { 'name': 'Bas',
'email': 'macbaszii@gmail.com'}
sentence = 'this is a cat'
x = 20
you_love_me = True

pi = 3.1415927

even_numbers = [2, 4, 6, 8, 10]

odd_numbers = {1, 3, 5, 7, 9}

nothing = None

my_car = Car('Lamborghini',
'Aventador LP 700-4', 'White')
Operator
Math Operator
Math Operator
x = 10
y = 20
x + y
x - y
x * y
x / y
x % y
x**y
x += y
y *= x
Math Operator
x = 10
y = 20
x + y
x - y
x * y
x / y
x % y
x**y
x += y
y *= x

## Tips ##
int + int = int
int**(-int) = float
int / float = float
string + string = concat_string
string * int = multiply_string
list + list = list
Comparison Operator
Comparison Operator
x = 10
y = 20
x
x
x
x
x
x
x

> y
>= y
< y
<= y
== y
!= y
is y
Comparison Operator
x = 10
y = 20
x
x
x
x
x
x
x

> y
>= y
< y
<= y
== y
!= y
is y

# Chain Comparison
5 < x < y
1 < y < 100
# Contains Operator
prime = [2, 3, 5, 7, 11]
9 in prime # False
sentence = 'this is a cat'
'cat' in sentence # True
Logical Operator
Logical Operator
Although Python have & and | (pipe) to do logical operation !
but it isn’t readable and it will confuse with other symbol. !
But Python have special symbols to do logical operation that is …
Logical Operator
Although Python have & and | (pipe) to do logical operation !
but it isn’t readable and it will confuse with other symbol. !
But Python have special symbols to do logical operation that is …

and, or
Range and Lazy Generator
Range and Lazy Generator
range(10)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(3, 10)
# [3, 4, 5, 6, 7, 8, 9]
range(1, 20, 3)
# [1, 4, 7, 10, 13, 16, 19]
xrange(10)
xrange(3, 10)
xrange(1, 20, 3)
Control Statement
Conditional Statement
if
Conditional Statement
if
number = input("Enter Number: ")
if number > 0:
print "Number is Positive"
elif number < 0:
print "Number is Negative"
else:
print "Number is Zero"
Conditional Statement
if
number = input("Enter Number: ")
if number > 0:
print "Number is Positive"
elif number < 0:
print "Number is Negative"
else:
print "Number is Zero"
result = (number % 2 == 0) ? 'Even' : 'Odd'
Conditional Statement
if
number = input("Enter Number: ")
if number > 0:
print "Number is Positive"
elif number < 0:
print "Number is Negative"
else:
print "Number is Zero"
result = 'Even' if number % 2 is 0 else 'Odd'
Conditional Statement
if
number = input("Enter Number: ")
if number > 0:
print "Number is Positive"
elif number < 0:
print "Number is Negative"
else:
print "Number is Zero"
result = 'Even' if number % 2 is 0 else 'Odd'
Iteration Statement
for
Iteration Statement
for
for i in xrange(1, 11):
print i**2
Iteration Statement
for
for i in xrange(1, 11):
print i**2
socials = ['Facebook', 'Twitter']
for social in socials:
print 'I played %s' % social
Iteration Statement
for
for i in xrange(1, 11):
print i**2
socials = ['Facebook', 'Twitter']
for social in socials:
print 'I played %s' % social
message = 'Hello, CPSU'
for letter in message:
print letter
Iteration Statement
for
for i in xrange(1, 11):
print i**2
socials = ['Facebook', 'Twitter']
for social in socials:
print 'I played %s' % social
message = 'Hello, CPSU'
for letter in message:
print letter

# Endless Loop #
while True:
# Do something
Problem#1: Most Letter Count
Hint: You can get list of alphabets with this code

import string
!

alphabets = list(string.lowercase)
Function
Function
def function_name(params):
# Do something
# Do anything
Function
def function_name(params):
# Do something
# Do anything
def fibonacci(n):
fibo = 0
for k in xrange(0, int(math.floor((n - 1) / 2)) + 1):
fibo += math.factorial(n - k - 1) /
(math.factorial(k) * math.factorial(n - k - 1 - k))
return fibo
Function
def function_name(params):
# Do something
# Do anything
def fibonacci(n):
fibo = 0
for k in xrange(0, int(math.floor((n - 1) / 2)) + 1):
fibo += math.factorial(n - k - 1) /
(math.factorial(k) * math.factorial(n - k - 1 - k))
return fibo
def colorMultiply(r, g=0, b=0):
return [ r * 3.14159,
g * 1.414,
b * 3.27 ]
Built-in Functions
http://docs.python.org/2/library/functions.html
Problem#2: Make a
Palindrome StringgnirtS emordnilaP
Way Too Long Words
Sometimes some words like "localization" or "internationalization" are so long that writing them
many times in one text is quite tiresome.!
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should
be replaced with a special abbreviation.!
This abbreviation is made like this: we write down the first and the last letter of a word and between
them we write the number of letters between the first and the last letters. That number is in decimal
system and doesn't contain any leading zeroes.!
Thus, "localization" will be spelt as "l10n", and "internationalization will be spelt as “i18n".!
and make Palindrome from that word after that :)

http://codeforces.com/problemset/problem/71/A
Indexing and Slice
Indexing and Slice
message = 'Hello, world'
message[0] # H
message[len(message) - 1] # d
message[-1] # d
Indexing and Slice
message = 'Hello, world'
message[0] # H
message[len(message) - 1] # d
message[-1] # d
fibo = [1, 1, 2, 3, 5, 8, 13, 21, 34]
fibo[:5] # [1, 1, 2, 3, 5]
fibo[2:] # [2, 3, 5, 8, 13, 21, 34]
fibo[3:6] # [3, 5, 8, 13]
fibo[::2] # [1, 2, 5, 13, 34]
Indexing and Slice
message = 'Hello, world'
message[0] # H
message[len(message) - 1] # d
message[-1] # d
fibo = [1, 1, 2, 3, 5, 8, 13, 21, 34]
fibo[:5] # [1, 1, 2, 3, 5]
fibo[2:] # [2, 3, 5, 8, 13, 21, 34]
fibo[3:6] # [3, 5, 8, 13]
fibo[::2] # [1, 2, 5, 13, 34]
fibo[::-1] # ???
message[::-1] # ???
String and Collections methods

Demo!
List Comprehensive
The Other way to create and manipulation Python’s List
List Comprehensive
The Other way to create and manipulation Python’s List

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List Comprehensive
The Other way to create and manipulation Python’s List

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = []
for x in range(10):
squares.append(x**2)
List Comprehensive
The Other way to create and manipulation Python’s List

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)]
List Comprehensive
The Other way to create and manipulation Python’s List

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)]

set1 = [1, 2, 3]
set2 = [3, 1, 4]
List Comprehensive
The Other way to create and manipulation Python’s List

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)]

set1 = [1, 2, 3]
set2 = [3, 1, 4]
combs = []
for x in set1:
for y in set2:
if x != y:
comb.append((x, y))
List Comprehensive
The Other way to create and manipulation Python’s List

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)]

set1 = [1, 2, 3]
set2 = [3, 1, 4]
combs = [(x, y) for x in set1 for y in set2 if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List Comprehensive
The Other way to create and manipulation Python’s List

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)]

set1 = [1, 2, 3]
set2 = [3, 1, 4]
combs = [(x, y) for x in set1 for y in set2 if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List Comprehensive
The Other way to create and manipulation Python’s List

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)]

set1 = [1, 2, 3]
set2 = [3, 1, 4]
combs = [(x, y) for x in set1 for y in set2 if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List Comprehensive
The Other way to create and manipulation Python’s List

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)]

set1 = [1, 2, 3]
set2 = [3, 1, 4]
combs = [(x, y) for x in set1 for y in set2 if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Working with File
Working with File
open('filename', mode)
# r: open file for read
# w: open file for write
# a: open file for append
Working with File
open('filename', mode)
# r: open file for read
# w: open file for write
# a: open file for append
f = open('data.txt', r)
f.read() # read file to string
f.readline() # read file for one line
f.readlines() # read file to lines
Working with File
open('filename', mode)
# r: open file for read
# w: open file for write
# a: open file for append
f = open('data.txt', r)
f.read() # read file to string
f.readline() # read file for one line
f.readlines() # read file to lines
f.write('this is a cat') # write string to file
f.writelines([list of line]) # write lines to file
Object Oriented Programming
Object Oriented Programming
Class
Object Oriented Programming
Class

Instance
Object Oriented Programming
class Book:
def __init__(self, name, size):
self.name = name
self.size = size
class BookStack:
def __init__(self):
self.books = []
self.top = 0
def push(self, book):
self.books.append(book)
self.top += 1
def pop(self):
self.top -= 1
return self.books.pop()

!
Test Driven Development
Unit Test
import unittest

! TestBookStack(unittest.TestCase):
class

# when book is created, it can return name, size
def test_book_created(self):
hunger_book = Book('The Hunger Games', 4)
self.assertEqual(hunger_book.name, 'The Hunger Games')
self.assertEqual(hunger_book.size, 4)
# when Book Stack is created / top is 0
def test_book_stack_created(self):
book_stack = BookStack()
self.assertEqual(book_stack.top, 0)
self.assertEqual(book_stack.books, [])
# when push book / top increase by one
def test_book_stack_push(self):
hunger_book = Book('The Hunger Games', 4)
book_stack = BookStack()
book_stack.push(hunger_book)
self.assertEqual(book_stack.top, 1)
self.assertEqual(book_stack.books[0].name, 'The Hunger Games')
book_stack.push(hunger_book)
self.assertEqual(book_stack.top, 2)
# when pop book / top decrease by one
def test_book_stack_pop(self):
hunger_book = Book('The Hunger Games', 4)
harry_book = Book('Harry Potter', 3)
book_stack = BookStack()
book_stack.push(hunger_book)
book_stack.push(harry_book)
present_size = book_stack.top
poped_book = book_stack.pop()
self.assertEqual(book_stack.top, present_size - 1)
self.assertEqual(poped_book.name, 'Harry Potter')

if __name__ == '__main__':
unittest.main()
Keep Calm and Code Python

Problem#3: Books
Instruction:!
!
- Using TDD!!
!
- Each Book have a name, size!
!
- Books have size and all of book!

!
Test case:!
!
- paste the new book on top!
!
- pick a book at top of books!
!
- when paste new book you must take a
larger book to below!
!
- program can tell a present Books size
Migrate to Python 3

❖

print is function instead of
statement!

❖

input()!

❖

range instead of xrange!

❖

more usage on lazy generator

Weitere ähnliche Inhalte

Was ist angesagt?

AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basicsLuigi De Russis
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basicsLuigi De Russis
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programmingDamian T. Gordon
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Scott Wlaschin
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)Scott Wlaschin
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using PythonNishantKumar1179
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
Declarative Thinking, Declarative Practice
Declarative Thinking, Declarative PracticeDeclarative Thinking, Declarative Practice
Declarative Thinking, Declarative PracticeKevlin Henney
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data TypesRavi Shankar
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Python tutorial
Python tutorialPython tutorial
Python tutorialRajiv Risi
 

Was ist angesagt? (20)

AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basics
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basics
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)
 
Python language data types
Python language data typesPython language data types
Python language data types
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Declarative Thinking, Declarative Practice
Declarative Thinking, Declarative PracticeDeclarative Thinking, Declarative Practice
Declarative Thinking, Declarative Practice
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data Types
 
Eugene goostman the bot
Eugene goostman the botEugene goostman the bot
Eugene goostman the bot
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 

Ähnlich wie Python slide

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computingGo Asgard
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In PythonMarwan Osman
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutesSumit Raj
 
Introduction to Python3 Programming Language
Introduction to Python3 Programming LanguageIntroduction to Python3 Programming Language
Introduction to Python3 Programming LanguageTushar Mittal
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
Python Basics
Python BasicsPython Basics
Python BasicsPooja B S
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in pythoneShikshak
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfKosmikTech1
 

Ähnlich wie Python slide (20)

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Python
PythonPython
Python
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Python: The Dynamic!
Python: The Dynamic!Python: The Dynamic!
Python: The Dynamic!
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Introduction to Python3 Programming Language
Introduction to Python3 Programming LanguageIntroduction to Python3 Programming Language
Introduction to Python3 Programming Language
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 

Kürzlich hochgeladen

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Kürzlich hochgeladen (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Python slide

  • 1.
  • 2.
  • 3.
  • 4. Keep Calm and Code Python Let’s Python Department of Computing! Faculty of Science! Silpakorn University
  • 5. Keep Calm and Code Python Let’s Python Department of Computing! Faculty of Science! Silpakorn University
  • 6. Keep Calm and Code Python Let’s Python Department of Computing! Faculty of Science! Silpakorn University
  • 7. Keep Calm and Code Python Who am I ? Kiattisak Anoochitarom! Graduated from Computer Science at SU, 2013! Software Developer at Charged Concept Co, LTD.! ! Skill Sets: iOS, Rails, Node.js, Ruby, Python, Javascript, ! C++, C, Java, Badminton! ! Contacts:! macbaszii@gmail.com! Twitter: @iMacbaszii! http://www.facebook.com/baszii! http://www.macbaszii.com!
  • 8. Who Invented ? ❖ Guido van Rossum! ❖ Dutch! ❖ 2005 - 2012 at Google inc.! ❖ 2013 at Dropbox inc.
  • 10. Langauge Characteristic ❖ Open Source (Python Software Foundation)
  • 11. Langauge Characteristic ❖ Open Source (Python Software Foundation) ❖ Rapid Development
  • 12. Langauge Characteristic ❖ Open Source (Python Software Foundation) ❖ Rapid Development ❖ Short and Readable Code
  • 13. Langauge Characteristic ❖ Open Source (Python Software Foundation) ❖ Rapid Development ❖ Short and Readable Code ❖ Indentation!
  • 14. Langauge Characteristic ❖ Open Source (Python Software Foundation) ❖ Rapid Development ❖ Short and Readable Code ❖ Indentation! ❖ Strong and Dynamic Typing
  • 15. Langauge Characteristic ❖ Open Source (Python Software Foundation) ❖ Rapid Development ❖ Short and Readable Code ❖ Indentation! ❖ Strong and Dynamic Typing ❖ Interpreter Style
  • 16. PEP - 8 Python Coding Style Guide http://www.python.org/dev/peps/pep-0008/
  • 18. Input & Output name = raw_input() print "Hello, %s" % (name) print "Hello, " + name x = input() y = input() print x * y
  • 19. Input & Output name = raw_input() print "Hello, %s" % (name) print "Hello, " + name x = input() y = input() print x * y Hands - on!!
  • 21. Data Type Dictionary sentence = 'this is a cat' Integer Boolean Floating Point List Set None Class Instance
  • 22. Data Type Dictionary sentence = 'this is a cat' x = 20 Boolean Floating Point List Set None Class Instance
  • 23. Data Type Dictionary sentence = 'this is a cat' x = 20 you_love_me = True Floating Point List Set None Class Instance
  • 24. Data Type Dictionary sentence = 'this is a cat' x = 20 you_love_me = True pi = 3.1415927 List Set None Class Instance
  • 25. Data Type Dictionary sentence = 'this is a cat' x = 20 you_love_me = True pi = 3.1415927 List Set nothing = None Class Instance
  • 26. Data Type Dictionary sentence = 'this is a cat' x = 20 you_love_me = True pi = 3.1415927 even_numbers = [2, 4, 6, 8, 10] Set nothing = None Class Instance
  • 27. Data Type Dictionary sentence = 'this is a cat' x = 20 you_love_me = True pi = 3.1415927 even_numbers = [2, 4, 6, 8, 10] odd_numbers = {1, 3, 5, 7, 9} nothing = None Class Instance
  • 28. Data Type profile = { 'name': 'Bas', 'email': 'macbaszii@gmail.com'} sentence = 'this is a cat' x = 20 you_love_me = True pi = 3.1415927 even_numbers = [2, 4, 6, 8, 10] odd_numbers = {1, 3, 5, 7, 9} nothing = None Class Instance
  • 29. Data Type profile = { 'name': 'Bas', 'email': 'macbaszii@gmail.com'} sentence = 'this is a cat' x = 20 you_love_me = True pi = 3.1415927 even_numbers = [2, 4, 6, 8, 10] odd_numbers = {1, 3, 5, 7, 9} nothing = None my_car = Car('Lamborghini', 'Aventador LP 700-4', 'White')
  • 30. Data Type profile = { 'name': 'Bas', 'email': 'macbaszii@gmail.com'} sentence = 'this is a cat' x = 20 you_love_me = True pi = 3.1415927 even_numbers = [2, 4, 6, 8, 10] odd_numbers = {1, 3, 5, 7, 9} nothing = None my_car = Car('Lamborghini', 'Aventador LP 700-4', 'White')
  • 33. Math Operator x = 10 y = 20 x + y x - y x * y x / y x % y x**y x += y y *= x
  • 34. Math Operator x = 10 y = 20 x + y x - y x * y x / y x % y x**y x += y y *= x ## Tips ## int + int = int int**(-int) = float int / float = float string + string = concat_string string * int = multiply_string list + list = list
  • 36. Comparison Operator x = 10 y = 20 x x x x x x x > y >= y < y <= y == y != y is y
  • 37. Comparison Operator x = 10 y = 20 x x x x x x x > y >= y < y <= y == y != y is y # Chain Comparison 5 < x < y 1 < y < 100 # Contains Operator prime = [2, 3, 5, 7, 11] 9 in prime # False sentence = 'this is a cat' 'cat' in sentence # True
  • 39. Logical Operator Although Python have & and | (pipe) to do logical operation ! but it isn’t readable and it will confuse with other symbol. ! But Python have special symbols to do logical operation that is …
  • 40. Logical Operator Although Python have & and | (pipe) to do logical operation ! but it isn’t readable and it will confuse with other symbol. ! But Python have special symbols to do logical operation that is … and, or
  • 41. Range and Lazy Generator
  • 42. Range and Lazy Generator range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(3, 10) # [3, 4, 5, 6, 7, 8, 9] range(1, 20, 3) # [1, 4, 7, 10, 13, 16, 19] xrange(10) xrange(3, 10) xrange(1, 20, 3)
  • 45. Conditional Statement if number = input("Enter Number: ") if number > 0: print "Number is Positive" elif number < 0: print "Number is Negative" else: print "Number is Zero"
  • 46. Conditional Statement if number = input("Enter Number: ") if number > 0: print "Number is Positive" elif number < 0: print "Number is Negative" else: print "Number is Zero" result = (number % 2 == 0) ? 'Even' : 'Odd'
  • 47. Conditional Statement if number = input("Enter Number: ") if number > 0: print "Number is Positive" elif number < 0: print "Number is Negative" else: print "Number is Zero" result = 'Even' if number % 2 is 0 else 'Odd'
  • 48. Conditional Statement if number = input("Enter Number: ") if number > 0: print "Number is Positive" elif number < 0: print "Number is Negative" else: print "Number is Zero" result = 'Even' if number % 2 is 0 else 'Odd'
  • 50. Iteration Statement for for i in xrange(1, 11): print i**2
  • 51. Iteration Statement for for i in xrange(1, 11): print i**2 socials = ['Facebook', 'Twitter'] for social in socials: print 'I played %s' % social
  • 52. Iteration Statement for for i in xrange(1, 11): print i**2 socials = ['Facebook', 'Twitter'] for social in socials: print 'I played %s' % social message = 'Hello, CPSU' for letter in message: print letter
  • 53. Iteration Statement for for i in xrange(1, 11): print i**2 socials = ['Facebook', 'Twitter'] for social in socials: print 'I played %s' % social message = 'Hello, CPSU' for letter in message: print letter # Endless Loop # while True: # Do something
  • 54. Problem#1: Most Letter Count Hint: You can get list of alphabets with this code import string ! alphabets = list(string.lowercase)
  • 56. Function def function_name(params): # Do something # Do anything
  • 57. Function def function_name(params): # Do something # Do anything def fibonacci(n): fibo = 0 for k in xrange(0, int(math.floor((n - 1) / 2)) + 1): fibo += math.factorial(n - k - 1) / (math.factorial(k) * math.factorial(n - k - 1 - k)) return fibo
  • 58. Function def function_name(params): # Do something # Do anything def fibonacci(n): fibo = 0 for k in xrange(0, int(math.floor((n - 1) / 2)) + 1): fibo += math.factorial(n - k - 1) / (math.factorial(k) * math.factorial(n - k - 1 - k)) return fibo def colorMultiply(r, g=0, b=0): return [ r * 3.14159, g * 1.414, b * 3.27 ]
  • 60. Problem#2: Make a Palindrome StringgnirtS emordnilaP Way Too Long Words Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.! Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.! This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.! Thus, "localization" will be spelt as "l10n", and "internationalization will be spelt as “i18n".! and make Palindrome from that word after that :) http://codeforces.com/problemset/problem/71/A
  • 62. Indexing and Slice message = 'Hello, world' message[0] # H message[len(message) - 1] # d message[-1] # d
  • 63. Indexing and Slice message = 'Hello, world' message[0] # H message[len(message) - 1] # d message[-1] # d fibo = [1, 1, 2, 3, 5, 8, 13, 21, 34] fibo[:5] # [1, 1, 2, 3, 5] fibo[2:] # [2, 3, 5, 8, 13, 21, 34] fibo[3:6] # [3, 5, 8, 13] fibo[::2] # [1, 2, 5, 13, 34]
  • 64. Indexing and Slice message = 'Hello, world' message[0] # H message[len(message) - 1] # d message[-1] # d fibo = [1, 1, 2, 3, 5, 8, 13, 21, 34] fibo[:5] # [1, 1, 2, 3, 5] fibo[2:] # [2, 3, 5, 8, 13, 21, 34] fibo[3:6] # [3, 5, 8, 13] fibo[::2] # [1, 2, 5, 13, 34] fibo[::-1] # ??? message[::-1] # ???
  • 65. String and Collections methods Demo!
  • 66. List Comprehensive The Other way to create and manipulation Python’s List
  • 67. List Comprehensive The Other way to create and manipulation Python’s List [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  • 68. List Comprehensive The Other way to create and manipulation Python’s List [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] squares = [] for x in range(10): squares.append(x**2)
  • 69. List Comprehensive The Other way to create and manipulation Python’s List [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] squares = [x**2 for x in range(10)]
  • 70. List Comprehensive The Other way to create and manipulation Python’s List [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] squares = [x**2 for x in range(10)] set1 = [1, 2, 3] set2 = [3, 1, 4]
  • 71. List Comprehensive The Other way to create and manipulation Python’s List [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] squares = [x**2 for x in range(10)] set1 = [1, 2, 3] set2 = [3, 1, 4] combs = [] for x in set1: for y in set2: if x != y: comb.append((x, y))
  • 72. List Comprehensive The Other way to create and manipulation Python’s List [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] squares = [x**2 for x in range(10)] set1 = [1, 2, 3] set2 = [3, 1, 4] combs = [(x, y) for x in set1 for y in set2 if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
  • 73. List Comprehensive The Other way to create and manipulation Python’s List [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] squares = [x**2 for x in range(10)] set1 = [1, 2, 3] set2 = [3, 1, 4] combs = [(x, y) for x in set1 for y in set2 if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
  • 74. List Comprehensive The Other way to create and manipulation Python’s List [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] squares = [x**2 for x in range(10)] set1 = [1, 2, 3] set2 = [3, 1, 4] combs = [(x, y) for x in set1 for y in set2 if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
  • 75. List Comprehensive The Other way to create and manipulation Python’s List [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] squares = [x**2 for x in range(10)] set1 = [1, 2, 3] set2 = [3, 1, 4] combs = [(x, y) for x in set1 for y in set2 if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
  • 77. Working with File open('filename', mode) # r: open file for read # w: open file for write # a: open file for append
  • 78. Working with File open('filename', mode) # r: open file for read # w: open file for write # a: open file for append f = open('data.txt', r) f.read() # read file to string f.readline() # read file for one line f.readlines() # read file to lines
  • 79. Working with File open('filename', mode) # r: open file for read # w: open file for write # a: open file for append f = open('data.txt', r) f.read() # read file to string f.readline() # read file for one line f.readlines() # read file to lines f.write('this is a cat') # write string to file f.writelines([list of line]) # write lines to file
  • 83. Object Oriented Programming class Book: def __init__(self, name, size): self.name = name self.size = size class BookStack: def __init__(self): self.books = [] self.top = 0 def push(self, book): self.books.append(book) self.top += 1 def pop(self): self.top -= 1 return self.books.pop() !
  • 85.
  • 86.
  • 87. Unit Test import unittest ! TestBookStack(unittest.TestCase): class # when book is created, it can return name, size def test_book_created(self): hunger_book = Book('The Hunger Games', 4) self.assertEqual(hunger_book.name, 'The Hunger Games') self.assertEqual(hunger_book.size, 4) # when Book Stack is created / top is 0 def test_book_stack_created(self): book_stack = BookStack() self.assertEqual(book_stack.top, 0) self.assertEqual(book_stack.books, []) # when push book / top increase by one def test_book_stack_push(self): hunger_book = Book('The Hunger Games', 4) book_stack = BookStack() book_stack.push(hunger_book) self.assertEqual(book_stack.top, 1) self.assertEqual(book_stack.books[0].name, 'The Hunger Games') book_stack.push(hunger_book) self.assertEqual(book_stack.top, 2) # when pop book / top decrease by one def test_book_stack_pop(self): hunger_book = Book('The Hunger Games', 4) harry_book = Book('Harry Potter', 3) book_stack = BookStack() book_stack.push(hunger_book) book_stack.push(harry_book) present_size = book_stack.top poped_book = book_stack.pop() self.assertEqual(book_stack.top, present_size - 1) self.assertEqual(poped_book.name, 'Harry Potter') if __name__ == '__main__': unittest.main()
  • 88. Keep Calm and Code Python Problem#3: Books Instruction:! ! - Using TDD!! ! - Each Book have a name, size! ! - Books have size and all of book! ! Test case:! ! - paste the new book on top! ! - pick a book at top of books! ! - when paste new book you must take a larger book to below! ! - program can tell a present Books size
  • 89. Migrate to Python 3 ❖ print is function instead of statement! ❖ input()! ❖ range instead of xrange! ❖ more usage on lazy generator