SlideShare a Scribd company logo
advanced python for those who have beginner level experience with python
From the map() function, which applies a specified function to each
element of an iterable and returns a new iterable with the modified
elements, to the enumerate() function which adds a counter to an
iterable and returns an iterable of tuples, these functions can help you
write cleaner and more concise code.
Let’s take a closer look at these advanced Python functions and see how
to use them in your code.
map()
The map() function applies a specified function to each element of an iterable (such as a list, tuple, or
string) and returns a new iterable with the modified elements.
For example, you can use map() to apply the len() function to a list of strings and get a list of the lengths of
each string:
You can also use map() with multiple iterables by providing multiple function arguments. In this case, the
function should accept as many arguments as there are iterables. The map() function will then apply the
function to the elements of the iterables in parallel, with the first element of each iterable being passed as
arguments to the function, the second element of each iterable being passed as arguments to the function,
and so on.
For example, you can use map() to apply a function to two lists element-wise:
def multiply(x, y):
return x * y
a = [1, 2, 3]
b = [10, 20, 30]
result = map(multiply, a, b)
print(result) # [10, 40, 90]
reduce()
The reduce() function is a part of the functools module in Python and allows you to apply a function to a
sequence of elements in order to reduce them to a single value.
For example, you can use reduce() to multiply all the elements of a list:
You can also specify an initial value as the third argument to reduce(). In this case, the initial value will be
used as the first argument to the function and the first element of the iterable will be used as the second
argument.
For example, you can use reduce() to calculate the sum of a list of numbers:
filter()
The filter() function filters an iterable by removing elements that do not satisfy a specified condition. It
returns a new iterable with only the elements that satisfy the condition.
For example, you can use filter() to remove all the even numbers from a list:
def is_odd(x):
return x % 2 == 1
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = filter(is_odd, a)
print(odd_numbers) # [1, 3, 5, 7,
9]
You can also use filter() with a lambda function as the first argument:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = filter(lambda x: x %
2 == 1, a)
print(odd_numbers) # [1, 3, 5, 7,
9]
zip()
The zip() function combines multiple iterables into a single iterable of tuples. The zip() function stops
when the shortest iterable is exhausted.
For example, you can use zip() to combine two lists into a list of tuples:
a = [1, 2, 3]
b = ['a', 'b', 'c']
zipped = zip(a, b)
print(zipped) # [(1, 'a'), (2,
'b'), (3, 'c')]
You can also use zip() with more than two iterables:
a = [1, 2, 3]
b = ['a', 'b', 'c']
c = [True, False, True]
zipped = zip(a, b, c)
print(zipped) # [(1, 'a', True),
(2, 'b', False), (3, 'c', True)]
You can unpack the tuples in a zip() object by using the * operator in a function call or a list
comprehension:
enumerate()
The enumerate() function adds a counter to an iterable and returns an iterable of tuples, where each tuple
consists of the counter and the original element.
For example, you can use enumerate() to loop over a list and print the index and value of each element:
You can also specify a start value for the counter as the second argument to enumerate():
we covered some advanced Python functions that can be useful in your code. We looked at the map(),
reduce(), filter(), zip(), and enumerate() functions, and provided examples of how to use them. These
functions can help you write more efficient and concise code, and are worth exploring further.
Modules and Libraries in Python
1. What is a Module?
A module in Python is a file that contains Python code (functions, classes, or variables)
that you can reuse in your programs.
Any Python file with the .py extension is a module.
You can import a module into another program to access its functions or classes.
2. What is a Library?
A library is a collection of modules or packages that provide pre-written functionality to
simplify coding tasks.
Example: Libraries like NumPy for arrays, Pandas for data analysis, and Matplotlib for
plotting.
3. Importing Libraries and Modules
You can import libraries or modules using the import statement.
Basic Import Syntax:
Importing Specific Functions or Classes
https://www.learnpython.dev/03-intermediate-python/50-libraries-module
s/30-modules-and-imports/
We will study little from this site now…
4. Installing External Libraries Using pip
What is pip?
● pip is Python's package manager used to install external libraries that are not built
into Python.
● Libraries like NumPy, Pandas, and Matplotlib are installed using pip.
Installing a Library
pip install library_name
For example:
pip install numpy
pip install pandas
Advanced Strings in Python
Decimal Formatting:
Formatting decimal or floating point numbers with f-strings is easy - you can pass in both a
field width and a precision. The format is {value:width.precision}. Let’s format pi (3.1415926)
to two decimal places - we’ll set the width to 1 because we don’t need padding, and the
precision to 3, giving us the one number to the left of the decimal and the two numbers to the
right
Note how the
second one is
padded with
extra spaces -
the number is
four characters
long (including
the period), so
the formatter
added six extra
spaces to equal
the total width
of 10.
Multiline Strings
Sometimes it’s easier to break up large statements into multiple lines. Just prepend every line with
f:
Trimming a string
Python strings have some very useful functions for trimming whitespace. strip() returns a new
string after removing any leading and trailing whitespace. rstrip() and does the same but only
removes trailing whitespace, and lstrip() only trims leading whitespace. We’ll print our string inside
>< characters to make it clear:
Note the different spaces inside of the brackets. These functions also accept an optional argument of
characters to remove. Let’s remove all leading or trailing commas:
Replacing Characters
Strings have a useful function for replacing characters - just call replace() on any string and pass in what
you want replace, and what you want to replace it with:
str.format() and % formatting
Python has two older methods for string formatting that you’ll probably come across at some point.
str.format() is the more verbose older cousin to f-strings - variables appear in brackets in the string but
must be passed in to the format() call. For example:
Note that the variable name inside the string is local to the string - it must be assigned to an outside
variable inside the format() call, hence .format(name=name).
%-formatting is a much older method of string interpolating and isn’t used much anymore. It’s very similar
to the methods used in C/C++. Here, we’ll use %s as our placeholder for a string, and pass the name
variable in to the formatter by placing it after the % symbol.
*******************************************************************
Advanced Looping with List Comprehensions
List Comprehensions
List comprehensions are a unique way to create lists in Python. A list comprehension consists of brackets
containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can
be any kind of Python object. List comprehensions will commonly take the form of [<value> for <vars>
in <iter>].
A simple case: Say we want to turn a list of strings into a list of string lengths. We could do this with a for
loop:
We can do this much easier with a list comprehension:
We can also use comprehensions to perform operations, and the lists we assemble can be composed of any
type of Python object. For example:
In the above example, we assemble a list of tuples - each tuple contains the element “length” as well as
each number from the len() function multiplied by two.
Conditionals
You can also use conditionals (if statements) in your list comprehensions. For example, to quickly make a list of
only the even lengths, you could do:
Here, we check divide every string length by 2, and check to see if the remainder is 0 (using the modulo
operator).
String Joining with a List Comprehension
Back in our exercise on converting between types, we introduced the string.join() function.
You can call this function on any string, pass it a list, and it will spit out a string with every
element from the list “joined” by the string. For example, to get a comma-delimited list of
numbers, you might be tempted to do:
Unfortunately, you can’t join a list of numbers without first converting them to strings. But
you can do this easily with a list comprehension:
Some mathematical functions, such as sum, min, and max, accept lists of numbers to operate
on. For example, to get the sum of numbers between zero and five, you could do:
But remember, anywhere you can use a list, you can use a list comprehension.
Say you want to get sum, minimum, and maximum of every number between 0 and 100 that
is evenly divisible by 3? No sense typing out a whole list in advance, just use a
comprehension:
Exception Handling:
Many languages have the concept of the “Try-Catch” block. Python uses four keywords:
try, except, else, and finally. Code that can possibly throw an exception goes in the try
block. except gets the code that runs if an exception is raised. else is an optional block
that runs if no exception was raised in the try block, and finally is an optional block of
code that will run last, regardless of if an exception was raised. We’ll focus on try and
except for this chapter.
First, the try clause is executed. If no exception occurs, the except clause is skipped and
execution of the try statement is finished. If an exception occurs in the try clause, the rest of
the clause is skipped. If the exception’s type matches the exception named after the except
keyword, then the except clause is executed. If the exception doesn’t match, then the
exception is unhandled and execution stops.
The except Clause
An except clause may have multiple exceptions, given as a parenthesized tuple:
A try statement can also have more than one except clause:
Finally
Finally, we have finally. finally is an optional block that runs after try, except, and else,
regardless of if an exception is thrown or not. This is good for doing any cleanup that
you want to happen, whether or not an exception is thrown.
As you can see, the Goodbye! gets printed just before the unhandled
KeyboardInterrupt gets propagated up and triggers the traceback.
Ad

Recommended

CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
faithxdunce63732
 
Python for loop
Python for loop
Aishwarya Deshmukh
 
Python Interview Questions And Answers
Python Interview Questions And Answers
H2Kinfosys
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
priestmanmable
 
Python cheat-sheet
Python cheat-sheet
srinivasanr281952
 
Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Python Objects
Python Objects
MuhammadBakri13
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
KrithikaTM
 
Lecture 14. Lamda, filter, map, zip.pptx
Lecture 14. Lamda, filter, map, zip.pptx
ikromovavazbek02
 
Chapter - 2.pptx
Chapter - 2.pptx
MikialeTesfamariam
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use cases
Srajan Mor
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Introduction To Python
Introduction To Python
shailaja30
 
Python slide.1
Python slide.1
Aswin Krishnamoorthy
 
Python For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
python1.ppt
python1.ppt
arivukarasi2
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
Python Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
Notes3
Notes3
hccit
 
3_MATLAB Basics Introduction for Engineers .pptx
3_MATLAB Basics Introduction for Engineers .pptx
SungaleliYuen
 
Introduction to biopython
Introduction to biopython
Suhad Jihad
 
Python Revision Tour.pptx class 12 python notes
Python Revision Tour.pptx class 12 python notes
student164700
 
Python1_Extracted_PDF_20250404_1054.pptx
Python1_Extracted_PDF_20250404_1054.pptx
ecomwithfaith
 
Lecture 09.pptx
Lecture 09.pptx
Mohammad Hassan
 
Phyton Learning extracts
Phyton Learning extracts
Pavan Babu .G
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 
Arrays in programming
Arrays in programming
TaseerRao
 
CPP homework help
CPP homework help
C++ Homework Help
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 

More Related Content

Similar to advanced python for those who have beginner level experience with python (20)

Lecture 14. Lamda, filter, map, zip.pptx
Lecture 14. Lamda, filter, map, zip.pptx
ikromovavazbek02
 
Chapter - 2.pptx
Chapter - 2.pptx
MikialeTesfamariam
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use cases
Srajan Mor
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Introduction To Python
Introduction To Python
shailaja30
 
Python slide.1
Python slide.1
Aswin Krishnamoorthy
 
Python For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
python1.ppt
python1.ppt
arivukarasi2
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
Python Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
Notes3
Notes3
hccit
 
3_MATLAB Basics Introduction for Engineers .pptx
3_MATLAB Basics Introduction for Engineers .pptx
SungaleliYuen
 
Introduction to biopython
Introduction to biopython
Suhad Jihad
 
Python Revision Tour.pptx class 12 python notes
Python Revision Tour.pptx class 12 python notes
student164700
 
Python1_Extracted_PDF_20250404_1054.pptx
Python1_Extracted_PDF_20250404_1054.pptx
ecomwithfaith
 
Lecture 09.pptx
Lecture 09.pptx
Mohammad Hassan
 
Phyton Learning extracts
Phyton Learning extracts
Pavan Babu .G
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 
Arrays in programming
Arrays in programming
TaseerRao
 
CPP homework help
CPP homework help
C++ Homework Help
 
Lecture 14. Lamda, filter, map, zip.pptx
Lecture 14. Lamda, filter, map, zip.pptx
ikromovavazbek02
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use cases
Srajan Mor
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Introduction To Python
Introduction To Python
shailaja30
 
Python For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
Python Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
Notes3
Notes3
hccit
 
3_MATLAB Basics Introduction for Engineers .pptx
3_MATLAB Basics Introduction for Engineers .pptx
SungaleliYuen
 
Introduction to biopython
Introduction to biopython
Suhad Jihad
 
Python Revision Tour.pptx class 12 python notes
Python Revision Tour.pptx class 12 python notes
student164700
 
Python1_Extracted_PDF_20250404_1054.pptx
Python1_Extracted_PDF_20250404_1054.pptx
ecomwithfaith
 
Phyton Learning extracts
Phyton Learning extracts
Pavan Babu .G
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 
Arrays in programming
Arrays in programming
TaseerRao
 

Recently uploaded (20)

4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Cadastral Maps
Cadastral Maps
Google
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
ieijjournal
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Microwatt: Open Tiny Core, Big Possibilities
Microwatt: Open Tiny Core, Big Possibilities
IBM
 
grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
KhadijaKhadijaAouadi
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
ijab2
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Cadastral Maps
Cadastral Maps
Google
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
ieijjournal
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Microwatt: Open Tiny Core, Big Possibilities
Microwatt: Open Tiny Core, Big Possibilities
IBM
 
grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
KhadijaKhadijaAouadi
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
ijab2
 
Ad

advanced python for those who have beginner level experience with python

  • 2. From the map() function, which applies a specified function to each element of an iterable and returns a new iterable with the modified elements, to the enumerate() function which adds a counter to an iterable and returns an iterable of tuples, these functions can help you write cleaner and more concise code. Let’s take a closer look at these advanced Python functions and see how to use them in your code.
  • 3. map() The map() function applies a specified function to each element of an iterable (such as a list, tuple, or string) and returns a new iterable with the modified elements. For example, you can use map() to apply the len() function to a list of strings and get a list of the lengths of each string:
  • 4. You can also use map() with multiple iterables by providing multiple function arguments. In this case, the function should accept as many arguments as there are iterables. The map() function will then apply the function to the elements of the iterables in parallel, with the first element of each iterable being passed as arguments to the function, the second element of each iterable being passed as arguments to the function, and so on. For example, you can use map() to apply a function to two lists element-wise: def multiply(x, y): return x * y a = [1, 2, 3] b = [10, 20, 30] result = map(multiply, a, b) print(result) # [10, 40, 90]
  • 5. reduce() The reduce() function is a part of the functools module in Python and allows you to apply a function to a sequence of elements in order to reduce them to a single value. For example, you can use reduce() to multiply all the elements of a list:
  • 6. You can also specify an initial value as the third argument to reduce(). In this case, the initial value will be used as the first argument to the function and the first element of the iterable will be used as the second argument. For example, you can use reduce() to calculate the sum of a list of numbers:
  • 7. filter() The filter() function filters an iterable by removing elements that do not satisfy a specified condition. It returns a new iterable with only the elements that satisfy the condition. For example, you can use filter() to remove all the even numbers from a list: def is_odd(x): return x % 2 == 1 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers = filter(is_odd, a) print(odd_numbers) # [1, 3, 5, 7, 9] You can also use filter() with a lambda function as the first argument: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers = filter(lambda x: x % 2 == 1, a) print(odd_numbers) # [1, 3, 5, 7, 9]
  • 8. zip() The zip() function combines multiple iterables into a single iterable of tuples. The zip() function stops when the shortest iterable is exhausted. For example, you can use zip() to combine two lists into a list of tuples: a = [1, 2, 3] b = ['a', 'b', 'c'] zipped = zip(a, b) print(zipped) # [(1, 'a'), (2, 'b'), (3, 'c')] You can also use zip() with more than two iterables: a = [1, 2, 3] b = ['a', 'b', 'c'] c = [True, False, True] zipped = zip(a, b, c) print(zipped) # [(1, 'a', True), (2, 'b', False), (3, 'c', True)]
  • 9. You can unpack the tuples in a zip() object by using the * operator in a function call or a list comprehension:
  • 10. enumerate() The enumerate() function adds a counter to an iterable and returns an iterable of tuples, where each tuple consists of the counter and the original element. For example, you can use enumerate() to loop over a list and print the index and value of each element:
  • 11. You can also specify a start value for the counter as the second argument to enumerate(): we covered some advanced Python functions that can be useful in your code. We looked at the map(), reduce(), filter(), zip(), and enumerate() functions, and provided examples of how to use them. These functions can help you write more efficient and concise code, and are worth exploring further.
  • 13. 1. What is a Module? A module in Python is a file that contains Python code (functions, classes, or variables) that you can reuse in your programs. Any Python file with the .py extension is a module. You can import a module into another program to access its functions or classes. 2. What is a Library? A library is a collection of modules or packages that provide pre-written functionality to simplify coding tasks. Example: Libraries like NumPy for arrays, Pandas for data analysis, and Matplotlib for plotting. 3. Importing Libraries and Modules You can import libraries or modules using the import statement.
  • 14. Basic Import Syntax: Importing Specific Functions or Classes
  • 16. 4. Installing External Libraries Using pip What is pip? ● pip is Python's package manager used to install external libraries that are not built into Python. ● Libraries like NumPy, Pandas, and Matplotlib are installed using pip. Installing a Library pip install library_name For example: pip install numpy pip install pandas
  • 18. Decimal Formatting: Formatting decimal or floating point numbers with f-strings is easy - you can pass in both a field width and a precision. The format is {value:width.precision}. Let’s format pi (3.1415926) to two decimal places - we’ll set the width to 1 because we don’t need padding, and the precision to 3, giving us the one number to the left of the decimal and the two numbers to the right Note how the second one is padded with extra spaces - the number is four characters long (including the period), so the formatter added six extra spaces to equal the total width of 10.
  • 19. Multiline Strings Sometimes it’s easier to break up large statements into multiple lines. Just prepend every line with f:
  • 20. Trimming a string Python strings have some very useful functions for trimming whitespace. strip() returns a new string after removing any leading and trailing whitespace. rstrip() and does the same but only removes trailing whitespace, and lstrip() only trims leading whitespace. We’ll print our string inside >< characters to make it clear: Note the different spaces inside of the brackets. These functions also accept an optional argument of characters to remove. Let’s remove all leading or trailing commas:
  • 21. Replacing Characters Strings have a useful function for replacing characters - just call replace() on any string and pass in what you want replace, and what you want to replace it with: str.format() and % formatting Python has two older methods for string formatting that you’ll probably come across at some point. str.format() is the more verbose older cousin to f-strings - variables appear in brackets in the string but must be passed in to the format() call. For example:
  • 22. Note that the variable name inside the string is local to the string - it must be assigned to an outside variable inside the format() call, hence .format(name=name). %-formatting is a much older method of string interpolating and isn’t used much anymore. It’s very similar to the methods used in C/C++. Here, we’ll use %s as our placeholder for a string, and pass the name variable in to the formatter by placing it after the % symbol. *******************************************************************
  • 23. Advanced Looping with List Comprehensions
  • 24. List Comprehensions List comprehensions are a unique way to create lists in Python. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be any kind of Python object. List comprehensions will commonly take the form of [<value> for <vars> in <iter>]. A simple case: Say we want to turn a list of strings into a list of string lengths. We could do this with a for loop: We can do this much easier with a list comprehension:
  • 25. We can also use comprehensions to perform operations, and the lists we assemble can be composed of any type of Python object. For example: In the above example, we assemble a list of tuples - each tuple contains the element “length” as well as each number from the len() function multiplied by two. Conditionals You can also use conditionals (if statements) in your list comprehensions. For example, to quickly make a list of only the even lengths, you could do: Here, we check divide every string length by 2, and check to see if the remainder is 0 (using the modulo operator).
  • 26. String Joining with a List Comprehension Back in our exercise on converting between types, we introduced the string.join() function. You can call this function on any string, pass it a list, and it will spit out a string with every element from the list “joined” by the string. For example, to get a comma-delimited list of numbers, you might be tempted to do: Unfortunately, you can’t join a list of numbers without first converting them to strings. But you can do this easily with a list comprehension:
  • 27. Some mathematical functions, such as sum, min, and max, accept lists of numbers to operate on. For example, to get the sum of numbers between zero and five, you could do: But remember, anywhere you can use a list, you can use a list comprehension. Say you want to get sum, minimum, and maximum of every number between 0 and 100 that is evenly divisible by 3? No sense typing out a whole list in advance, just use a comprehension:
  • 28. Exception Handling: Many languages have the concept of the “Try-Catch” block. Python uses four keywords: try, except, else, and finally. Code that can possibly throw an exception goes in the try block. except gets the code that runs if an exception is raised. else is an optional block that runs if no exception was raised in the try block, and finally is an optional block of code that will run last, regardless of if an exception was raised. We’ll focus on try and except for this chapter. First, the try clause is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs in the try clause, the rest of the clause is skipped. If the exception’s type matches the exception named after the except keyword, then the except clause is executed. If the exception doesn’t match, then the exception is unhandled and execution stops.
  • 29. The except Clause An except clause may have multiple exceptions, given as a parenthesized tuple: A try statement can also have more than one except clause:
  • 30. Finally Finally, we have finally. finally is an optional block that runs after try, except, and else, regardless of if an exception is thrown or not. This is good for doing any cleanup that you want to happen, whether or not an exception is thrown. As you can see, the Goodbye! gets printed just before the unhandled KeyboardInterrupt gets propagated up and triggers the traceback.