SlideShare a Scribd company logo
Programming with
Python
                    Week 2
Dept. of Electrical Engineering and Computer Science
Academic Year 2010-2011
Week 1 - Highlights


• In Python, everything is an object.
• In Python, you never explicitly specify the datatype
  of anything.
• Based on what value you assign, Python keeps track
  of the datatype internally.
Week 1 - Highlights
• just indent and get on with your life.
• indentation is a language requirement. not a matter of
  style.
• Python uses carriage return to separate statements.
• Python uses a colon and indentation to separate code
  blocks.
  :
            ...
Mannerism: Dropbox usage


• Use Shared Dropbox folder more responsibly.
• Think of your friends.
• Think before you act.
Week 2
3.1 Introducing
Dictionaries

• Dictionary is a built-in datatype of Python.
• It defines a one-to-one relationship between keys and
  values.
• One-to-one relationship? Let’s see with a useful
  example.
One-to-one relationship?

• http://maps.google.com/maps/place?
  cid=12784366278796637370&q=Wells+Fargo+Bank
  +near+Union+Street,+SF,+CA,+United
  +States&hl=en&dtab=0&sll=37.798984,-122.421915&ssp
  n=0.006295,0.03601&ie=UTF8&ll=37.817446,-122.4536
  13&spn=0,0&z=14
  Relationship:          shortened to by

• http://bit.ly/f2bSMH
Takeaway I: It's much easier to include

Key --> Value                                 the shorter link in an email or Twitter
                                              post without it breaking or taking up
                                              space.




 Takeaway II: bit.ly works by issuing a "301 redirect". When you shorten a link with bit.ly,
 you are redirecting a click from bit.ly to the destination URL. A 301 redirect is the most
 efficient and search engine-friendly method for webpage redirection.
3.1.1 Defining Dictionaries


• >>> d = {“bruce”: “lee”, “mortal”: “kombat”}
                                                 }
                                 {
• >>> d
  {'bruce': 'lee', 'mortal': 'kombat'}
• >>> d["bruce"]
  'lee'
Rules, rules, rules
• You can not have duplicate keys in a dictionary. Assigning
  a value to an existing key will wipe out the old value.
• You can add new key-value pairs at any time. This syntax
  is identical to modifying existing values.
• Be careful: you may be adding new values but are
  actually just modifying the same value over and over
  because your key isn't changing the way you think it is.
• Dictionaries are unordered.
• Dictionary keys are case-sensitive.
3.1.2 Modifying dictionaries
& case-sensitivity



                                     K
• >>> d = {}
• >>> d = {“key” : “value”}
• >>> d


                                     k
  {'key': 'value'}
• >>> d[“Key”] = “Value”
• >>> d
  {'Key': 'Value', 'key': 'value'}
Shepherd’s
salad of datatypes
• >>> d={"bruce":"lee","mortal":"kombat"}
• >>> d["air force"] = 1
• >>> d
  {'bruce': 'lee', 'air force': 1, 'mortal': 'kombat'}
• >>> d[2]="two"
• >>> d
  {'bruce': 'lee', 2: 'two', 'air force': 1, 'mortal': 'kombat'}
Dictionaries

• Dictionaries are NOT just for strings.
• Dictionary values can be any datatype. Within a single
  dictionary, you can have values of different datatypes.
• Dictionary keys are more restricted: strings and
  integers are mostly used (note: there are some others
  too).
3.1.3 Deleting Items
from Dictionaries
• >>> d
  {'bruce': 'lee', 2: 'two', 'air force': 1, 'mortal': 'kombat'}
• >>> del d[2]
• >>> d
  {'bruce': 'lee', 'air force': 1, 'mortal': 'kombat'}
• >>> d.clear()
• >>> d
  {}
3.2 Introducing Lists



• Shopping cart is a list.
Grocery list is a list.
Things to do is a list.
3.2.1 Defining Lists
• >>> li=["armani watch","hunting with the
  moon","amazon kindle","iphone 4"]
• >>> li
  ['armani watch', 'hunting with the moon', 'amazon
  kindle', 'iphone 4']
• >>> li[0]
  'armani watch'
• >>> li[3]
  'iphone 4'
Lists are

             , , ,]
• ordered.  [
• enclosed in square brackets.
• having their first element start at index 0.
Two way access
• Forward:
                 li[0]                                      li[3]


 li = ["armani watch","hunting with the moon","amazon kindle","iphone 4"]




• Backward:
                 li[-1]                                         li[-4]
Slicing a list


                                                 :3 ]
• Reading the list from left to right:
                                         [ 1
  i. the first slice index specifies the first element you
  want,
  ii. the second slice index specifies the first element you
  don't want,
  iii. the return value is everything in between.
Slicing at work

• >>> li
  ['armani watch', 'hunting with the moon', 'amazon
  kindle', 'iphone 4']
• >>> li[1:3]
  ['hunting with the moon', 'amazon kindle']
• >>> li[0:0] Ask in class...
Assuming list length is n

• li[:3] is the same as li[0:3].
• li[3:] is the same as li[3:n], where n is the length of the
  list.
• li[:n] will always return the first n elements.
• li[:] is shorthand for making a complete copy of a list: all
  elements of the original list are included. But this is not
  the same as the original li list; it is a new list that has the
  same elements.
3.2.1 Adding elements to
Lists

• >>> li
  ['armani watch', 'hunting with the moon', 'amazon
  kindle', 'iphone 4']
• >>> li.append("ipad 32gb wifi+3g")
• >>> li
  ['armani watch', 'hunting with the moon', 'amazon
  kindle', 'iphone 4', 'ipad 32gb wifi+3g']
3.2.1 Adding elements to
Lists

• >>> li
  ['armani watch', 'hunting with the moon', 'amazon
  kindle', 'iphone 4', 'ipad 32gb wifi+3g']
• >>> li.insert(1,”macbook pro”)
• >>> li
  ['armani watch', 'macbook pro', 'hunting with the moon',
  'amazon kindle', 'iphone 4', 'ipad 32gb wifi+3g']
3.2.1 Adding elements to
Lists
• >>> li
  ['armani watch', 'macbook pro', 'hunting with the moon',
  'amazon kindle', 'iphone 4', 'ipad 32gb wifi+3g']
• >>> li.extend(["zoolander dvd","v for vendetta
  dvd","gladiator dvd"])
• >>> li
  ['armani watch', 'macbook pro', 'hunting with the moon',
  'amazon kindle', 'iphone 4', 'ipad 32gb wifi+3g',
  'zoolander dvd', 'v for vendetta dvd', 'gladiator dvd']
Difference between extend
and append
• >>> li=["a","b","c"]          • >>> del li[3]
• >>> li                        • >>> li
  ['a', 'b', 'c']                 ['a', 'b', 'c']

• >>> li.append            • >>> li.extend(["d","e"])
• >>> li.append(["d","e"]) • >>>'b', 'c', 'd', 'e']
                             ['a',
                                   li

• >>> li
  ['a', 'b', 'c', ['d', 'e']]
3.2.3 Searching a List
• >>> li                      • >>> “c” in li
  ['a', 'b', 'c', 'd', 'e']      True
• >>> li                      • >>> “f” in li
  ['a', 'b', 'c', 'd', 'e']      False
• >>> li.index("a")           • >>> li.index(“g”) call last):
  0                             Traceback (most recent
                                 File "<pyshell#47>", line 1, in
• >>> li.index("e")              <module>
                                 li.index("g")
  4
                                 ValueError: list.index(x): x not in list
• >>> “c” in li
3.2.4 Deleting List elements
•   >>> li
    ['a', 'b', 'c', 'd', 'e']

•   >>> li.remove("a")

•   >>> li
    ['b', 'c', 'd', 'e']

•   >>> li.remove("f")
    Traceback (most recent call last): File "<pyshell#51>", line 1, in
    <module> li.remove("f") ValueError: list.remove(x): x not in list

•   >>> li.pop()
    'e'
3.2.5 Using List operators

• >>> li
  ['b', 'c', 'd']
• >>> li = ["a"] + li
• >>> li
  ['a', 'b', 'c', 'd']
• >>> li += ["e","f"]
• >>> li
  ['a', 'b', 'c', 'd', 'e', 'f']
3.2.5 Using List operators
  extend
• >>> li
  ['b', 'c', 'd']
                                           ext
                                         fas
                                    larg ter is
                                               end
• >>> li = ["a"] + li              an    e li for
• >>> li                                     sts
                                       in- . it
  ['a', 'b', 'c', 'd']
                                   op pla is
• >>> li += ["e","f"]                 era        ce
• >>> li                                  tio
  ['a', 'b', 'c', 'd', 'e', 'f']              n.
3.3 Introducing Tuples




                                     ,)
• A tuple is an immutable list.



                                 , ,
• A tuple cannot be changed once it is created.



                               (
Tuples have no methods



immutable
Tuples are good for?



• Tuples are faster than lists.
• Working with read-only data makes your code safer.
  Implicit write-protection.
• Note that tuples can be converted into lists and vice-
  versa.
3.4 Declaring Variables

• Python has local and global variables like most other
  languages, but it has no explicit variable
  declarations.
• Variables spring into existence by being assigned a
  value, and they are automatically destroyed when they
  go out of scope.
• Python will not allow you to reference a variable that
  has never been assigned a value; trying to do so will
  raise an exception.
VARIABLES


 VALUE
        = 1
 ASSIGNMENT
3.4.2 Assigning
multiple values at once

• >>> tuple_t = ('eecs',211)
• >>> (dept,course_code)=tuple_t
• >>> dept
  'eecs'
• >>> course_code
  211
Tuples are good for?



• Tuples are used in multi-variable assignment.
3.5 Formatting Strings

• >>> m = “mortal”
• >>> k = “kombat”
• >>> “%s %s” % (m,k)
  'mortal kombat'


• note the usage of tuples here as well.
                                           %
String formatting vs.
String concatenation


• >>> li
  ['a', 'b', 'c', 'd', 'e', 'f']
• >>> len(li)
  6
                                   %d
• >>> print "The length of the list is: %d" % (len(li),)
  The length of the list is: 6
String concatenation



                                                   +
• >>> print "The length of the list is: " + (len(li))
  Traceback (most recent call last):
   File "<pyshell#74>", line 1, in <module>
     print "The length of the list is: " + (len(li))
  TypeError: cannot concatenate 'str' and 'int' objects
• >>> print “mortal” + “ kombat”
  mortal kombat
• string concatenation works only when everything is
  already a string.
Formatting numbers
                                     %f
• >>> print "Today's stock price: %f" % 50.4625
  Today's stock price: 50.462500
• >>> print "Today's stock price: %.2f" % 50.4625
  Today's stock price: 50.46
• >>> print "Change since yesterday: %+.2f" % 1.5
  Change since yesterday: +1.50
3.6 Mapping Lists

• One of the most powerful features of Python is the list
  comprehension, which provides a compact way of
  mapping a list into another list by applying a function
  to each of the elements of the list.
• >>> l_numbers = [1,2,3,4]
• >>> [element*2 for element in l_numbers]
  [2, 4, 6, 8]
List comprehension
step by step
•   >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa",
    "pwd":"secret"}

•   >>> params.items()
    [('pwd', 'secret'), ('database', 'master'), ('uid', 'sa'), ('server', 'mpilgrim')]

•   >>> [k for k, v in params.items()]


•
    ['pwd', 'database', 'uid', 'server']
    >>> [v for k, v in params.items()]
                                                    tuples
    ['secret', 'master', 'sa', 'mpilgrim']

•   >>> ["%s=%s" % (k, v) for k, v in params.items()]
    ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim']
3.7 Joining Lists and
Splitting Strings

• To join any list of strings into a single string, use the join
  method of a string object.
• >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])
  'pwd=secret;database=master;uid=sa;server=mpilgrim'
• join works only on lists of strings; it does not do any
  type coercion. Joining a list that has one or more non-
  string elements will raise an exception.
3.7 Joining Lists and
Splitting Strings
• >>> li = ";".join(["%s=%s" % (k, v) for k, v in
  params.items()])
• >>> li
  'pwd=secret;database=master;uid=sa;server=mpilgrim'
• >>> li.split(";")
  ['pwd=secret', 'database=master', 'uid=sa',
  'server=mpilgrim']
• Ask in class.. what do you notice?
Remember Your First
Python Program




                      odbchelper.py
Dr. Ahmet Bulut took this picture in NYC during when he was
interning at IBM T.J.Watson Research Center in August 2004.

More Related Content

What's hot (19)

Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
 
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
Matt Harrison
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
Megha V
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
1. python
1. python1. python
1. python
PRASHANT OJHA
 
Standard data-types-in-py
Standard data-types-in-pyStandard data-types-in-py
Standard data-types-in-py
Priyanshu Sengar
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
 
String in python lecture (3)
String in python lecture (3)String in python lecture (3)
String in python lecture (3)
Ali ٍSattar
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
SivaSankar Gorantla
 
Python
PythonPython
Python
Kumar Gaurav
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
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
Matt Harrison
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
Megha V
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
String in python lecture (3)
String in python lecture (3)String in python lecture (3)
String in python lecture (3)
Ali ٍSattar
 

Viewers also liked (6)

Bilisim 2010 @ bura
Bilisim 2010 @ buraBilisim 2010 @ bura
Bilisim 2010 @ bura
Ahmet Bulut
 
Ecosystem for Scholarly Work
Ecosystem for Scholarly WorkEcosystem for Scholarly Work
Ecosystem for Scholarly Work
Ahmet Bulut
 
Agile Software Development
Agile Software DevelopmentAgile Software Development
Agile Software Development
Ahmet Bulut
 
ESX Server from VMware
ESX Server from VMwareESX Server from VMware
ESX Server from VMware
Ahmet Bulut
 
Liselerde tanıtım sunumu
Liselerde tanıtım sunumuLiselerde tanıtım sunumu
Liselerde tanıtım sunumu
Ahmet Bulut
 
Bilisim 2010 @ bura
Bilisim 2010 @ buraBilisim 2010 @ bura
Bilisim 2010 @ bura
Ahmet Bulut
 
Ecosystem for Scholarly Work
Ecosystem for Scholarly WorkEcosystem for Scholarly Work
Ecosystem for Scholarly Work
Ahmet Bulut
 
Agile Software Development
Agile Software DevelopmentAgile Software Development
Agile Software Development
Ahmet Bulut
 
ESX Server from VMware
ESX Server from VMwareESX Server from VMware
ESX Server from VMware
Ahmet Bulut
 
Liselerde tanıtım sunumu
Liselerde tanıtım sunumuLiselerde tanıtım sunumu
Liselerde tanıtım sunumu
Ahmet Bulut
 
Ad

Similar to Programming with Python - Week 2 (20)

Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
GDSCKYAMBOGO
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 
Meaning of Dictionary in python language
Meaning of Dictionary in python languageMeaning of Dictionary in python language
Meaning of Dictionary in python language
PRASHANTMISHRA16761
 
Python Basics it will teach you about data types
Python Basics it will teach you about data typesPython Basics it will teach you about data types
Python Basics it will teach you about data types
NimitSinghal2
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
Module-3.pptx
Module-3.pptxModule-3.pptx
Module-3.pptx
Manohar Nelli
 
Python study material
Python study materialPython study material
Python study material
Satish Nagabhushan
 
UNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering studentsUNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering students
SabarigiriVason
 
Python course
Python coursePython course
Python course
Евгений Сазонов
 
Learning python
Learning pythonLearning python
Learning python
Young Alista
 
Learning python
Learning pythonLearning python
Learning python
Luis Goldster
 
Learning python
Learning pythonLearning python
Learning python
Harry Potter
 
Learning python
Learning pythonLearning python
Learning python
James Wong
 
Learning python
Learning pythonLearning python
Learning python
Fraboni Ec
 
Learning python
Learning pythonLearning python
Learning python
Tony Nguyen
 
Learning python
Learning pythonLearning python
Learning python
Hoang Nguyen
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
Simplilearn
 
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdfPy4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
horiamommand
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdf
AUNGHTET61
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
GDSCKYAMBOGO
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 
Meaning of Dictionary in python language
Meaning of Dictionary in python languageMeaning of Dictionary in python language
Meaning of Dictionary in python language
PRASHANTMISHRA16761
 
Python Basics it will teach you about data types
Python Basics it will teach you about data typesPython Basics it will teach you about data types
Python Basics it will teach you about data types
NimitSinghal2
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
UNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering studentsUNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering students
SabarigiriVason
 
Learning python
Learning pythonLearning python
Learning python
James Wong
 
Learning python
Learning pythonLearning python
Learning python
Fraboni Ec
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
Simplilearn
 
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdfPy4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
horiamommand
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdf
AUNGHTET61
 
Ad

More from Ahmet Bulut (11)

Nose Dive into Apache Spark ML
Nose Dive into Apache Spark MLNose Dive into Apache Spark ML
Nose Dive into Apache Spark ML
Ahmet Bulut
 
Data Economy: Lessons learned and the Road ahead!
Data Economy: Lessons learned and the Road ahead!Data Economy: Lessons learned and the Road ahead!
Data Economy: Lessons learned and the Road ahead!
Ahmet Bulut
 
Apache Spark Tutorial
Apache Spark TutorialApache Spark Tutorial
Apache Spark Tutorial
Ahmet Bulut
 
A Few Tips for the CS Freshmen
A Few Tips for the CS FreshmenA Few Tips for the CS Freshmen
A Few Tips for the CS Freshmen
Ahmet Bulut
 
Agile Data Science
Agile Data ScienceAgile Data Science
Agile Data Science
Ahmet Bulut
 
Data Science
Data ScienceData Science
Data Science
Ahmet Bulut
 
What is open source?
What is open source?What is open source?
What is open source?
Ahmet Bulut
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
Ahmet Bulut
 
Startup Execution Models
Startup Execution ModelsStartup Execution Models
Startup Execution Models
Ahmet Bulut
 
I feel dealsy
I feel dealsyI feel dealsy
I feel dealsy
Ahmet Bulut
 
Virtualization @ Sehir
Virtualization @ SehirVirtualization @ Sehir
Virtualization @ Sehir
Ahmet Bulut
 
Nose Dive into Apache Spark ML
Nose Dive into Apache Spark MLNose Dive into Apache Spark ML
Nose Dive into Apache Spark ML
Ahmet Bulut
 
Data Economy: Lessons learned and the Road ahead!
Data Economy: Lessons learned and the Road ahead!Data Economy: Lessons learned and the Road ahead!
Data Economy: Lessons learned and the Road ahead!
Ahmet Bulut
 
Apache Spark Tutorial
Apache Spark TutorialApache Spark Tutorial
Apache Spark Tutorial
Ahmet Bulut
 
A Few Tips for the CS Freshmen
A Few Tips for the CS FreshmenA Few Tips for the CS Freshmen
A Few Tips for the CS Freshmen
Ahmet Bulut
 
Agile Data Science
Agile Data ScienceAgile Data Science
Agile Data Science
Ahmet Bulut
 
What is open source?
What is open source?What is open source?
What is open source?
Ahmet Bulut
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
Ahmet Bulut
 
Startup Execution Models
Startup Execution ModelsStartup Execution Models
Startup Execution Models
Ahmet Bulut
 
Virtualization @ Sehir
Virtualization @ SehirVirtualization @ Sehir
Virtualization @ Sehir
Ahmet Bulut
 

Recently uploaded (20)

Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 

Programming with Python - Week 2

  • 1. Programming with Python Week 2 Dept. of Electrical Engineering and Computer Science Academic Year 2010-2011
  • 2. Week 1 - Highlights • In Python, everything is an object. • In Python, you never explicitly specify the datatype of anything. • Based on what value you assign, Python keeps track of the datatype internally.
  • 3. Week 1 - Highlights • just indent and get on with your life. • indentation is a language requirement. not a matter of style. • Python uses carriage return to separate statements. • Python uses a colon and indentation to separate code blocks. : ...
  • 4. Mannerism: Dropbox usage • Use Shared Dropbox folder more responsibly. • Think of your friends. • Think before you act.
  • 6. 3.1 Introducing Dictionaries • Dictionary is a built-in datatype of Python. • It defines a one-to-one relationship between keys and values. • One-to-one relationship? Let’s see with a useful example.
  • 7. One-to-one relationship? • http://maps.google.com/maps/place? cid=12784366278796637370&q=Wells+Fargo+Bank +near+Union+Street,+SF,+CA,+United +States&hl=en&dtab=0&sll=37.798984,-122.421915&ssp n=0.006295,0.03601&ie=UTF8&ll=37.817446,-122.4536 13&spn=0,0&z=14 Relationship: shortened to by • http://bit.ly/f2bSMH
  • 8. Takeaway I: It's much easier to include Key --> Value the shorter link in an email or Twitter post without it breaking or taking up space. Takeaway II: bit.ly works by issuing a "301 redirect". When you shorten a link with bit.ly, you are redirecting a click from bit.ly to the destination URL. A 301 redirect is the most efficient and search engine-friendly method for webpage redirection.
  • 9. 3.1.1 Defining Dictionaries • >>> d = {“bruce”: “lee”, “mortal”: “kombat”} } { • >>> d {'bruce': 'lee', 'mortal': 'kombat'} • >>> d["bruce"] 'lee'
  • 10. Rules, rules, rules • You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value. • You can add new key-value pairs at any time. This syntax is identical to modifying existing values. • Be careful: you may be adding new values but are actually just modifying the same value over and over because your key isn't changing the way you think it is. • Dictionaries are unordered. • Dictionary keys are case-sensitive.
  • 11. 3.1.2 Modifying dictionaries & case-sensitivity K • >>> d = {} • >>> d = {“key” : “value”} • >>> d k {'key': 'value'} • >>> d[“Key”] = “Value” • >>> d {'Key': 'Value', 'key': 'value'}
  • 12. Shepherd’s salad of datatypes • >>> d={"bruce":"lee","mortal":"kombat"} • >>> d["air force"] = 1 • >>> d {'bruce': 'lee', 'air force': 1, 'mortal': 'kombat'} • >>> d[2]="two" • >>> d {'bruce': 'lee', 2: 'two', 'air force': 1, 'mortal': 'kombat'}
  • 13. Dictionaries • Dictionaries are NOT just for strings. • Dictionary values can be any datatype. Within a single dictionary, you can have values of different datatypes. • Dictionary keys are more restricted: strings and integers are mostly used (note: there are some others too).
  • 14. 3.1.3 Deleting Items from Dictionaries • >>> d {'bruce': 'lee', 2: 'two', 'air force': 1, 'mortal': 'kombat'} • >>> del d[2] • >>> d {'bruce': 'lee', 'air force': 1, 'mortal': 'kombat'} • >>> d.clear() • >>> d {}
  • 15. 3.2 Introducing Lists • Shopping cart is a list.
  • 16. Grocery list is a list.
  • 17. Things to do is a list.
  • 18. 3.2.1 Defining Lists • >>> li=["armani watch","hunting with the moon","amazon kindle","iphone 4"] • >>> li ['armani watch', 'hunting with the moon', 'amazon kindle', 'iphone 4'] • >>> li[0] 'armani watch' • >>> li[3] 'iphone 4'
  • 19. Lists are , , ,] • ordered. [ • enclosed in square brackets. • having their first element start at index 0.
  • 20. Two way access • Forward: li[0] li[3] li = ["armani watch","hunting with the moon","amazon kindle","iphone 4"] • Backward: li[-1] li[-4]
  • 21. Slicing a list :3 ] • Reading the list from left to right: [ 1 i. the first slice index specifies the first element you want, ii. the second slice index specifies the first element you don't want, iii. the return value is everything in between.
  • 22. Slicing at work • >>> li ['armani watch', 'hunting with the moon', 'amazon kindle', 'iphone 4'] • >>> li[1:3] ['hunting with the moon', 'amazon kindle'] • >>> li[0:0] Ask in class...
  • 23. Assuming list length is n • li[:3] is the same as li[0:3]. • li[3:] is the same as li[3:n], where n is the length of the list. • li[:n] will always return the first n elements. • li[:] is shorthand for making a complete copy of a list: all elements of the original list are included. But this is not the same as the original li list; it is a new list that has the same elements.
  • 24. 3.2.1 Adding elements to Lists • >>> li ['armani watch', 'hunting with the moon', 'amazon kindle', 'iphone 4'] • >>> li.append("ipad 32gb wifi+3g") • >>> li ['armani watch', 'hunting with the moon', 'amazon kindle', 'iphone 4', 'ipad 32gb wifi+3g']
  • 25. 3.2.1 Adding elements to Lists • >>> li ['armani watch', 'hunting with the moon', 'amazon kindle', 'iphone 4', 'ipad 32gb wifi+3g'] • >>> li.insert(1,”macbook pro”) • >>> li ['armani watch', 'macbook pro', 'hunting with the moon', 'amazon kindle', 'iphone 4', 'ipad 32gb wifi+3g']
  • 26. 3.2.1 Adding elements to Lists • >>> li ['armani watch', 'macbook pro', 'hunting with the moon', 'amazon kindle', 'iphone 4', 'ipad 32gb wifi+3g'] • >>> li.extend(["zoolander dvd","v for vendetta dvd","gladiator dvd"]) • >>> li ['armani watch', 'macbook pro', 'hunting with the moon', 'amazon kindle', 'iphone 4', 'ipad 32gb wifi+3g', 'zoolander dvd', 'v for vendetta dvd', 'gladiator dvd']
  • 27. Difference between extend and append • >>> li=["a","b","c"] • >>> del li[3] • >>> li • >>> li ['a', 'b', 'c'] ['a', 'b', 'c'] • >>> li.append • >>> li.extend(["d","e"]) • >>> li.append(["d","e"]) • >>>'b', 'c', 'd', 'e'] ['a', li • >>> li ['a', 'b', 'c', ['d', 'e']]
  • 28. 3.2.3 Searching a List • >>> li • >>> “c” in li ['a', 'b', 'c', 'd', 'e'] True • >>> li • >>> “f” in li ['a', 'b', 'c', 'd', 'e'] False • >>> li.index("a") • >>> li.index(“g”) call last): 0 Traceback (most recent File "<pyshell#47>", line 1, in • >>> li.index("e") <module> li.index("g") 4 ValueError: list.index(x): x not in list • >>> “c” in li
  • 29. 3.2.4 Deleting List elements • >>> li ['a', 'b', 'c', 'd', 'e'] • >>> li.remove("a") • >>> li ['b', 'c', 'd', 'e'] • >>> li.remove("f") Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> li.remove("f") ValueError: list.remove(x): x not in list • >>> li.pop() 'e'
  • 30. 3.2.5 Using List operators • >>> li ['b', 'c', 'd'] • >>> li = ["a"] + li • >>> li ['a', 'b', 'c', 'd'] • >>> li += ["e","f"] • >>> li ['a', 'b', 'c', 'd', 'e', 'f']
  • 31. 3.2.5 Using List operators extend • >>> li ['b', 'c', 'd'] ext fas larg ter is end • >>> li = ["a"] + li an e li for • >>> li sts in- . it ['a', 'b', 'c', 'd'] op pla is • >>> li += ["e","f"] era ce • >>> li tio ['a', 'b', 'c', 'd', 'e', 'f'] n.
  • 32. 3.3 Introducing Tuples ,) • A tuple is an immutable list. , , • A tuple cannot be changed once it is created. (
  • 33. Tuples have no methods immutable
  • 34. Tuples are good for? • Tuples are faster than lists. • Working with read-only data makes your code safer. Implicit write-protection. • Note that tuples can be converted into lists and vice- versa.
  • 35. 3.4 Declaring Variables • Python has local and global variables like most other languages, but it has no explicit variable declarations. • Variables spring into existence by being assigned a value, and they are automatically destroyed when they go out of scope. • Python will not allow you to reference a variable that has never been assigned a value; trying to do so will raise an exception.
  • 36. VARIABLES VALUE = 1 ASSIGNMENT
  • 37. 3.4.2 Assigning multiple values at once • >>> tuple_t = ('eecs',211) • >>> (dept,course_code)=tuple_t • >>> dept 'eecs' • >>> course_code 211
  • 38. Tuples are good for? • Tuples are used in multi-variable assignment.
  • 39. 3.5 Formatting Strings • >>> m = “mortal” • >>> k = “kombat” • >>> “%s %s” % (m,k) 'mortal kombat' • note the usage of tuples here as well. %
  • 40. String formatting vs. String concatenation • >>> li ['a', 'b', 'c', 'd', 'e', 'f'] • >>> len(li) 6 %d • >>> print "The length of the list is: %d" % (len(li),) The length of the list is: 6
  • 41. String concatenation + • >>> print "The length of the list is: " + (len(li)) Traceback (most recent call last): File "<pyshell#74>", line 1, in <module> print "The length of the list is: " + (len(li)) TypeError: cannot concatenate 'str' and 'int' objects • >>> print “mortal” + “ kombat” mortal kombat • string concatenation works only when everything is already a string.
  • 42. Formatting numbers %f • >>> print "Today's stock price: %f" % 50.4625 Today's stock price: 50.462500 • >>> print "Today's stock price: %.2f" % 50.4625 Today's stock price: 50.46 • >>> print "Change since yesterday: %+.2f" % 1.5 Change since yesterday: +1.50
  • 43. 3.6 Mapping Lists • One of the most powerful features of Python is the list comprehension, which provides a compact way of mapping a list into another list by applying a function to each of the elements of the list. • >>> l_numbers = [1,2,3,4] • >>> [element*2 for element in l_numbers] [2, 4, 6, 8]
  • 44. List comprehension step by step • >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} • >>> params.items() [('pwd', 'secret'), ('database', 'master'), ('uid', 'sa'), ('server', 'mpilgrim')] • >>> [k for k, v in params.items()] • ['pwd', 'database', 'uid', 'server'] >>> [v for k, v in params.items()] tuples ['secret', 'master', 'sa', 'mpilgrim'] • >>> ["%s=%s" % (k, v) for k, v in params.items()] ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim']
  • 45. 3.7 Joining Lists and Splitting Strings • To join any list of strings into a single string, use the join method of a string object. • >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()]) 'pwd=secret;database=master;uid=sa;server=mpilgrim' • join works only on lists of strings; it does not do any type coercion. Joining a list that has one or more non- string elements will raise an exception.
  • 46. 3.7 Joining Lists and Splitting Strings • >>> li = ";".join(["%s=%s" % (k, v) for k, v in params.items()]) • >>> li 'pwd=secret;database=master;uid=sa;server=mpilgrim' • >>> li.split(";") ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] • Ask in class.. what do you notice?
  • 47. Remember Your First Python Program odbchelper.py
  • 48. Dr. Ahmet Bulut took this picture in NYC during when he was interning at IBM T.J.Watson Research Center in August 2004.

Editor's Notes