SlideShare una empresa de Scribd logo
1 de 36
Functions and (list and string
methods)
Python SIG – PYA
Class 3 – 3/10/15
These are things you should know
pretty well by now:
• raw_input, printing
• help(), dir(), online docs, searching the
internet
• The fact that Python is awesome. (No, really,
I’m just being completely objective here.)
(Revision of)Useful built-ins
• len()
• range() (and xrange())
• sum(), max(), min()
• int(), float(), str()
• dir() – use it to find list and string methods
• Use help() to find out about them
(Revision of)if else elif
if SomethingThatEvaluatesToABoolean:
# code
elif SomethingElseThatEvaluatesToABoolean:
# code
else:
# code
(Revision of)String formatting
• What is it? (Immutable)
• %something - %d, %f, %s
– ‘a = %d’ % (a)
• Prefer .format()
• {} sufficient – numbers optional
• More complex things possible
(Revision of)Loops
• for – for when you how many iterations
• while - while you don’t know how many
iterations
• while SomethingThatEvaluatesToABoolean:
# code
• for loop syntax in Python
– for iterVar in (x)range(iterNum):
# code
(Revision of)for loops can do more!
• What is this ‘in’ anyway? (different time
complexity for different cases)
• for char in string
• for line in text
• for item in sequence
–Example: for i in [1,’a’,3]:
print i
# output: 1nan3
And one more thing
Don’t be afraid of these:
Exception EOFError OSError
StopIteration ImportError SyntaxError
SystemExit KeyboardInterrupt IndentationError
StandardError LookupError SystemError
ArithmeticError IndexError SystemExit
OverflowError KeyError TypeError
FloatingPointError NameError ValueError
ZeroDivisonError UnboundLocalError RuntimeError
AssertionError EnvironmentError NotImplementedError
AttributeError IOError SomeRandomError
And one more thing
• If nothing, look at what error it is and what
line it is on. And make sure you look above
and below that line.
• Further reading – 16 common runtime errors
Python beginners find:
http://inventwithpython.com/blog/2012/07/0
9/16-common-python-runtime-errors/
Obligatory xkcd reference[1]
Serious questions:
• What are functions?
• Why are they important?
• What is the difference between a
function and a method? (OOP language
guys should answer)
Functions are:
“Functions are reusable pieces of programs.
They allow you to give a name to a block of
statements, allowing you to run that block
using the specified name anywhere in your
program and any number of times. This is
known as calling the function.” - Byte of
Python, Swaroop CH[2]
General syntax
• def function_name(param_1, ..., param_n):
# code to do something
[return some_tuple] # square brackets because
# optional
• Why param not arg?
• That is, what is the difference between
arguments and parameters?
• Fact: Functions in Python always return
something. So, in a function that just prints
something, what does it return?
More about functions
• Flow of execution – jumping when called,
ending when a return is reached
• Try making a IndentationError or SyntaxError
in your function definition. Is it caught without
calling your function?
• What about other types of errors? That is,
runtime errors.
( dir(__builtins__) lists (yes, LISTs), among
other things, all possible [Something]Error)
Docstrings
• Let’s open some random library’s .py files and
look at the code. (Be careful about modifying it,
though.)
• Have you noticed __doc__?
• Ignoring classes (and double underscores) for
now.
• def somefunction(args):
“””This is a docstring and it
describes what the function does
“””
Functions that return
• What is the point of this?
• How to receive what the function returns?
• Be careful about number of arguments.
• Idea of local variables.
• Global variables using global statement
(But bad practice!)
• Functional programming – stateless, no side
effects
Imported stuff
• Before going to assignments for functions,
let’s take a little detour to the import
statement.
• Modules vs. Libraries – basic difference
• And before going to import, let’s take a little
detour to...
Remember import antigravity?
• For those who don’t:
(not so) Serious questions:
• Do you think I’m just looking for an excuse to
put xkcd comics in my slides or they actually
have served a purpose in every case (so far)?
Why am I talking about that anyway?
• Because whatever we import are usually .py
or .pyc files
• And I found antigravity.py and antigravity.pyc
in C:Python27Lib
• Let’s open both with a text editor.
• What happens when we click on both?
• What happens when we modify the .py file?
• Does is effect the .pyc file? Should it?
(Again)Why am I talking about that
anyway?
• To explain better how import works
– The .pyc file is unaffected until we modify, save
and import antigravity again
– Searches everything in sys.path
• Just to give you an idea that Python is not a
complex or rigid as you think it is.
• Open source for the win!
Try ‘this’. Literally.
• Try ‘import this’.
• Find “this.py” and try to make sense of it.
• Make a .py file called “this_1.py” and modify it to
print whatever you want.
• Save it in a non C: partition
• Now find a way to run it in a Python session
without navigating to saved location.
• After you’ve finished, read the output of import
this. It’s pretty well written!
Make a dice rolling game
Find a module that helps you with pseudorandom
generation of numbers and
use it to create a program to emulate a dice.
Then it should roll the dice until the user gets the
same number three times in a row or m tries,
whichever is earlier. (m is entered by the user at
the beginning)
In case of the former, it prints, “You’re lucky.”
Otherwise it prints “m chances up. ”
It should also print no. of chances remaining at
every roll and display the results of the last 3
rolls.
For those who have finished
• Try playing the game to see if you “are lucky”!
How big should your m be to win consistently?
• What is the ideal probability for a random
dice? (1/6th per toss, one doesn’t affect the
other.)
• But here it is pseudorandom.
• Further reading – Blog post by Jeff Atwood:
https://blog.codinghorror.com/computers-
are-lousy-random-number-generators/
Default args
• Functions can use a default value as argument
in case it is not passed while calling it.
• “Only those parameters which are at the end
of the parameter list can be given default
argument values ” [2]
• def func_name(param1, param2 = 0):
• NOT def func_name(param1 = 0, param2):
*args and **kwargs
• Variable number of arguments
• kwargs – keyword arguments
• def complex_func(*args, **kwargs):
# try this
a = args; b = kwargs
print(a, type(a)); print(b,type(b))
*args and **kwargs
• You can use for loops to iterate over the
arguments.
• args is a tuple
• kwargs is a dictionary
• How to call such a function? What is the value
of the dictionary?
Other things about functions
• Functions can return multiple values. Use
tuples (if confused, just comma-separate the
variables for now)
• Too many arguments make a function
argumentative. Limit yourself to fewer
arguments per function; and more functions if
required.
List and string methods
• Why is this important enough to be a separate
topic?
• What is the main difference between them?
• Hint: This goes back to mutability.
• Hint: Try something on both. What is the
return type
List methods
• Do dir([]) and try to guess what each of the
methods might do to a list.
• list.append(element)
• list.extend(list)
• list.remove(element)
• list.pop(index)
• list.reverse()
• list.sort()
Assignment
Write a function which takes an input ‘n’.
Then it asks for ‘n’ numbers and makes a list
of Boolean values that are returned by a
function is_greater(arg1, arg2) by comparing
input values in order. That is, when 4 values a,
b, c and d are given. The value of the list is:
[a > b, b > c, c > d]. The program runs until the
user types ‘end’.
Assignment
A list containing ints, floats, and strings, when unsorted
looks like this:
Example: l1_unsorted = [[1], 1, 2, 1.0, ‘aa’, ‘a’, ‘b’,
[‘b’], [‘a’]]
Using the default sort gives:
Example: l1_sorted = [1, 1.0, 2, [1], ['a'], ['b'], 'a', 'aa',
'b']
Write a program that returns:
l1_custom_sorted = [[‘a’], [‘b’], ‘b’, ‘aa’, ‘a’, 2, 1,
1.0] . Make sure that no more than 4 lines of code is
outside a function. Functionify you code!
String methods
• Do dir(‘’) and try to guess what each of
methods might do to a string.
• string.split(delimiter)
• string.upper() / .lower()
• ‘ ‘.join([list of things to join])
• string.startswith() / .endswith()
Palindrome checker
• Write a palindrome checker.
• That’s it. Up to you how complex you make it.
Thanks!
Pranav S Bijapur,
ECE, BMSCE, Bangalore
b.pranavshankar@gmail.com
Telegram - @pranavsb
References
All (Revision of) slides were taken from the
class2 presentation that was made by me
and used on 29/9/15
1. xkcd – Wisdom of the ancients
https://xkcd.com/979
2. Byte of Python by Swaroop CH, available
online at
http://www.swaroopch.com/notes/python

Más contenido relacionado

La actualidad más candente

Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with PythonSushant Mane
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsPhoenix
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 

La actualidad más candente (20)

Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Python basics
Python basicsPython basics
Python basics
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
 
Introduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data AnalyticsIntroduction to Python Pandas for Data Analytics
Introduction to Python Pandas for Data Analytics
 
Python basic
Python basicPython basic
Python basic
 
python.ppt
python.pptpython.ppt
python.ppt
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Python basics
Python basicsPython basics
Python basics
 
Python ppt
Python pptPython ppt
Python ppt
 

Destacado

5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
8086 Interrupts & With DOS and BIOS by vijay
8086 Interrupts &  With DOS and BIOS  by vijay8086 Interrupts &  With DOS and BIOS  by vijay
8086 Interrupts & With DOS and BIOS by vijayVijay Kumar
 
Applications of stack
Applications of stackApplications of stack
Applications of stackeShikshak
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming languageVasavi College of Engg
 

Destacado (6)

5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
Application of Stacks
Application of StacksApplication of Stacks
Application of Stacks
 
8086 Interrupts & With DOS and BIOS by vijay
8086 Interrupts &  With DOS and BIOS  by vijay8086 Interrupts &  With DOS and BIOS  by vijay
8086 Interrupts & With DOS and BIOS by vijay
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
 
Interrupts
InterruptsInterrupts
Interrupts
 

Similar a Functions, List and String methods

Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingPranavSB
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security ProfessionalsAditya Shankar
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Fariz Darari
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu Kumar
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Reuven Lerner
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
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
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 

Similar a Functions, List and String methods (20)

Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Python basics
Python basicsPython basics
Python basics
 
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 ...
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 

Último (20)

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 

Functions, List and String methods

  • 1. Functions and (list and string methods) Python SIG – PYA Class 3 – 3/10/15
  • 2. These are things you should know pretty well by now: • raw_input, printing • help(), dir(), online docs, searching the internet • The fact that Python is awesome. (No, really, I’m just being completely objective here.)
  • 3. (Revision of)Useful built-ins • len() • range() (and xrange()) • sum(), max(), min() • int(), float(), str() • dir() – use it to find list and string methods • Use help() to find out about them
  • 4. (Revision of)if else elif if SomethingThatEvaluatesToABoolean: # code elif SomethingElseThatEvaluatesToABoolean: # code else: # code
  • 5. (Revision of)String formatting • What is it? (Immutable) • %something - %d, %f, %s – ‘a = %d’ % (a) • Prefer .format() • {} sufficient – numbers optional • More complex things possible
  • 6. (Revision of)Loops • for – for when you how many iterations • while - while you don’t know how many iterations • while SomethingThatEvaluatesToABoolean: # code • for loop syntax in Python – for iterVar in (x)range(iterNum): # code
  • 7. (Revision of)for loops can do more! • What is this ‘in’ anyway? (different time complexity for different cases) • for char in string • for line in text • for item in sequence –Example: for i in [1,’a’,3]: print i # output: 1nan3
  • 8. And one more thing Don’t be afraid of these: Exception EOFError OSError StopIteration ImportError SyntaxError SystemExit KeyboardInterrupt IndentationError StandardError LookupError SystemError ArithmeticError IndexError SystemExit OverflowError KeyError TypeError FloatingPointError NameError ValueError ZeroDivisonError UnboundLocalError RuntimeError AssertionError EnvironmentError NotImplementedError AttributeError IOError SomeRandomError
  • 9. And one more thing • If nothing, look at what error it is and what line it is on. And make sure you look above and below that line. • Further reading – 16 common runtime errors Python beginners find: http://inventwithpython.com/blog/2012/07/0 9/16-common-python-runtime-errors/
  • 11. Serious questions: • What are functions? • Why are they important? • What is the difference between a function and a method? (OOP language guys should answer)
  • 12. Functions are: “Functions are reusable pieces of programs. They allow you to give a name to a block of statements, allowing you to run that block using the specified name anywhere in your program and any number of times. This is known as calling the function.” - Byte of Python, Swaroop CH[2]
  • 13. General syntax • def function_name(param_1, ..., param_n): # code to do something [return some_tuple] # square brackets because # optional • Why param not arg? • That is, what is the difference between arguments and parameters? • Fact: Functions in Python always return something. So, in a function that just prints something, what does it return?
  • 14. More about functions • Flow of execution – jumping when called, ending when a return is reached • Try making a IndentationError or SyntaxError in your function definition. Is it caught without calling your function? • What about other types of errors? That is, runtime errors. ( dir(__builtins__) lists (yes, LISTs), among other things, all possible [Something]Error)
  • 15. Docstrings • Let’s open some random library’s .py files and look at the code. (Be careful about modifying it, though.) • Have you noticed __doc__? • Ignoring classes (and double underscores) for now. • def somefunction(args): “””This is a docstring and it describes what the function does “””
  • 16. Functions that return • What is the point of this? • How to receive what the function returns? • Be careful about number of arguments. • Idea of local variables. • Global variables using global statement (But bad practice!) • Functional programming – stateless, no side effects
  • 17. Imported stuff • Before going to assignments for functions, let’s take a little detour to the import statement. • Modules vs. Libraries – basic difference • And before going to import, let’s take a little detour to...
  • 18. Remember import antigravity? • For those who don’t:
  • 19. (not so) Serious questions: • Do you think I’m just looking for an excuse to put xkcd comics in my slides or they actually have served a purpose in every case (so far)?
  • 20. Why am I talking about that anyway? • Because whatever we import are usually .py or .pyc files • And I found antigravity.py and antigravity.pyc in C:Python27Lib • Let’s open both with a text editor. • What happens when we click on both? • What happens when we modify the .py file? • Does is effect the .pyc file? Should it?
  • 21. (Again)Why am I talking about that anyway? • To explain better how import works – The .pyc file is unaffected until we modify, save and import antigravity again – Searches everything in sys.path • Just to give you an idea that Python is not a complex or rigid as you think it is. • Open source for the win!
  • 22. Try ‘this’. Literally. • Try ‘import this’. • Find “this.py” and try to make sense of it. • Make a .py file called “this_1.py” and modify it to print whatever you want. • Save it in a non C: partition • Now find a way to run it in a Python session without navigating to saved location. • After you’ve finished, read the output of import this. It’s pretty well written!
  • 23. Make a dice rolling game Find a module that helps you with pseudorandom generation of numbers and use it to create a program to emulate a dice. Then it should roll the dice until the user gets the same number three times in a row or m tries, whichever is earlier. (m is entered by the user at the beginning) In case of the former, it prints, “You’re lucky.” Otherwise it prints “m chances up. ” It should also print no. of chances remaining at every roll and display the results of the last 3 rolls.
  • 24. For those who have finished • Try playing the game to see if you “are lucky”! How big should your m be to win consistently? • What is the ideal probability for a random dice? (1/6th per toss, one doesn’t affect the other.) • But here it is pseudorandom. • Further reading – Blog post by Jeff Atwood: https://blog.codinghorror.com/computers- are-lousy-random-number-generators/
  • 25. Default args • Functions can use a default value as argument in case it is not passed while calling it. • “Only those parameters which are at the end of the parameter list can be given default argument values ” [2] • def func_name(param1, param2 = 0): • NOT def func_name(param1 = 0, param2):
  • 26. *args and **kwargs • Variable number of arguments • kwargs – keyword arguments • def complex_func(*args, **kwargs): # try this a = args; b = kwargs print(a, type(a)); print(b,type(b))
  • 27. *args and **kwargs • You can use for loops to iterate over the arguments. • args is a tuple • kwargs is a dictionary • How to call such a function? What is the value of the dictionary?
  • 28. Other things about functions • Functions can return multiple values. Use tuples (if confused, just comma-separate the variables for now) • Too many arguments make a function argumentative. Limit yourself to fewer arguments per function; and more functions if required.
  • 29. List and string methods • Why is this important enough to be a separate topic? • What is the main difference between them? • Hint: This goes back to mutability. • Hint: Try something on both. What is the return type
  • 30. List methods • Do dir([]) and try to guess what each of the methods might do to a list. • list.append(element) • list.extend(list) • list.remove(element) • list.pop(index) • list.reverse() • list.sort()
  • 31. Assignment Write a function which takes an input ‘n’. Then it asks for ‘n’ numbers and makes a list of Boolean values that are returned by a function is_greater(arg1, arg2) by comparing input values in order. That is, when 4 values a, b, c and d are given. The value of the list is: [a > b, b > c, c > d]. The program runs until the user types ‘end’.
  • 32. Assignment A list containing ints, floats, and strings, when unsorted looks like this: Example: l1_unsorted = [[1], 1, 2, 1.0, ‘aa’, ‘a’, ‘b’, [‘b’], [‘a’]] Using the default sort gives: Example: l1_sorted = [1, 1.0, 2, [1], ['a'], ['b'], 'a', 'aa', 'b'] Write a program that returns: l1_custom_sorted = [[‘a’], [‘b’], ‘b’, ‘aa’, ‘a’, 2, 1, 1.0] . Make sure that no more than 4 lines of code is outside a function. Functionify you code!
  • 33. String methods • Do dir(‘’) and try to guess what each of methods might do to a string. • string.split(delimiter) • string.upper() / .lower() • ‘ ‘.join([list of things to join]) • string.startswith() / .endswith()
  • 34. Palindrome checker • Write a palindrome checker. • That’s it. Up to you how complex you make it.
  • 35. Thanks! Pranav S Bijapur, ECE, BMSCE, Bangalore b.pranavshankar@gmail.com Telegram - @pranavsb
  • 36. References All (Revision of) slides were taken from the class2 presentation that was made by me and used on 29/9/15 1. xkcd – Wisdom of the ancients https://xkcd.com/979 2. Byte of Python by Swaroop CH, available online at http://www.swaroopch.com/notes/python