SlideShare a Scribd company logo
PyLecture4 -Python Basics2-
 Write following python script with your text
editor.
 Then, run ‘python your_script.py’
 If you got ‘Hello World’, go on to the next
slide.
def main():
print ‘Hello World’
if __name__ == ‘__main__’:
main()
 Lists – compound data type
l = [1,2,3,5] # defines a list contains 1, 2, 3, 5
print l[0] # getting a value
l[0] = 6 # setting a value
l.append(7) # adding to list
print l # will print ‘[6, 2, 3, 5, 7]’
l.extend([8, 9, 10]) # connecting another list
print l # will print ‘[6, 2, 3, 5, 7, 8, 9, 10]’
print range(3) # stops at 2
print range(1, 3) # starts at 1 and stops at 2
print range(0, 5, 2) # start: 1 stop: 4 and steps by 2
 Create following lists with range function.
1. [0, 1, 2, 3, 4]
2. [3, 4, 5, 6, 7]
3. [3, 6, 9, 12, 15, 18]
4. [2, 4, 6, 8, 12, 16, 20] hint: use + operator
 Answer:
1. range(5)
2. range(3, 8)
3. range(3, 21, 3)
4. range(2, 10, 2) + range(12, 24, 4)
 Dictionaries – compound data type
 Found in other languages as “map”,
“associative memories”, or “associative arrays”
 Lists vs Dictionaries
› You can use only integer number as index on lists
Like a[0], a[-1]
› You can use integer numbers and strings as key on
dictionaries(if its value exists)
Like d[0], d[‘foo’], d[‘bar’]
 Creating a dictionary
tel = {‘John’:8000, ‘Jane’:8001, ‘Joe’:8002}
 Adding key and value
tel[‘Joan’] = 8003
 Getting value from key
tel[‘Jane’]
 Setting value from key
tel[‘Joe’] = 0004
 Removing value from key
del tel[‘John’]
 Getting key list of a dictionary
tel.keys()
 Crate a dictionary from two lists
names = [‘John’, ‘Jane’, ‘Joe’]
tel = [8000, 8001, 8002]
tel = dict(zip(names, tel))
 Create a dictionary that
› Keys are [0, 1, …, 10]
› Values are (key) * 2
› i.e. d[0]=0, d[1]=2, d[2]=4, …, d[10]=20
 Answer:
k = range(11)
v = range(0, 11*2, 2)
d = dict(zip(k, v))
 Logical Operator
 if statements
 for statements
 Compares two values
print 1 < 2
print 1 > 2
print 1 == 2
print 1 <= 2
print 1 >= 2
 And, Or, and Not
print 1 < 2 and 1 == 2
print 1 < 2 or 1 > 2
print not 1 == 2
x = int(raw_input(‘value of x: ’))
if x < 0:
print(‘x is negative’) # must indent
elif x > 0:
print(‘x is positive’)
else:
print(‘x is not positive neither negative’)
print(‘i.e. x is zero’)
For integer variable named ‘x’,
› Print ‘fizz’ if x can be divided by 3
› Print ‘buzz’ if x can be divided by 5
(e.g. if x is 10, print ‘buzz’, x is 15, print ‘fizz buzz’)
(hint: use % operator(e.g. 10 % 3 = 1, 14 % 5 = 4))
x = int(raw_input('x value:'))
if x % 3 == 0:
print 'fizz'
if x % 5 == 0:
print 'buzz'
n = int(raw_input(‘list length: ’))
l = []
for i in range(n): # for each number in (0…n-1)
l.append(raw_input(‘%dth word: ’ % i))
for w in l: # for each word in your list
print w
Create a list only contains
› Multiple of 3 or 5 (3, 5, 6, 9…)
› Between 1 and 20
i.e. [3, 5, 6, 9, 10, 12, 15, 18, 20]
l = []
for i in range(1, 21):
if i % 3 == 0 or i % 5 == 0:
l.append(i)
print l
 Defining a function
def add(a, b):
return a + b
 Calling the function
print add(10, 2)
 Recursive call
def factorial(n):
if n <= 0:
return 1
else:
return n * factorial(n-1)
 Find the 10-th Fibonacci sequence
› Fibonacci sequence is
 0, 1, 1, 2, 3, 5, 8, …
 The next number is found by adding up the two
numbers before it(e.g. 5th number 3 = 2 + 1).
def fib(n):
if n <= 1:
return 0
elif n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
print fib(10)

More Related Content

What's hot (20)

PDF
令和から本気出す
Takashi Kitano
 
PDF
Taking Perl to Eleven with Higher-Order Functions
David Golden
 
PDF
Elixir & Phoenix – fast, concurrent and explicit
Tobias Pfeiffer
 
PDF
Elixir & Phoenix – fast, concurrent and explicit
Tobias Pfeiffer
 
PDF
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland
 
PDF
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
Takashi Kitano
 
PPT
An Elephant of a Different Colour: Hack
Vic Metcalfe
 
PPTX
Python PCEP Operations On Lists
IHTMINSTITUTE
 
PDF
Webmontag Berlin "coffee script"
Webmontag Berlin
 
PDF
Python idioms
Sofian Hadiwijaya
 
PDF
Closure, Higher-order function in Swift
SeongGyu Jo
 
PDF
{shiny}と{leaflet}による地図アプリ開発Tips
Takashi Kitano
 
PPTX
PHP string-part 1
monikadeshmane
 
PDF
Favouring Composition - The Groovy Way
Naresha K
 
PDF
WordPress 3.1 at DC PHP
andrewnacin
 
PPTX
Python chapter 2
Raghu nath
 
PPTX
python chapter 1
Raghu nath
 
PDF
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
Takashi Kitano
 
PPTX
Database performance 101
Leon Fayer
 
PDF
Templating you're doing it wrong - Nikolas Martens - Codemotion Amsterdam 2017
Codemotion
 
令和から本気出す
Takashi Kitano
 
Taking Perl to Eleven with Higher-Order Functions
David Golden
 
Elixir & Phoenix – fast, concurrent and explicit
Tobias Pfeiffer
 
Elixir & Phoenix – fast, concurrent and explicit
Tobias Pfeiffer
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland
 
{tidytext}と{RMeCab}によるモダンな日本語テキスト分析
Takashi Kitano
 
An Elephant of a Different Colour: Hack
Vic Metcalfe
 
Python PCEP Operations On Lists
IHTMINSTITUTE
 
Webmontag Berlin "coffee script"
Webmontag Berlin
 
Python idioms
Sofian Hadiwijaya
 
Closure, Higher-order function in Swift
SeongGyu Jo
 
{shiny}と{leaflet}による地図アプリ開発Tips
Takashi Kitano
 
PHP string-part 1
monikadeshmane
 
Favouring Composition - The Groovy Way
Naresha K
 
WordPress 3.1 at DC PHP
andrewnacin
 
Python chapter 2
Raghu nath
 
python chapter 1
Raghu nath
 
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
Takashi Kitano
 
Database performance 101
Leon Fayer
 
Templating you're doing it wrong - Nikolas Martens - Codemotion Amsterdam 2017
Codemotion
 

Viewers also liked (14)

PDF
Oratoria
Paula Andrea
 
PPTX
Pelajaran5
Firda_123
 
PPTX
Pelajaran4
Firda_123
 
PDF
How Docker didn't invent containers (Docker Meetup Brno #1)
Pavel Snajdr
 
PPTX
KEPERCAYAAN GURU
NurAlias91
 
DOCX
công ty thiết kế phim quảng cáo nhanh nhất
evette568
 
PPTX
Top 8 internet marketing specialist resume samples
hallerharry710
 
ODP
Galaxy royale
Dhra Sharma
 
PPTX
Ace city
Dhra Sharma
 
PDF
La Representacion Grafica
Alejandra Gamboa
 
DOC
Carlito N. Siervo Jr
Carlito Jr Siervo
 
PDF
Terril Application Developer
Terril Thomas
 
PDF
when you forget your password
Corneliu Dascălu
 
PPT
Advertising agencies
Shrey Oberoi
 
Oratoria
Paula Andrea
 
Pelajaran5
Firda_123
 
Pelajaran4
Firda_123
 
How Docker didn't invent containers (Docker Meetup Brno #1)
Pavel Snajdr
 
KEPERCAYAAN GURU
NurAlias91
 
công ty thiết kế phim quảng cáo nhanh nhất
evette568
 
Top 8 internet marketing specialist resume samples
hallerharry710
 
Galaxy royale
Dhra Sharma
 
Ace city
Dhra Sharma
 
La Representacion Grafica
Alejandra Gamboa
 
Carlito N. Siervo Jr
Carlito Jr Siervo
 
Terril Application Developer
Terril Thomas
 
when you forget your password
Corneliu Dascălu
 
Advertising agencies
Shrey Oberoi
 
Ad

Similar to PyLecture4 -Python Basics2- (20)

PDF
Python Part 1
Mohamed Ramadan
 
PDF
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
PPTX
Python.pptx
AshaS74
 
PDF
python_lab_manual_final (1).pdf
keerthu0442
 
PDF
Python_ 3 CheatSheet
Dr. Volkan OBAN
 
PDF
Mementopython3 english
ssuser442080
 
PDF
Python3
Sourodip Kundu
 
PDF
Mementopython3 english
yassminkhaldi1
 
PDF
Python3 cheatsheet
Gil Cohen
 
PDF
Introduction to python cheat sheet for all
shwetakushwaha45
 
ODP
Python basics
Himanshu Awasthi
 
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
PPTX
Python bible
adarsh j
 
PDF
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
PDF
GE3151_PSPP_UNIT_4_Notes
Guru Nanak Technical Institutions
 
PDF
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
PDF
python.pdf
wekarep985
 
PDF
Python for High School Programmers
Siva Arunachalam
 
PDF
Python Cheat Sheet
Muthu Vinayagam
 
Python Part 1
Mohamed Ramadan
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
Python.pptx
AshaS74
 
python_lab_manual_final (1).pdf
keerthu0442
 
Python_ 3 CheatSheet
Dr. Volkan OBAN
 
Mementopython3 english
ssuser442080
 
Mementopython3 english
yassminkhaldi1
 
Python3 cheatsheet
Gil Cohen
 
Introduction to python cheat sheet for all
shwetakushwaha45
 
Python basics
Himanshu Awasthi
 
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
Python bible
adarsh j
 
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
GE3151_PSPP_UNIT_4_Notes
Guru Nanak Technical Institutions
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
python.pdf
wekarep985
 
Python for High School Programmers
Siva Arunachalam
 
Python Cheat Sheet
Muthu Vinayagam
 
Ad

More from Yoshiki Satotani (7)

PPTX
Basic practice of R
Yoshiki Satotani
 
PPTX
Basic use of Python (Practice)
Yoshiki Satotani
 
PPTX
Basic use of Python
Yoshiki Satotani
 
PDF
Py lecture5 python plots
Yoshiki Satotani
 
PDF
PyLecture2 -NetworkX-
Yoshiki Satotani
 
PDF
PyLecture1 -Python Basics-
Yoshiki Satotani
 
PDF
PyLecture3 -json-
Yoshiki Satotani
 
Basic practice of R
Yoshiki Satotani
 
Basic use of Python (Practice)
Yoshiki Satotani
 
Basic use of Python
Yoshiki Satotani
 
Py lecture5 python plots
Yoshiki Satotani
 
PyLecture2 -NetworkX-
Yoshiki Satotani
 
PyLecture1 -Python Basics-
Yoshiki Satotani
 
PyLecture3 -json-
Yoshiki Satotani
 

Recently uploaded (20)

PDF
Rewards and Recognition (2).pdf
ethan Talor
 
PPTX
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
PDF
Difference Between Kubernetes and Docker .pdf
Kindlebit Solutions
 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
PDF
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
PDF
LPS25 - Operationalizing MLOps in GEP - Terradue.pdf
terradue
 
PDF
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
 
PPTX
EO4EU Ocean Monitoring: Maritime Weather Routing Optimsation Use Case
EO4EU
 
PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
 
PPTX
Introduction to web development | MERN Stack
JosephLiyon
 
PDF
Building scalbale cloud native apps with .NET 8
GillesMathieu10
 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
PDF
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
PPTX
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
 
PPTX
Seamless-Image-Conversion-From-Raster-to-wrt-rtx-rtx.pptx
Quick Conversion Services
 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
PDF
>Wondershare Filmora Crack Free Download 2025
utfefguu
 
Rewards and Recognition (2).pdf
ethan Talor
 
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
Difference Between Kubernetes and Docker .pdf
Kindlebit Solutions
 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
LPS25 - Operationalizing MLOps in GEP - Terradue.pdf
terradue
 
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
 
EO4EU Ocean Monitoring: Maritime Weather Routing Optimsation Use Case
EO4EU
 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
 
Introduction to web development | MERN Stack
JosephLiyon
 
Building scalbale cloud native apps with .NET 8
GillesMathieu10
 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
 
Seamless-Image-Conversion-From-Raster-to-wrt-rtx-rtx.pptx
Quick Conversion Services
 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
>Wondershare Filmora Crack Free Download 2025
utfefguu
 

PyLecture4 -Python Basics2-

  • 2.  Write following python script with your text editor.  Then, run ‘python your_script.py’  If you got ‘Hello World’, go on to the next slide. def main(): print ‘Hello World’ if __name__ == ‘__main__’: main()
  • 3.  Lists – compound data type l = [1,2,3,5] # defines a list contains 1, 2, 3, 5 print l[0] # getting a value l[0] = 6 # setting a value l.append(7) # adding to list print l # will print ‘[6, 2, 3, 5, 7]’ l.extend([8, 9, 10]) # connecting another list print l # will print ‘[6, 2, 3, 5, 7, 8, 9, 10]’
  • 4. print range(3) # stops at 2 print range(1, 3) # starts at 1 and stops at 2 print range(0, 5, 2) # start: 1 stop: 4 and steps by 2
  • 5.  Create following lists with range function. 1. [0, 1, 2, 3, 4] 2. [3, 4, 5, 6, 7] 3. [3, 6, 9, 12, 15, 18] 4. [2, 4, 6, 8, 12, 16, 20] hint: use + operator
  • 6.  Answer: 1. range(5) 2. range(3, 8) 3. range(3, 21, 3) 4. range(2, 10, 2) + range(12, 24, 4)
  • 7.  Dictionaries – compound data type  Found in other languages as “map”, “associative memories”, or “associative arrays”  Lists vs Dictionaries › You can use only integer number as index on lists Like a[0], a[-1] › You can use integer numbers and strings as key on dictionaries(if its value exists) Like d[0], d[‘foo’], d[‘bar’]
  • 8.  Creating a dictionary tel = {‘John’:8000, ‘Jane’:8001, ‘Joe’:8002}  Adding key and value tel[‘Joan’] = 8003  Getting value from key tel[‘Jane’]  Setting value from key tel[‘Joe’] = 0004  Removing value from key del tel[‘John’]  Getting key list of a dictionary tel.keys()
  • 9.  Crate a dictionary from two lists names = [‘John’, ‘Jane’, ‘Joe’] tel = [8000, 8001, 8002] tel = dict(zip(names, tel))
  • 10.  Create a dictionary that › Keys are [0, 1, …, 10] › Values are (key) * 2 › i.e. d[0]=0, d[1]=2, d[2]=4, …, d[10]=20
  • 11.  Answer: k = range(11) v = range(0, 11*2, 2) d = dict(zip(k, v))
  • 12.  Logical Operator  if statements  for statements
  • 13.  Compares two values print 1 < 2 print 1 > 2 print 1 == 2 print 1 <= 2 print 1 >= 2  And, Or, and Not print 1 < 2 and 1 == 2 print 1 < 2 or 1 > 2 print not 1 == 2
  • 14. x = int(raw_input(‘value of x: ’)) if x < 0: print(‘x is negative’) # must indent elif x > 0: print(‘x is positive’) else: print(‘x is not positive neither negative’) print(‘i.e. x is zero’)
  • 15. For integer variable named ‘x’, › Print ‘fizz’ if x can be divided by 3 › Print ‘buzz’ if x can be divided by 5 (e.g. if x is 10, print ‘buzz’, x is 15, print ‘fizz buzz’) (hint: use % operator(e.g. 10 % 3 = 1, 14 % 5 = 4))
  • 16. x = int(raw_input('x value:')) if x % 3 == 0: print 'fizz' if x % 5 == 0: print 'buzz'
  • 17. n = int(raw_input(‘list length: ’)) l = [] for i in range(n): # for each number in (0…n-1) l.append(raw_input(‘%dth word: ’ % i)) for w in l: # for each word in your list print w
  • 18. Create a list only contains › Multiple of 3 or 5 (3, 5, 6, 9…) › Between 1 and 20 i.e. [3, 5, 6, 9, 10, 12, 15, 18, 20]
  • 19. l = [] for i in range(1, 21): if i % 3 == 0 or i % 5 == 0: l.append(i) print l
  • 20.  Defining a function def add(a, b): return a + b  Calling the function print add(10, 2)
  • 21.  Recursive call def factorial(n): if n <= 0: return 1 else: return n * factorial(n-1)
  • 22.  Find the 10-th Fibonacci sequence › Fibonacci sequence is  0, 1, 1, 2, 3, 5, 8, …  The next number is found by adding up the two numbers before it(e.g. 5th number 3 = 2 + 1).
  • 23. def fib(n): if n <= 1: return 0 elif n == 2: return 1 else: return fib(n-1) + fib(n-2) print fib(10)