SlideShare a Scribd company logo
Introduction to Python II CSE 391: Artificial Intelligence adapted from slides by Matt Huenerfauth for CSE 391, 1/05
Dictionaries
Dictionaries: A  Mapping  type Dictionaries store a  mapping  between a set of keys and a set of values. Keys can be any  immutable  type. Values can be any type A single dictionary can have store different types of values You can define, modify, view, lookup, and delete the key-value pairs in the dictionary.
Creating and accessing dictionaries >>>  d = { ‘user’ : ‘bozo’ ,  ‘pswd’ :1234} >>>  d[ ‘user’ ]  ‘ bozo’ >>>  d[ ‘pswd’ ] 1234 >>>  d[ ‘bozo’ ] Traceback (innermost last): File ‘<interactive input>’ line 1, in ? KeyError: bozo
Updating Dictionaries >>>  d = { ‘user’ : ‘bozo’ ,  ‘pswd’ :1234} >>>  d[ ‘user’ ] =  ‘clown’ >>>  d {‘user’:‘clown’, ‘pswd’:1234} Keys must be unique.  Assigning to an existing key replaces its value. >>>  d[ ‘id’ ] = 45 >>>  d {‘user’:‘clown’, ‘id’:45, ‘pswd’:1234} Dictionaries are unordered New entry might appear anywhere in the output. (Dictionaries work by  hashing )
Removing dictionary entries >>>  d = { ‘user’ : ‘bozo’ ,  ‘p’ :1234,  ‘i’ :34} >>>   del  d[ ‘user’ ]  # Remove one. >>>  d {‘p’:1234, ‘i’:34} >>>  d.clear()  # Remove all. >>>  d {}y
Useful Accessor Methods >>>  d = { ‘user’ : ‘bozo’ ,  ‘p’ :1234,  ‘i’ :34} >>>  d.keys()  # List of keys. [‘user’, ‘p’, ‘i’] >>>  d.values()  # List of values. [‘bozo’, 1234, 34] >>>  d.items()  # List of item tuples. [(‘user’,‘bozo’), (‘p’,1234), (‘i’,34)]
Functions in Python
Defining Functions No header file or declaration of  types  of function or arguments. def   get_final_answer (filename):   “ Documentation String”  line1   line2   return  total_counter The indentation matters… First line with different  indentation is considered to be outside of the function definition. Function definition begins with “def.” Function name and its arguments. The keyword ‘return’ indicates the  value to be sent back to the caller. Colon.
Python and Types Python determines the data types  in a program automatically. “Dynamic Typing” But Python’s not casual about types, it  enforces them after it figures them out.  “Strong Typing” So, for example, you can’t just append an integer to a string.  You must first convert the integer to a string itself.  x =  “the answer is ”  # Decides x is string. y = 23  # Decides y is integer. print  x + y  # Python will complain about this.
Calling a Function The syntax for a function call is: >>>   def   myfun (x, y): return  x * y >>>  myfun(3, 4) 12 Parameters in Python are “Call by Assignment.” Sometimes acts like “call by reference” and sometimes like “call by value” in C++.  Mutable datatypes: Call by reference. Immutable datatypes: Call by value.
Functions without returns All  functions in Python have a return value even if no  return  line inside the code. Functions without a  return  return the special value  None . None  is a special constant in the language.  None  is used like  NULL ,  void , or  nil  in other languages.  None  is also logically equivalent to False. The interpreter doesn’t print  None
Function overloading? No. There is no function overloading in Python. Unlike C++, a Python function is specified by its name alone The number, order, names, or types of its arguments cannot be used to distinguish between two functions with the same name. Two different functions can’t have the same name, even if they have different arguments. But: see  operator overloading  in later slides (Note: van Rossum playing with function overloading for the future)
Functions are first-class objects in Python Functions can be used as any other data type They can be  Arguments to function Return values of functions Assigned to variables Parts of tuples, lists, etc … >>>   def   myfun (x): return  x*3 >>>   def   applier (q, x): return  q(x) >>>  applier(myfun, 7) 21
Logical Expressions
True and False  True  and  False  are constants in Python. Other values equivalent to  True  and  False : False : zero,  None , empty container or object True : non-zero numbers, non-empty objects Comparison operators: ==, !=, <, <=, etc. X and Y have same value:  X == Y Compare with  X  is  Y  :  X and Y are two names that refer to the  identical same object.
Boolean Logic Expressions You can also combine Boolean expressions. true  if a is true and b is true:  a  and  b true  if a is true or b is true: a  or  b true  if a is false: not  a Use parentheses as needed to disambiguate complex Boolean expressions.
Special Properties of  and  and  or Actually  and  and  or   don’t  return  True  or  False .  They return the value of one of their sub-expressions (which may be a non-Boolean value). X  and  Y  and  Z If all are true, returns value of Z. Otherwise, returns value of first false sub-expression. X  or  Y  or  Z If all are false, returns value of Z. Otherwise, returns value of first true sub-expression.
The “and-or” Trick A trick to implement a simple conditional  result = test  and  expr1  or  expr2 When test is  True , result is assigned expr1. When test is  False , result is assigned expr2. Works almost like  (test ? expr1 : expr2)  expression of C++. But  if the value of expr1 is  ever   False,  the trick doesn’t work. Avoid (hard to debug), but you may see it in the code.
Control of Flow
Control of Flow There are several Python expressions that control the flow of a program.  All of them make use of Boolean conditional tests. if  Statements while  Loops assert  Statements
if  Statements  if  x == 3: print   “X equals 3.” elif  x == 2: print   “X equals 2.” else : print   “X equals something else.” print   “This is outside the ‘if’.” Be careful! The keyword  if  is also used in the syntax of filtered  list comprehensions . Note: Use of indentation for blocks Colon ( : ) after boolean expression
while  Loops x = 3 while  x < 10: x = x + 1 print   “Still in the loop.” print   “Outside of the loop.”
break  and  continue You can use the keyword  break  inside a loop to leave the  while  loop entirely.  You can use the keyword  continue  inside a loop to stop processing the current iteration of the loop and to immediately go on to the next one.
assert An  assert  statement will check to make sure that something is true during the course of a program.  If the condition if false, the program stops. assert (number_of_players < 5)
Generating Lists using  “List Comprehensions”
List Comprehensions A powerful feature of the Python language. Generate a new list by applying a function to every member of an original list. Python programmers use list comprehensions extensively.  You’ll see many of them in real code. The syntax of a  list comprehension  is somewhat tricky. Syntax suggests that of a  for -loop, an  in  operation, or an  if  statement  all three of these keywords (‘ for ’, ‘ in ’, and ‘ if ’) are also used in the syntax of forms of list comprehensions.
Using List Comprehensions 1 >>> li = [3, 6, 2, 7] >>> [ elem*2  for  elem  in  li ] [6, 12, 4, 14] [   expression   for   name   in   list   ] Where  expression  is some calculation or operation acting upon the variable  name . For each member of the  list , the list comprehension sets  name  equal to that member,  calculates a new value using  expression ,  It then collects these new values into a list which is the return value of the list comprehension. Note: Non-standard colors on next several slides to help clarify the list comprehension syntax.
Using List Comprehensions  2 [   expression   for   name   in   list   ] If  list  contains elements of different types, then  expression  must operate correctly on the types of all of  list  members.  If the elements of  list  are other containers, then the  name  can consist of a container of names that match the type and “shape” of the  list  members.  >>>  li = [(‘a’, 1), (‘b’, 2), (‘c’, 7)] >>> [  n * 3  for  (x, n)  in  li ] [3, 6, 21]
[   expression   for   name   in   list   ] expression  can also contain user-defined functions. >>> def subtract(a, b):   return a – b >>>  oplist = [(6, 3), (1, 7), (5, 5)] >>> [ subtract(y, x)  for  (x, y)  in  oplist ] [-3, 6, 0] Using List Comprehensions 3
Filtered List Comprehension 1 [   expression   for   name   in   list   if   filter   ] Filter   determines whether  expression   is performed on each member of the  list .  For each element of  list , checks if it satisfies the  filter condition .  If it returns  False  for the  filter condition , it is omitted from the  list  before the list comprehension is evaluated.
Filtered List Comprehension 2 [   expression   for   name   in   list   if   filter   ] >>> li = [3, 6, 2, 7, 1, 9] >>> [ elem * 2  for  elem  in  li  if  elem > 4 ] [12, 14, 18] Only 6, 7, and 9 satisfy the filter condition.  So, only 12, 14, and 18 are produced.
Nested List Comprehensions Since list comprehensions take a list as input and produce a list as output, they are easily nested: >>> li = [3, 2, 4, 1] >>> [ elem*2  for  elem  in    [ item+1  for  item  in  li ] ] [8, 6, 10, 4] The inner comprehension produces: [4, 3, 5, 2]. So, the outer one produces: [8, 6, 10, 4].
For Loops
For Loops / List Comprehensions Python’s list comprehensions and split/join operations provide natural idioms that usually require a for-loop in other programming languages. As a result, Python code uses many fewer for-loops  Nevertheless, it’s important to learn about for-loops. Caveat !  The keywords  for  and  in  are also used in the syntax of list comprehensions, but this is a totally different construction.
For Loops 1 A for-loop steps through each of the items in a list,  tuple, string, or any other type of object which the language considers an “iterator.” for  <item>  in  <collection> : <statements> If  <collection>  is a list or a tuple, then the loop steps through each element of the sequence. If  <collection>  is a string, then the loop steps through each character of the string.  for  someChar  in  “Hello World” : print someChar Note: Non-standard colors on these slides.
For Loops 2 for  <item>  in  <collection> : <statements> <item>  can be more complex than a single variable name. When the elements of  <collection>  are themselves sequences, then  <item>  can match the structure of the elements. This multiple assignment can make it easier to access the individual parts of each element. for  (x, y)  in  [(a,1), (b,2), (c,3), (d,4)] : print x
For  loops and the  range()  function Since a variable often ranges over some sequence of numbers, the  range()  function returns a list of numbers from 0 up to but not including the number we pass to it. range(5) returns [0,1,2,3,4] So we could say: for  x  in  range(5) :   print x (There are more complex forms of  range()  that provide richer  functionality…)
Some Fancy Function Syntax
Lambda Notation Functions can be defined without giving them names. This is most useful when passing a short function as an argument to another function. >>>  applier( lambda  z: z * 4, 7) 28 The first argument to applier() is an unnamed function that takes one input and returns the input multiplied by four.  Note: only single-expression functions can be defined using this lambda notation. Lambda notation has a rich history in program language research, AI, and the design of the LISP language.
Default Values for Arguments You can provide default values for a function’s arguments  These arguments are optional when the function is called >>>   def   myfun (b, c=3, d= “hello” ):   return  b + c >>>  myfun(5,3, ”hello” ) >>>  myfun(5,3) >>>  myfun(5) All of the above function calls return 8.
The Order of Arguments You can call a function with some or all of its arguments out of order as long as you specify them (these are called keyword arguments).  You can also just use keywords for a final subset of the arguments. >>>   def   myfun (a, b, c):   return  a-b >>>  myfun(2, 1, 43) 1 >>>  myfun(c=43, b=1, a=2) 1 >>>  myfun(2, c=43, b=1) 1
Assignment and Containers
Multiple Assignment with Sequences We’ve seen multiple assignment before: >>>  x, y = 2, 3 But you can also do it with sequences. The type and “shape” just has to match. >>>  (x, y, (w, z)) = (2, 3, (4, 5)) >>>  [x, y] = [4, 5]
Assignment creates a name, if it didn’t exist already.    x = 3   Creates name x of type integer. Assignment is also what creates named references to containers. >>>  d = { ‘a’ :3,  ‘b’ :4} We can also create empty containers: >>>  li = [] >>>  tu = () >>>  di = {} Empty Containers 1 Note: an empty container is logically equivalent to  False.  (Just like None.)
Empty Containers 2 Why create a named reference to empty container?  To initialize an empty list, for example, before using append. This would cause an unknown name error a named reference to the right data type wasn’t created first >>>  g.append(3) Python complains here about the unknown name ‘g’! >>>  g = [] >>>  g.append(3) >>>  g [3]
String Operations
String Operations A number of methods for the string class perform useful formatting operations: >>>   “hello” .upper() ‘ HELLO’ Check the Python documentation for many other handy string operations.
String Formatting Operator: % The operator % allows strings to be built out of many data items in a “fill in the blanks” fashion. Allows  control  of how the final string output will appear.  For example, we could force a number to display with a specific number of digits after the decimal point. Very similar to the sprintf command of C. >>>  x =  “abc” >>>  y = 34 >>>   “%s xyz %d”  % (x, y) ‘ abc xyz 34’ The tuple following the % operator is used to fill in the blanks in the original string marked with %s or %d.  Check Python documentation for whether to use %s, %d, or some other formatting code inside the string.
Printing with Python You can print a string to the screen using “print.” Using the % string operator in combination with the print command, we can format our output text.  >>>  print  “%s xyz %d”   %  ( “abc” , 34) abc xyz 34 “ Print” automatically adds a newline to the end of the string.  If you include a list of strings, it will concatenate them with a space between them. >>>   print   “abc” >>>   print   “abc” ,   “def” abc abc def
String Conversions
String to List to String Join turns a list of strings into one string. <separator_string>. join(  <some_list>  ) >>>  “;” .join(  [“abc”, “def”, “ghi”]  )   “ abc;def;ghi” Split turns one string into a list of strings. <some_string> .split(  <separator_string>  ) >>>  “abc;def;ghi” .split(  “;”  )   [“abc”, “def”, “ghi”] Note: Non-standard colors on this slide to help clarify the string syntax.
Convert Anything to a String The built-in str() function can convert an instance of  any  data type into a string. You can define how this function behaves for user-created data types.  You can also redefine the behavior of this function for many types. >>>   “Hello ”  + str(2) “ Hello 2”

More Related Content

PPTX
Ch_13_Dictionary.pptx
PPTX
Chapter 14 strings
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
PPTX
Python dictionary
PDF
Overview of python 2019
PPTX
Python Tutorial Part 1
PPTX
Dictionary
Ch_13_Dictionary.pptx
Chapter 14 strings
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python dictionary
Overview of python 2019
Python Tutorial Part 1
Dictionary

What's hot (20)

PDF
Python Programming Language | Python Classes | Python Tutorial | Python Train...
PDF
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
PPT
PDF
Tuples in Python
PDF
Python_Regular Expression
PDF
Python strings
PDF
Python programming : Arrays
PPT
Exception handling and function in python
PPT
Introduction to Python
PDF
Introduction To Python | Edureka
PPTX
Python Tutorial Part 2
PPTX
Python variables and data types.pptx
PDF
Python Flow Control
PPTX
Turtle graphics
PPTX
Python- Regular expression
PDF
Python data handling notes
PDF
Python programming : Strings
PPTX
Dictionaries and Sets
PPTX
Python Programming Essentials - M8 - String Methods
Python Programming Language | Python Classes | Python Tutorial | Python Train...
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
Tuples in Python
Python_Regular Expression
Python strings
Python programming : Arrays
Exception handling and function in python
Introduction to Python
Introduction To Python | Edureka
Python Tutorial Part 2
Python variables and data types.pptx
Python Flow Control
Turtle graphics
Python- Regular expression
Python data handling notes
Python programming : Strings
Dictionaries and Sets
Python Programming Essentials - M8 - String Methods
Ad

Viewers also liked (19)

PPT
Introduction to Python - Part Three
PPT
Introduction to Python
PDF
An Introduction to Python Programming
PPT
Introduction to C++
PDF
Phishing As Tragedy of the Commons
PDF
SQLite 3
PDF
Solid C++ by Example
DOCX
Introduction to Python - Running Notes
PPTX
SQLite: Light, Open Source Relational Database Management System
PDF
Python master class part 1
PPTX
SQLite - Overview
PPTX
Introduction to Python for Security Professionals
PDF
Getting Started with SQLite
PDF
Introduction to Python for Data Science
PDF
Deep learning - Part I
PDF
Basics of bioinformatics
PDF
Learn 90% of Python in 90 Minutes
PPT
Basics of c++ Programming Language
PDF
Deep C
Introduction to Python - Part Three
Introduction to Python
An Introduction to Python Programming
Introduction to C++
Phishing As Tragedy of the Commons
SQLite 3
Solid C++ by Example
Introduction to Python - Running Notes
SQLite: Light, Open Source Relational Database Management System
Python master class part 1
SQLite - Overview
Introduction to Python for Security Professionals
Getting Started with SQLite
Introduction to Python for Data Science
Deep learning - Part I
Basics of bioinformatics
Learn 90% of Python in 90 Minutes
Basics of c++ Programming Language
Deep C
Ad

Similar to Introduction to Python - Part Two (20)

PPT
PDF
Python Programming Module 3 (2).pdf
PPTX
Python Workshop - Learn Python the Hard Way
PDF
Lecture_11.pdf
PPTX
Learn more about the concepts of Data Types in Python
PPT
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT
Python tutorialfeb152012
PDF
Python cheatsheat.pdf
PPT
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
PDF
Python revision tour i
PPTX
Basic of Python- Hands on Session
PDF
Python Basics
PPTX
Python For Data Science.pptx
PPTX
An Introduction : Python
PPT
python language programming presentation
PPTX
Python Revision Tour.pptx class 12 python notes
PPTX
python_computer engineering_semester_computer_language.pptx
PDF
Introduction to python
PDF
Python basic
PPTX
python-presentationpython-presentationpython-presentation.pptx
Python Programming Module 3 (2).pdf
Python Workshop - Learn Python the Hard Way
Lecture_11.pdf
Learn more about the concepts of Data Types in Python
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
Python tutorialfeb152012
Python cheatsheat.pdf
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
Python revision tour i
Basic of Python- Hands on Session
Python Basics
Python For Data Science.pptx
An Introduction : Python
python language programming presentation
Python Revision Tour.pptx class 12 python notes
python_computer engineering_semester_computer_language.pptx
Introduction to python
Python basic
python-presentationpython-presentationpython-presentation.pptx

More from amiable_indian (20)

PDF
Cisco IOS Attack & Defense - The State of the Art
PDF
Secrets of Top Pentesters
PPS
Workshop on Wireless Security
PDF
Insecure Implementation of Security Best Practices: of hashing, CAPTCHA's and...
PPS
Workshop on BackTrack live CD
PPS
Reverse Engineering for exploit writers
PPS
State of Cyber Law in India
PPS
AntiSpam - Understanding the good, the bad and the ugly
PPS
Reverse Engineering v/s Secure Coding
PPS
Network Vulnerability Assessments: Lessons Learned
PPS
Economic offenses through Credit Card Frauds Dissected
PPS
Immune IT: Moving from Security to Immunity
PPS
Reverse Engineering for exploit writers
PPS
Hacking Client Side Insecurities
PDF
Web Exploit Finder Presentation
PPT
Network Security Data Visualization
PPT
Enhancing Computer Security via End-to-End Communication Visualization
PDF
Top Network Vulnerabilities Over Time
PDF
What are the Business Security Metrics?
PPT
No Substitute for Ongoing Data, Quantification, Visualization, and Story-Telling
Cisco IOS Attack & Defense - The State of the Art
Secrets of Top Pentesters
Workshop on Wireless Security
Insecure Implementation of Security Best Practices: of hashing, CAPTCHA's and...
Workshop on BackTrack live CD
Reverse Engineering for exploit writers
State of Cyber Law in India
AntiSpam - Understanding the good, the bad and the ugly
Reverse Engineering v/s Secure Coding
Network Vulnerability Assessments: Lessons Learned
Economic offenses through Credit Card Frauds Dissected
Immune IT: Moving from Security to Immunity
Reverse Engineering for exploit writers
Hacking Client Side Insecurities
Web Exploit Finder Presentation
Network Security Data Visualization
Enhancing Computer Security via End-to-End Communication Visualization
Top Network Vulnerabilities Over Time
What are the Business Security Metrics?
No Substitute for Ongoing Data, Quantification, Visualization, and Story-Telling

Recently uploaded (20)

PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
Teaching material agriculture food technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Cloud computing and distributed systems.
PDF
Machine learning based COVID-19 study performance prediction
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
KodekX | Application Modernization Development
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Empathic Computing: Creating Shared Understanding
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Teaching material agriculture food technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Cloud computing and distributed systems.
Machine learning based COVID-19 study performance prediction
The Rise and Fall of 3GPP – Time for a Sabbatical?
Understanding_Digital_Forensics_Presentation.pptx
Unlocking AI with Model Context Protocol (MCP)
KodekX | Application Modernization Development
Chapter 3 Spatial Domain Image Processing.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Empathic Computing: Creating Shared Understanding
Network Security Unit 5.pdf for BCA BBA.
NewMind AI Weekly Chronicles - August'25 Week I
Dropbox Q2 2025 Financial Results & Investor Presentation

Introduction to Python - Part Two

  • 1. Introduction to Python II CSE 391: Artificial Intelligence adapted from slides by Matt Huenerfauth for CSE 391, 1/05
  • 3. Dictionaries: A Mapping type Dictionaries store a mapping between a set of keys and a set of values. Keys can be any immutable type. Values can be any type A single dictionary can have store different types of values You can define, modify, view, lookup, and delete the key-value pairs in the dictionary.
  • 4. Creating and accessing dictionaries >>> d = { ‘user’ : ‘bozo’ , ‘pswd’ :1234} >>> d[ ‘user’ ] ‘ bozo’ >>> d[ ‘pswd’ ] 1234 >>> d[ ‘bozo’ ] Traceback (innermost last): File ‘<interactive input>’ line 1, in ? KeyError: bozo
  • 5. Updating Dictionaries >>> d = { ‘user’ : ‘bozo’ , ‘pswd’ :1234} >>> d[ ‘user’ ] = ‘clown’ >>> d {‘user’:‘clown’, ‘pswd’:1234} Keys must be unique. Assigning to an existing key replaces its value. >>> d[ ‘id’ ] = 45 >>> d {‘user’:‘clown’, ‘id’:45, ‘pswd’:1234} Dictionaries are unordered New entry might appear anywhere in the output. (Dictionaries work by hashing )
  • 6. Removing dictionary entries >>> d = { ‘user’ : ‘bozo’ , ‘p’ :1234, ‘i’ :34} >>> del d[ ‘user’ ] # Remove one. >>> d {‘p’:1234, ‘i’:34} >>> d.clear() # Remove all. >>> d {}y
  • 7. Useful Accessor Methods >>> d = { ‘user’ : ‘bozo’ , ‘p’ :1234, ‘i’ :34} >>> d.keys() # List of keys. [‘user’, ‘p’, ‘i’] >>> d.values() # List of values. [‘bozo’, 1234, 34] >>> d.items() # List of item tuples. [(‘user’,‘bozo’), (‘p’,1234), (‘i’,34)]
  • 9. Defining Functions No header file or declaration of types of function or arguments. def get_final_answer (filename): “ Documentation String” line1 line2 return total_counter The indentation matters… First line with different indentation is considered to be outside of the function definition. Function definition begins with “def.” Function name and its arguments. The keyword ‘return’ indicates the value to be sent back to the caller. Colon.
  • 10. Python and Types Python determines the data types in a program automatically. “Dynamic Typing” But Python’s not casual about types, it enforces them after it figures them out. “Strong Typing” So, for example, you can’t just append an integer to a string. You must first convert the integer to a string itself. x = “the answer is ” # Decides x is string. y = 23 # Decides y is integer. print x + y # Python will complain about this.
  • 11. Calling a Function The syntax for a function call is: >>> def myfun (x, y): return x * y >>> myfun(3, 4) 12 Parameters in Python are “Call by Assignment.” Sometimes acts like “call by reference” and sometimes like “call by value” in C++. Mutable datatypes: Call by reference. Immutable datatypes: Call by value.
  • 12. Functions without returns All functions in Python have a return value even if no return line inside the code. Functions without a return return the special value None . None is a special constant in the language. None is used like NULL , void , or nil in other languages. None is also logically equivalent to False. The interpreter doesn’t print None
  • 13. Function overloading? No. There is no function overloading in Python. Unlike C++, a Python function is specified by its name alone The number, order, names, or types of its arguments cannot be used to distinguish between two functions with the same name. Two different functions can’t have the same name, even if they have different arguments. But: see operator overloading in later slides (Note: van Rossum playing with function overloading for the future)
  • 14. Functions are first-class objects in Python Functions can be used as any other data type They can be Arguments to function Return values of functions Assigned to variables Parts of tuples, lists, etc … >>> def myfun (x): return x*3 >>> def applier (q, x): return q(x) >>> applier(myfun, 7) 21
  • 16. True and False True and False are constants in Python. Other values equivalent to True and False : False : zero, None , empty container or object True : non-zero numbers, non-empty objects Comparison operators: ==, !=, <, <=, etc. X and Y have same value: X == Y Compare with X is Y : X and Y are two names that refer to the identical same object.
  • 17. Boolean Logic Expressions You can also combine Boolean expressions. true if a is true and b is true: a and b true if a is true or b is true: a or b true if a is false: not a Use parentheses as needed to disambiguate complex Boolean expressions.
  • 18. Special Properties of and and or Actually and and or don’t return True or False . They return the value of one of their sub-expressions (which may be a non-Boolean value). X and Y and Z If all are true, returns value of Z. Otherwise, returns value of first false sub-expression. X or Y or Z If all are false, returns value of Z. Otherwise, returns value of first true sub-expression.
  • 19. The “and-or” Trick A trick to implement a simple conditional result = test and expr1 or expr2 When test is True , result is assigned expr1. When test is False , result is assigned expr2. Works almost like (test ? expr1 : expr2) expression of C++. But if the value of expr1 is ever False, the trick doesn’t work. Avoid (hard to debug), but you may see it in the code.
  • 21. Control of Flow There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests. if Statements while Loops assert Statements
  • 22. if Statements if x == 3: print “X equals 3.” elif x == 2: print “X equals 2.” else : print “X equals something else.” print “This is outside the ‘if’.” Be careful! The keyword if is also used in the syntax of filtered list comprehensions . Note: Use of indentation for blocks Colon ( : ) after boolean expression
  • 23. while Loops x = 3 while x < 10: x = x + 1 print “Still in the loop.” print “Outside of the loop.”
  • 24. break and continue You can use the keyword break inside a loop to leave the while loop entirely. You can use the keyword continue inside a loop to stop processing the current iteration of the loop and to immediately go on to the next one.
  • 25. assert An assert statement will check to make sure that something is true during the course of a program. If the condition if false, the program stops. assert (number_of_players < 5)
  • 26. Generating Lists using “List Comprehensions”
  • 27. List Comprehensions A powerful feature of the Python language. Generate a new list by applying a function to every member of an original list. Python programmers use list comprehensions extensively. You’ll see many of them in real code. The syntax of a list comprehension is somewhat tricky. Syntax suggests that of a for -loop, an in operation, or an if statement all three of these keywords (‘ for ’, ‘ in ’, and ‘ if ’) are also used in the syntax of forms of list comprehensions.
  • 28. Using List Comprehensions 1 >>> li = [3, 6, 2, 7] >>> [ elem*2 for elem in li ] [6, 12, 4, 14] [ expression for name in list ] Where expression is some calculation or operation acting upon the variable name . For each member of the list , the list comprehension sets name equal to that member, calculates a new value using expression , It then collects these new values into a list which is the return value of the list comprehension. Note: Non-standard colors on next several slides to help clarify the list comprehension syntax.
  • 29. Using List Comprehensions 2 [ expression for name in list ] If list contains elements of different types, then expression must operate correctly on the types of all of list members. If the elements of list are other containers, then the name can consist of a container of names that match the type and “shape” of the list members. >>> li = [(‘a’, 1), (‘b’, 2), (‘c’, 7)] >>> [ n * 3 for (x, n) in li ] [3, 6, 21]
  • 30. [ expression for name in list ] expression can also contain user-defined functions. >>> def subtract(a, b): return a – b >>> oplist = [(6, 3), (1, 7), (5, 5)] >>> [ subtract(y, x) for (x, y) in oplist ] [-3, 6, 0] Using List Comprehensions 3
  • 31. Filtered List Comprehension 1 [ expression for name in list if filter ] Filter determines whether expression is performed on each member of the list . For each element of list , checks if it satisfies the filter condition . If it returns False for the filter condition , it is omitted from the list before the list comprehension is evaluated.
  • 32. Filtered List Comprehension 2 [ expression for name in list if filter ] >>> li = [3, 6, 2, 7, 1, 9] >>> [ elem * 2 for elem in li if elem > 4 ] [12, 14, 18] Only 6, 7, and 9 satisfy the filter condition. So, only 12, 14, and 18 are produced.
  • 33. Nested List Comprehensions Since list comprehensions take a list as input and produce a list as output, they are easily nested: >>> li = [3, 2, 4, 1] >>> [ elem*2 for elem in [ item+1 for item in li ] ] [8, 6, 10, 4] The inner comprehension produces: [4, 3, 5, 2]. So, the outer one produces: [8, 6, 10, 4].
  • 35. For Loops / List Comprehensions Python’s list comprehensions and split/join operations provide natural idioms that usually require a for-loop in other programming languages. As a result, Python code uses many fewer for-loops Nevertheless, it’s important to learn about for-loops. Caveat ! The keywords for and in are also used in the syntax of list comprehensions, but this is a totally different construction.
  • 36. For Loops 1 A for-loop steps through each of the items in a list, tuple, string, or any other type of object which the language considers an “iterator.” for <item> in <collection> : <statements> If <collection> is a list or a tuple, then the loop steps through each element of the sequence. If <collection> is a string, then the loop steps through each character of the string. for someChar in “Hello World” : print someChar Note: Non-standard colors on these slides.
  • 37. For Loops 2 for <item> in <collection> : <statements> <item> can be more complex than a single variable name. When the elements of <collection> are themselves sequences, then <item> can match the structure of the elements. This multiple assignment can make it easier to access the individual parts of each element. for (x, y) in [(a,1), (b,2), (c,3), (d,4)] : print x
  • 38. For loops and the range() function Since a variable often ranges over some sequence of numbers, the range() function returns a list of numbers from 0 up to but not including the number we pass to it. range(5) returns [0,1,2,3,4] So we could say: for x in range(5) : print x (There are more complex forms of range() that provide richer functionality…)
  • 40. Lambda Notation Functions can be defined without giving them names. This is most useful when passing a short function as an argument to another function. >>> applier( lambda z: z * 4, 7) 28 The first argument to applier() is an unnamed function that takes one input and returns the input multiplied by four. Note: only single-expression functions can be defined using this lambda notation. Lambda notation has a rich history in program language research, AI, and the design of the LISP language.
  • 41. Default Values for Arguments You can provide default values for a function’s arguments These arguments are optional when the function is called >>> def myfun (b, c=3, d= “hello” ): return b + c >>> myfun(5,3, ”hello” ) >>> myfun(5,3) >>> myfun(5) All of the above function calls return 8.
  • 42. The Order of Arguments You can call a function with some or all of its arguments out of order as long as you specify them (these are called keyword arguments). You can also just use keywords for a final subset of the arguments. >>> def myfun (a, b, c): return a-b >>> myfun(2, 1, 43) 1 >>> myfun(c=43, b=1, a=2) 1 >>> myfun(2, c=43, b=1) 1
  • 44. Multiple Assignment with Sequences We’ve seen multiple assignment before: >>> x, y = 2, 3 But you can also do it with sequences. The type and “shape” just has to match. >>> (x, y, (w, z)) = (2, 3, (4, 5)) >>> [x, y] = [4, 5]
  • 45. Assignment creates a name, if it didn’t exist already. x = 3 Creates name x of type integer. Assignment is also what creates named references to containers. >>> d = { ‘a’ :3, ‘b’ :4} We can also create empty containers: >>> li = [] >>> tu = () >>> di = {} Empty Containers 1 Note: an empty container is logically equivalent to False. (Just like None.)
  • 46. Empty Containers 2 Why create a named reference to empty container? To initialize an empty list, for example, before using append. This would cause an unknown name error a named reference to the right data type wasn’t created first >>> g.append(3) Python complains here about the unknown name ‘g’! >>> g = [] >>> g.append(3) >>> g [3]
  • 48. String Operations A number of methods for the string class perform useful formatting operations: >>> “hello” .upper() ‘ HELLO’ Check the Python documentation for many other handy string operations.
  • 49. String Formatting Operator: % The operator % allows strings to be built out of many data items in a “fill in the blanks” fashion. Allows control of how the final string output will appear. For example, we could force a number to display with a specific number of digits after the decimal point. Very similar to the sprintf command of C. >>> x = “abc” >>> y = 34 >>> “%s xyz %d” % (x, y) ‘ abc xyz 34’ The tuple following the % operator is used to fill in the blanks in the original string marked with %s or %d. Check Python documentation for whether to use %s, %d, or some other formatting code inside the string.
  • 50. Printing with Python You can print a string to the screen using “print.” Using the % string operator in combination with the print command, we can format our output text. >>> print “%s xyz %d” % ( “abc” , 34) abc xyz 34 “ Print” automatically adds a newline to the end of the string. If you include a list of strings, it will concatenate them with a space between them. >>> print “abc” >>> print “abc” , “def” abc abc def
  • 52. String to List to String Join turns a list of strings into one string. <separator_string>. join( <some_list> ) >>> “;” .join( [“abc”, “def”, “ghi”] ) “ abc;def;ghi” Split turns one string into a list of strings. <some_string> .split( <separator_string> ) >>> “abc;def;ghi” .split( “;” ) [“abc”, “def”, “ghi”] Note: Non-standard colors on this slide to help clarify the string syntax.
  • 53. Convert Anything to a String The built-in str() function can convert an instance of any data type into a string. You can define how this function behaves for user-created data types. You can also redefine the behavior of this function for many types. >>> “Hello ” + str(2) “ Hello 2”