SlideShare a Scribd company logo
… loops…
… loops …
… loops …
… & …
… lists …
The plan!
Basics: data types (and operations & calculations)
Basics: conditionals & iteration
Basics: lists, tuples, dictionaries
Basics: writing functions
Reading & writing files: opening, parsing & formats
Working with numbers: numpy & scipy
Making plots: matplotlib & pylab
… if you guys want more after all of that …
Writing better code: functions, pep8, classes
Working with numbers: Numpy & Scipy (advanced)
Other modules: Pandas & Scikit-learn
Interactive notebooks: ipython & jupyter
Advanced topics: virtual environments & version control
for … in … range
# the basic “for - in - range” loop
for x in range(stop):
code to repeat goes here…
it can be as long as you want!
and include, ifs, other loops, etc..
again, indentation is
everything in python!
# three ways to create a range
… range(stop)
… range(start, stop)
… range(start, stop, step)
(stop - 1)
okay, some exercises with loops
Basic practice:
- Write a script that asks the user for two numbers and calculates:
- The sum of all numbers between the two.
- Write a script that asks the user for a single number and calculates:
- The sum of all even numbers between 0 and that number.
A little more complex:
- Write a script that asks the user for a single number and calculates whether or not
the number is prime.
- Write a script that asks the user for a single number and finds all prime numbers
less than that number.
the “while loop”
---- file contents ----
# adding numbers, until we reach 100
total = 0
while total <= 100:
n = int(raw_input(“Please write a number:”))
total = total + n
print “The total exceeded 100. It is:”, total
the “while loop”
---- file contents ----
# adding numbers, until we reach 100
total = 0
while total <= 100:
n = int(raw_input(“Please write a number:”))
total = total + n
print “The total exceeded 100. It is:”, total
# adding numbers, until we reach 100
user_input = “”
while user_input != “stop”:
user_input = raw_input(“Type ‘stop’ to stop:”)
# the basic “while ” loop
while boolean:
code goes here
again, indentation!
the “while loop”
---- file contents ----
# adding numbers, until we reach 100
total = 0
while total <= 100:
n = int(raw_input(“Please write a number:”))
total = total + n
print “The total exceeded 100. It is:”, total
# adding numbers, until we reach 100
user_input = “”
while user_input != “stop”:
user_input = raw_input(“Type ‘stop’ to stop:”)
# the basic “while ” loop
while boolean:
code goes here
again, indentation!
NEVER use while loops!
okay… not “never”, but a “for loop” is
almost always better!
Let’s write the following variants of the lion/chair/hungry program. They start as
above, but:
- If the ‘user’ does not write ‘yes’ or ‘no’ when answering ‘hungry?’, keeps on asking
them for some useful information.
okay, juuuust one exercise using “while”
# the beginning of the lion / hungry program from last week…
chairs = int(raw_input(“How many chairs do you have?:”))
lions = int(raw_input(“How many lions are there?:”))
hungry = raw_input(“Are the lions hungry? (yes/no)?:”)
… etc…
data types for multiple things...
lists
[ 1, 2, 3, 100, 99 , 50]
strings
“wait, we already know these!”
tuples
(10, 11, 12, 100, 90, 80)
dictionaries
… we’ll get to those later…
lists!
---- file contents ----
# define a list like any other variable
# using “[” and “]” and commas:
numbers = [1, 2, 3]
print type(numbers)
# lists can contain different data...
mylist = [1, 2.0, 50.0, True, “wow”, 70, “that’s cool!”]
# lists can even have lists as elements!
awesome = [‘A’, ‘B’, [5, 3, 1], “amazing”, [“stuff”, “with”, “lists”]]
# lists can also be defined using variables (of course)
pi = 3.14
a = 100
mega_list = [50, 40, a, pi, 1, mylist]
indexing and slicing
---- file contents ----
# lets define a list…
numbers = [1, 2, “a”, “b”, 99, 98]
# indexing: find the 2nd
element in the list:
print numbers[1]
# remember, we start counting at 0 :)
# slicing: find the first 3 elements:
print numbers[:3]
# yap, also “n-1”
# slicing: ignore the first three elements:
print numbers[3:]
print numbers[3:5]
# what about negative numbers?
print numbers[-2]
# reassignment
numbers[3] = “X”
what about strings?
---- file contents ----
# lets define a string
mystring = “What if a string is basically a list of characters?”
# indexing and slicing on strings:
print mystring[8:]
print mystring[20:36]
# but … this won’t work...
mystring[8] = “A”
what about strings?
---- file contents ----
# lets define a string
mystring = “What if a string is basically a list of characters?”
# indexing and slicing on strings:
print mystring[8:]
print mystring[20:36]
# but … this won’t work...
mystring[8] = “A”
list
a “mutable object” (i.e., we can change the list
after creating it)
string
an “immutable object” (and cannot be
changed after creation).
what about tuples?
---- file contents ----
# lets define a tuple:
# note the “(” and “)”
sometuple = (1, 2, “A”, “B”, 100.0)
print type(sometuple)
# indexing and slicing on tuples:
print sometuple[3]
print sometuple[:3]
# this also won’t work...
sometuple[2] = “X”
# muuuuch better
somelist = list(sometuple)
what about tuples?
---- file contents ----
# lets define a tuple:
# note the “(” and “)”
sometuple = (1, 2, “A”, “B”, 100.0)
print type(sometuple)
# indexing and slicing on tuples:
print sometuple[3]
print sometuple[:3]
# this also won’t work...
sometuple[2] = “X”
# muuuuch better
somelist = list(sometuple)
tuple
is basically an “immutable” list. Its values
cannot be changed after creation.
what about tuples?
---- file contents ----
# lets define a tuple:
# note the “(” and “)”
sometuple = (1, 2, “A”, “B”, 100.0)
print type(sometuple)
# indexing and slicing on tuples:
print sometuple[3]
print sometuple[:3]
# this also won’t work...
sometuple[2] = “X”
# muuuuch better
somelist = list(sometuple)
tuple
is basically an “immutable” list. Its values
cannot be changed after creation.
don't use tuples
They just confuse you. Unless you
have a really good reason to make to
define an immutable object...
what about pancakes?
---- pancakes.py ----
# lets define a list of pancakes:
pancakes = [“strawberry”, “chocolate”,
“pineapple”, “chocolate”, “sugar”, “cream”]
# finding an element: index()
print pancakes.index(“sugar”)
print pancakes.count(“chocolate”)
# removing an element: remove()
pancakes.remove(“sugar”)
# removing and storing the last element: ()
popped = pancakes.pop()
print pancakes
print popped
# removing and storing the an element by position: ()
popped = pancakes.pop(2)
print pancakes
print popped
Using an existing list with methods:
mylist.method()
Finding things:
.index(element) ← first only
.count(element)
Removing things:
.pop(<pos>) ← returns element
.remove(element) ← first only
Adding things:
.append(element)
.insert(<pos>, element)
.extend(newlist)
Not a method, but also useful: len(list)
what about pancakes?
---- pancakes.py (cont) ----
# adding an element to the end: append
pancakes.append(“cherry”)
# inserting an element to the beginning
pancakes.insert(“kiwi”)
# inserting an element anywhere
pancakes.insert(3, “more kiwi”)
print pancakes
# extending one list with another
newlist = [“cheese”, “bacon”]
pancakes.extend(newlist)
print pancakes
# getting the length
print len(pancakes)
Using an existing list with methods:
mylist.method()
Finding things:
.index(element) ← first only
.count(element)
Removing things:
.pop(<pos>) ← returns element
.remove(element)
Adding things:
.append(element)
.insert(<pos>, element)
.extend(newlist)
Not a method, but also useful: len(list)
copying lists
---- file contents ----
# making a copy of a list:
morecakes = pancakes
pancakes.append(“banana”)
print pancakes
print morecakes
copying lists
---- file contents ----
# making a copy of a list:
morecakes = pancakes
pancakes.append(“banana”)
print pancakes
print morecakes
# use list() or [:] to copy a list:
anothercakes = list(pancakes)
anothercakes.remove(“banana”)
print anothercakes
print pancakes
“=” does not copy a list!
list2 = list1 ← are the same list
… use:
list2 = list(list1)
list2 = list1[:]
exercises!
Here is a hamburger:
First, let's remove ingredients that don’t make sense. Then, add some ingredients, and
put them into the place you think they belong. Add (at least): Tomatoes, Salad, cheese.
hamburger = ["bread", "burger", "chocolate", "bread"] # left is the bottom, right is the top :)
lists, loops and conditionals
---- somefile.py ----
# lets take a close look at “range”:
a = range(10)
print type(a) # (note: different in python 3)
# using lists in loops:
a = [1, 2, “a”, “b”, “hello”, 3.0, 99]
for element in a:
print element, “is of type:”, type(element)
# using lists in tests and conditionals:
mylist = [1, 2, “a”, “b”, “hello”, 99]
print “is a in the list:”, a in mylist
for a in range(100):
if a in mylist:
print a, “is in the list!”
Using in with lists:
for var in list:
do stuff in loop
if var in list:
do “True” block
else:
do “False” block
- How many ingredients are there in total?
- Are there any in the “stack” which are not in “pancakes” or “hamburger”? (add
these to the correct list)
- By majority vote: is it a pancake or hamburger?
hamcake!
# you should be able to copy-paste this :)
stack = [
"chocolate", "strawberries", "salad", "chocolate", "salad", "cheese", "cream", "cheese", "tomatoes", "bacon", "bacon", "tomatoes", "burger", "onions", "cheese",
"banana", "pineapple", "tomatoes", "bacon", "cheese", "burger", "salad", "tomatoes", "onions", "chocolate", "pineapple", "tomatoes", "onions", "salad",
"strawberries",
"egg", "cheese", "tomatoes", "burger", "bacon", "cream", "sugar", "burger", "ketchup", "salad", "chocolate", "cream", "egg", "sugar", "salad", "pineapple", "bacon",
"cheese", "bacon",
]
pancake = [ "chocolate", "strawberries", "chocolate", "salad", "cream", "pineapple", "sugar",]
hamburger = [ "tomatoes", "bacon", "cheese", "burger", "salad", "onions", "egg", ]
Ad

More Related Content

What's hot (20)

Python Workshop
Python  Workshop Python  Workshop
Python Workshop
Assem CHELLI
 
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
climatewarrior
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
Narong Intiruk
 
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
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentation
Nimrita Koul
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
Variables In Php 1
Variables In Php 1Variables In Php 1
Variables In Php 1
Digital Insights - Digital Marketing Agency
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
Robert Lujo
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
Pedro Rodrigues
 
Python- strings
Python- stringsPython- strings
Python- strings
Krishna Nanda
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
Chan Shik Lim
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
Rohan Gupta
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Declarative Thinking, Declarative Practice
Declarative Thinking, Declarative PracticeDeclarative Thinking, Declarative Practice
Declarative Thinking, Declarative Practice
Kevlin Henney
 
Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.
Alamgir Hossain
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
Matt Harrison
 
Python basic
Python basic Python basic
Python basic
sewoo lee
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기
JangHyuk You
 
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
climatewarrior
 
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
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentation
Nimrita Koul
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
Robert Lujo
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
Pedro Rodrigues
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
Chan Shik Lim
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
Rohan Gupta
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Declarative Thinking, Declarative Practice
Declarative Thinking, Declarative PracticeDeclarative Thinking, Declarative Practice
Declarative Thinking, Declarative Practice
Kevlin Henney
 
Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.
Alamgir Hossain
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
Matt Harrison
 
Python basic
Python basic Python basic
Python basic
sewoo lee
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기
JangHyuk You
 

Viewers also liked (11)

Class 3: if/else
Class 3: if/elseClass 3: if/else
Class 3: if/else
Marc Gouw
 
Class 4: For and while
Class 4: For and whileClass 4: For and while
Class 4: For and while
Marc Gouw
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
Marc Gouw
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & Matplotlib
Marc Gouw
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programming
Marc Gouw
 
Class 8a: Modules and imports
Class 8a: Modules and importsClass 8a: Modules and imports
Class 8a: Modules and imports
Marc Gouw
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
Marc Gouw
 
Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/O
Marc Gouw
 
Introduction to SlideShare for Businesses
Introduction to SlideShare for BusinessesIntroduction to SlideShare for Businesses
Introduction to SlideShare for Businesses
SlideShare
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
SlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
SlideShare
 
Class 3: if/else
Class 3: if/elseClass 3: if/else
Class 3: if/else
Marc Gouw
 
Class 4: For and while
Class 4: For and whileClass 4: For and while
Class 4: For and while
Marc Gouw
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
Marc Gouw
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & Matplotlib
Marc Gouw
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programming
Marc Gouw
 
Class 8a: Modules and imports
Class 8a: Modules and importsClass 8a: Modules and imports
Class 8a: Modules and imports
Marc Gouw
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
Marc Gouw
 
Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/O
Marc Gouw
 
Introduction to SlideShare for Businesses
Introduction to SlideShare for BusinessesIntroduction to SlideShare for Businesses
Introduction to SlideShare for Businesses
SlideShare
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
SlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
SlideShare
 
Ad

Similar to Class 5: If, while & lists (20)

Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
O T
 
Python cheatsheet for beginners
Python cheatsheet for beginnersPython cheatsheet for beginners
Python cheatsheet for beginners
Lahore Garrison University
 
1. python
1. python1. python
1. python
PRASHANT OJHA
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
NawalKishore38
 
python cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningpython cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learning
TURAGAVIJAYAAKASH
 
Beginner's Python Cheat Sheet
Beginner's Python Cheat SheetBeginner's Python Cheat Sheet
Beginner's Python Cheat Sheet
Verxus
 
2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf
MeghanaDBengalur
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdf
ElNew2
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
Ravi Kiran Khareedi
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.
Python Meetup
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
mohitesoham12
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
aiclub_slides
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
anzhong70
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
juzihua1102
 
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILECOMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
Anushka Rai
 
cover every basics of python with this..
cover every basics of python with this..cover every basics of python with this..
cover every basics of python with this..
karkimanish411
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
O T
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
NawalKishore38
 
python cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningpython cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learning
TURAGAVIJAYAAKASH
 
Beginner's Python Cheat Sheet
Beginner's Python Cheat SheetBeginner's Python Cheat Sheet
Beginner's Python Cheat Sheet
Verxus
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdf
ElNew2
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.
Python Meetup
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
mohitesoham12
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
aiclub_slides
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
anzhong70
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
juzihua1102
 
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILECOMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
Anushka Rai
 
cover every basics of python with this..
cover every basics of python with this..cover every basics of python with this..
cover every basics of python with this..
karkimanish411
 
Ad

Recently uploaded (20)

ANTI URINARY TRACK INFECTION AGENT MC III
ANTI URINARY TRACK INFECTION AGENT MC IIIANTI URINARY TRACK INFECTION AGENT MC III
ANTI URINARY TRACK INFECTION AGENT MC III
HRUTUJA WAGH
 
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
Sérgio Sacani
 
MC III Prodrug Medicinal Chemistry III PPT
MC III Prodrug Medicinal Chemistry III PPTMC III Prodrug Medicinal Chemistry III PPT
MC III Prodrug Medicinal Chemistry III PPT
HRUTUJA WAGH
 
Seismic evidence of liquid water at the base of Mars' upper crust
Seismic evidence of liquid water at the base of Mars' upper crustSeismic evidence of liquid water at the base of Mars' upper crust
Seismic evidence of liquid water at the base of Mars' upper crust
Sérgio Sacani
 
Freud e sua Historia na Psicanalise Psic
Freud e sua Historia na Psicanalise PsicFreud e sua Historia na Psicanalise Psic
Freud e sua Historia na Psicanalise Psic
StefannyGoffi1
 
Macrolide and Miscellaneous Antibiotics.ppt
Macrolide and Miscellaneous Antibiotics.pptMacrolide and Miscellaneous Antibiotics.ppt
Macrolide and Miscellaneous Antibiotics.ppt
HRUTUJA WAGH
 
THE SENSORY ORGANS BY DR. SADAKAT BASHIR.pptx
THE SENSORY ORGANS BY DR. SADAKAT BASHIR.pptxTHE SENSORY ORGANS BY DR. SADAKAT BASHIR.pptx
THE SENSORY ORGANS BY DR. SADAKAT BASHIR.pptx
SadakatBashir
 
Funakoshi_ZymoResearch_2024-2025_catalog
Funakoshi_ZymoResearch_2024-2025_catalogFunakoshi_ZymoResearch_2024-2025_catalog
Funakoshi_ZymoResearch_2024-2025_catalog
fu7koshi
 
physics of renewable energy sources .pptx
physics of renewable energy sources  .pptxphysics of renewable energy sources  .pptx
physics of renewable energy sources .pptx
zaramunir6
 
Cordaitales - Yudhvir Singh Checked[1].pptx gymnosperms
Cordaitales - Yudhvir Singh Checked[1].pptx gymnospermsCordaitales - Yudhvir Singh Checked[1].pptx gymnosperms
Cordaitales - Yudhvir Singh Checked[1].pptx gymnosperms
ReetikaMakkar
 
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.pptSULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
HRUTUJA WAGH
 
Mycology:Characteristics of Ascomycetes Fungi
Mycology:Characteristics of Ascomycetes FungiMycology:Characteristics of Ascomycetes Fungi
Mycology:Characteristics of Ascomycetes Fungi
SAYANTANMALLICK5
 
Somato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptxSomato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptx
klynct
 
Chapter-10-Light-reflection-and-refraction.ppt
Chapter-10-Light-reflection-and-refraction.pptChapter-10-Light-reflection-and-refraction.ppt
Chapter-10-Light-reflection-and-refraction.ppt
uniyaladiti914
 
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptxA CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
ANJALICHANDRASEKARAN
 
Electroencephalogram_ wave components_Aignificancr
Electroencephalogram_ wave components_AignificancrElectroencephalogram_ wave components_Aignificancr
Electroencephalogram_ wave components_Aignificancr
klynct
 
Integration of AI and ML in Biotechnology
Integration of AI and ML in BiotechnologyIntegration of AI and ML in Biotechnology
Integration of AI and ML in Biotechnology
Sourabh Junawa
 
Meiosis Notes Slides biology powerpoint.pptx
Meiosis Notes Slides biology powerpoint.pptxMeiosis Notes Slides biology powerpoint.pptx
Meiosis Notes Slides biology powerpoint.pptx
sbates3
 
Green Synthesis of Gold Nanoparticles.pptx
Green Synthesis of Gold Nanoparticles.pptxGreen Synthesis of Gold Nanoparticles.pptx
Green Synthesis of Gold Nanoparticles.pptx
Torskal Nanoscience
 
class 7 polygenic inheritance.pptx biochemistry
class 7 polygenic inheritance.pptx biochemistryclass 7 polygenic inheritance.pptx biochemistry
class 7 polygenic inheritance.pptx biochemistry
LavanyaVijaykumar2
 
ANTI URINARY TRACK INFECTION AGENT MC III
ANTI URINARY TRACK INFECTION AGENT MC IIIANTI URINARY TRACK INFECTION AGENT MC III
ANTI URINARY TRACK INFECTION AGENT MC III
HRUTUJA WAGH
 
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
Sérgio Sacani
 
MC III Prodrug Medicinal Chemistry III PPT
MC III Prodrug Medicinal Chemistry III PPTMC III Prodrug Medicinal Chemistry III PPT
MC III Prodrug Medicinal Chemistry III PPT
HRUTUJA WAGH
 
Seismic evidence of liquid water at the base of Mars' upper crust
Seismic evidence of liquid water at the base of Mars' upper crustSeismic evidence of liquid water at the base of Mars' upper crust
Seismic evidence of liquid water at the base of Mars' upper crust
Sérgio Sacani
 
Freud e sua Historia na Psicanalise Psic
Freud e sua Historia na Psicanalise PsicFreud e sua Historia na Psicanalise Psic
Freud e sua Historia na Psicanalise Psic
StefannyGoffi1
 
Macrolide and Miscellaneous Antibiotics.ppt
Macrolide and Miscellaneous Antibiotics.pptMacrolide and Miscellaneous Antibiotics.ppt
Macrolide and Miscellaneous Antibiotics.ppt
HRUTUJA WAGH
 
THE SENSORY ORGANS BY DR. SADAKAT BASHIR.pptx
THE SENSORY ORGANS BY DR. SADAKAT BASHIR.pptxTHE SENSORY ORGANS BY DR. SADAKAT BASHIR.pptx
THE SENSORY ORGANS BY DR. SADAKAT BASHIR.pptx
SadakatBashir
 
Funakoshi_ZymoResearch_2024-2025_catalog
Funakoshi_ZymoResearch_2024-2025_catalogFunakoshi_ZymoResearch_2024-2025_catalog
Funakoshi_ZymoResearch_2024-2025_catalog
fu7koshi
 
physics of renewable energy sources .pptx
physics of renewable energy sources  .pptxphysics of renewable energy sources  .pptx
physics of renewable energy sources .pptx
zaramunir6
 
Cordaitales - Yudhvir Singh Checked[1].pptx gymnosperms
Cordaitales - Yudhvir Singh Checked[1].pptx gymnospermsCordaitales - Yudhvir Singh Checked[1].pptx gymnosperms
Cordaitales - Yudhvir Singh Checked[1].pptx gymnosperms
ReetikaMakkar
 
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.pptSULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
HRUTUJA WAGH
 
Mycology:Characteristics of Ascomycetes Fungi
Mycology:Characteristics of Ascomycetes FungiMycology:Characteristics of Ascomycetes Fungi
Mycology:Characteristics of Ascomycetes Fungi
SAYANTANMALLICK5
 
Somato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptxSomato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptx
klynct
 
Chapter-10-Light-reflection-and-refraction.ppt
Chapter-10-Light-reflection-and-refraction.pptChapter-10-Light-reflection-and-refraction.ppt
Chapter-10-Light-reflection-and-refraction.ppt
uniyaladiti914
 
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptxA CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
ANJALICHANDRASEKARAN
 
Electroencephalogram_ wave components_Aignificancr
Electroencephalogram_ wave components_AignificancrElectroencephalogram_ wave components_Aignificancr
Electroencephalogram_ wave components_Aignificancr
klynct
 
Integration of AI and ML in Biotechnology
Integration of AI and ML in BiotechnologyIntegration of AI and ML in Biotechnology
Integration of AI and ML in Biotechnology
Sourabh Junawa
 
Meiosis Notes Slides biology powerpoint.pptx
Meiosis Notes Slides biology powerpoint.pptxMeiosis Notes Slides biology powerpoint.pptx
Meiosis Notes Slides biology powerpoint.pptx
sbates3
 
Green Synthesis of Gold Nanoparticles.pptx
Green Synthesis of Gold Nanoparticles.pptxGreen Synthesis of Gold Nanoparticles.pptx
Green Synthesis of Gold Nanoparticles.pptx
Torskal Nanoscience
 
class 7 polygenic inheritance.pptx biochemistry
class 7 polygenic inheritance.pptx biochemistryclass 7 polygenic inheritance.pptx biochemistry
class 7 polygenic inheritance.pptx biochemistry
LavanyaVijaykumar2
 

Class 5: If, while & lists

  • 1. … loops… … loops … … loops … … & … … lists …
  • 2. The plan! Basics: data types (and operations & calculations) Basics: conditionals & iteration Basics: lists, tuples, dictionaries Basics: writing functions Reading & writing files: opening, parsing & formats Working with numbers: numpy & scipy Making plots: matplotlib & pylab … if you guys want more after all of that … Writing better code: functions, pep8, classes Working with numbers: Numpy & Scipy (advanced) Other modules: Pandas & Scikit-learn Interactive notebooks: ipython & jupyter Advanced topics: virtual environments & version control
  • 3. for … in … range # the basic “for - in - range” loop for x in range(stop): code to repeat goes here… it can be as long as you want! and include, ifs, other loops, etc.. again, indentation is everything in python! # three ways to create a range … range(stop) … range(start, stop) … range(start, stop, step) (stop - 1)
  • 4. okay, some exercises with loops Basic practice: - Write a script that asks the user for two numbers and calculates: - The sum of all numbers between the two. - Write a script that asks the user for a single number and calculates: - The sum of all even numbers between 0 and that number. A little more complex: - Write a script that asks the user for a single number and calculates whether or not the number is prime. - Write a script that asks the user for a single number and finds all prime numbers less than that number.
  • 5. the “while loop” ---- file contents ---- # adding numbers, until we reach 100 total = 0 while total <= 100: n = int(raw_input(“Please write a number:”)) total = total + n print “The total exceeded 100. It is:”, total
  • 6. the “while loop” ---- file contents ---- # adding numbers, until we reach 100 total = 0 while total <= 100: n = int(raw_input(“Please write a number:”)) total = total + n print “The total exceeded 100. It is:”, total # adding numbers, until we reach 100 user_input = “” while user_input != “stop”: user_input = raw_input(“Type ‘stop’ to stop:”) # the basic “while ” loop while boolean: code goes here again, indentation!
  • 7. the “while loop” ---- file contents ---- # adding numbers, until we reach 100 total = 0 while total <= 100: n = int(raw_input(“Please write a number:”)) total = total + n print “The total exceeded 100. It is:”, total # adding numbers, until we reach 100 user_input = “” while user_input != “stop”: user_input = raw_input(“Type ‘stop’ to stop:”) # the basic “while ” loop while boolean: code goes here again, indentation! NEVER use while loops! okay… not “never”, but a “for loop” is almost always better!
  • 8. Let’s write the following variants of the lion/chair/hungry program. They start as above, but: - If the ‘user’ does not write ‘yes’ or ‘no’ when answering ‘hungry?’, keeps on asking them for some useful information. okay, juuuust one exercise using “while” # the beginning of the lion / hungry program from last week… chairs = int(raw_input(“How many chairs do you have?:”)) lions = int(raw_input(“How many lions are there?:”)) hungry = raw_input(“Are the lions hungry? (yes/no)?:”) … etc…
  • 9. data types for multiple things... lists [ 1, 2, 3, 100, 99 , 50] strings “wait, we already know these!” tuples (10, 11, 12, 100, 90, 80) dictionaries … we’ll get to those later…
  • 10. lists! ---- file contents ---- # define a list like any other variable # using “[” and “]” and commas: numbers = [1, 2, 3] print type(numbers) # lists can contain different data... mylist = [1, 2.0, 50.0, True, “wow”, 70, “that’s cool!”] # lists can even have lists as elements! awesome = [‘A’, ‘B’, [5, 3, 1], “amazing”, [“stuff”, “with”, “lists”]] # lists can also be defined using variables (of course) pi = 3.14 a = 100 mega_list = [50, 40, a, pi, 1, mylist]
  • 11. indexing and slicing ---- file contents ---- # lets define a list… numbers = [1, 2, “a”, “b”, 99, 98] # indexing: find the 2nd element in the list: print numbers[1] # remember, we start counting at 0 :) # slicing: find the first 3 elements: print numbers[:3] # yap, also “n-1” # slicing: ignore the first three elements: print numbers[3:] print numbers[3:5] # what about negative numbers? print numbers[-2] # reassignment numbers[3] = “X”
  • 12. what about strings? ---- file contents ---- # lets define a string mystring = “What if a string is basically a list of characters?” # indexing and slicing on strings: print mystring[8:] print mystring[20:36] # but … this won’t work... mystring[8] = “A”
  • 13. what about strings? ---- file contents ---- # lets define a string mystring = “What if a string is basically a list of characters?” # indexing and slicing on strings: print mystring[8:] print mystring[20:36] # but … this won’t work... mystring[8] = “A” list a “mutable object” (i.e., we can change the list after creating it) string an “immutable object” (and cannot be changed after creation).
  • 14. what about tuples? ---- file contents ---- # lets define a tuple: # note the “(” and “)” sometuple = (1, 2, “A”, “B”, 100.0) print type(sometuple) # indexing and slicing on tuples: print sometuple[3] print sometuple[:3] # this also won’t work... sometuple[2] = “X” # muuuuch better somelist = list(sometuple)
  • 15. what about tuples? ---- file contents ---- # lets define a tuple: # note the “(” and “)” sometuple = (1, 2, “A”, “B”, 100.0) print type(sometuple) # indexing and slicing on tuples: print sometuple[3] print sometuple[:3] # this also won’t work... sometuple[2] = “X” # muuuuch better somelist = list(sometuple) tuple is basically an “immutable” list. Its values cannot be changed after creation.
  • 16. what about tuples? ---- file contents ---- # lets define a tuple: # note the “(” and “)” sometuple = (1, 2, “A”, “B”, 100.0) print type(sometuple) # indexing and slicing on tuples: print sometuple[3] print sometuple[:3] # this also won’t work... sometuple[2] = “X” # muuuuch better somelist = list(sometuple) tuple is basically an “immutable” list. Its values cannot be changed after creation. don't use tuples They just confuse you. Unless you have a really good reason to make to define an immutable object...
  • 17. what about pancakes? ---- pancakes.py ---- # lets define a list of pancakes: pancakes = [“strawberry”, “chocolate”, “pineapple”, “chocolate”, “sugar”, “cream”] # finding an element: index() print pancakes.index(“sugar”) print pancakes.count(“chocolate”) # removing an element: remove() pancakes.remove(“sugar”) # removing and storing the last element: () popped = pancakes.pop() print pancakes print popped # removing and storing the an element by position: () popped = pancakes.pop(2) print pancakes print popped Using an existing list with methods: mylist.method() Finding things: .index(element) ← first only .count(element) Removing things: .pop(<pos>) ← returns element .remove(element) ← first only Adding things: .append(element) .insert(<pos>, element) .extend(newlist) Not a method, but also useful: len(list)
  • 18. what about pancakes? ---- pancakes.py (cont) ---- # adding an element to the end: append pancakes.append(“cherry”) # inserting an element to the beginning pancakes.insert(“kiwi”) # inserting an element anywhere pancakes.insert(3, “more kiwi”) print pancakes # extending one list with another newlist = [“cheese”, “bacon”] pancakes.extend(newlist) print pancakes # getting the length print len(pancakes) Using an existing list with methods: mylist.method() Finding things: .index(element) ← first only .count(element) Removing things: .pop(<pos>) ← returns element .remove(element) Adding things: .append(element) .insert(<pos>, element) .extend(newlist) Not a method, but also useful: len(list)
  • 19. copying lists ---- file contents ---- # making a copy of a list: morecakes = pancakes pancakes.append(“banana”) print pancakes print morecakes
  • 20. copying lists ---- file contents ---- # making a copy of a list: morecakes = pancakes pancakes.append(“banana”) print pancakes print morecakes # use list() or [:] to copy a list: anothercakes = list(pancakes) anothercakes.remove(“banana”) print anothercakes print pancakes “=” does not copy a list! list2 = list1 ← are the same list … use: list2 = list(list1) list2 = list1[:]
  • 21. exercises! Here is a hamburger: First, let's remove ingredients that don’t make sense. Then, add some ingredients, and put them into the place you think they belong. Add (at least): Tomatoes, Salad, cheese. hamburger = ["bread", "burger", "chocolate", "bread"] # left is the bottom, right is the top :)
  • 22. lists, loops and conditionals ---- somefile.py ---- # lets take a close look at “range”: a = range(10) print type(a) # (note: different in python 3) # using lists in loops: a = [1, 2, “a”, “b”, “hello”, 3.0, 99] for element in a: print element, “is of type:”, type(element) # using lists in tests and conditionals: mylist = [1, 2, “a”, “b”, “hello”, 99] print “is a in the list:”, a in mylist for a in range(100): if a in mylist: print a, “is in the list!” Using in with lists: for var in list: do stuff in loop if var in list: do “True” block else: do “False” block
  • 23. - How many ingredients are there in total? - Are there any in the “stack” which are not in “pancakes” or “hamburger”? (add these to the correct list) - By majority vote: is it a pancake or hamburger? hamcake! # you should be able to copy-paste this :) stack = [ "chocolate", "strawberries", "salad", "chocolate", "salad", "cheese", "cream", "cheese", "tomatoes", "bacon", "bacon", "tomatoes", "burger", "onions", "cheese", "banana", "pineapple", "tomatoes", "bacon", "cheese", "burger", "salad", "tomatoes", "onions", "chocolate", "pineapple", "tomatoes", "onions", "salad", "strawberries", "egg", "cheese", "tomatoes", "burger", "bacon", "cream", "sugar", "burger", "ketchup", "salad", "chocolate", "cream", "egg", "sugar", "salad", "pineapple", "bacon", "cheese", "bacon", ] pancake = [ "chocolate", "strawberries", "chocolate", "salad", "cream", "pineapple", "sugar",] hamburger = [ "tomatoes", "bacon", "cheese", "burger", "salad", "onions", "egg", ]
  翻译: