Advanced
Programming
Chapter 2
Chapter Outline
1. Advanced Python techniques
1.2 Lambda Operator
1.3 Filter
1.4 Reduce
1.4 Map
2. Regular Expressions
3. Unit Tests
5. Parsing
6. GUI Applications
1. Advanced python techniques
1.1 Python lambda
In Python, a lambda function is an anonymous function
meaning it is defined without a name. Unlike regular
functions defined using def keyword, lambda functions are
created using lambda keyword.
They are useful for writing small, simple functions in a
concise way, especially when you need a function
temporarily.
Syntax : lambda arguments : expression
Explanation: calc creates an anonymous function that checks
if a number is divisible by 2. If yes, returns "Even number",
otherwise "Odd number".
Key Properties of Lambda Functions
1. Lambda functions can have any number of arguments but
only one expression.
2. The expression is evaluated and returned automatically no
explicit return needed.
3. Lambda functions are syntactically restricted to a single
expression (no multiple statements or commands).
4. They are often used where small, one-off function objects
are required for example, as arguments to other functions.
Note: Lambda functions cannot contain multiple statements (like
print). Using def is better for complex operations.
1.2 Filter ()
filter() function is used to extract elements from an iterable
(like a list, tuple or set) that satisfy a given condition. It
works by applying a function to each element and keeping
only those for which function returns True.
Parameters:
function: tests each element and if return, True - Keep the
element, if False - Discard the element
iterable: Any iterable (list, tuple, set, etc.).
Syntax : filter(function, iterable)
Using filter() with a Lambda Function
Explanation: filter(lambda x: x % 2 == 0, a) keeps only
numbers divisible by 2 (even numbers).
1.3 Reduce ()
reduce() function (from functools) applies a function
cumulatively to an iterable, reducing it to a single value. It’s
handy for concise tasks like summing, multiplying (factorial),
finding max/min, concatenating strings or flattening lists.
Use it for simple one-line reductions, avoid it for complex
logic (loops are clearer) or when intermediate results are
needed.
Syntax : It’s a method of functools module, so we need
to import it before use:
from functools import reduce
reduce(function, iterable[, initializer])
Parameters:
•function: A function that takes two arguments and
returns a single value.
•iterable: The sequence to be reduced (list, tuple, etc.).
•initializer (optional): A starting value that is placed before
first element.
1.4 Map ()
map() function in Python applies a given function to
each element of an iterable (list, tuple, set, etc.) and
returns a map object (iterator). It is a higher-order
function used for uniform element-wise
transformations, enabling concise and efficient code.
Syntax : map(function, iterable,..)
Explanation: map() applies int() to each element
in s which changes their datatype from string to int.
Parameters:
function: The function to apply to every element of the
iterable.
iterable: One or more iterable objects (list, tuple, etc.)
whose elements will be processed.
Note: You can pass multiple iterables if the function
accepts multiple arguments.
map() with multiple iterables
We can use map() with multiple iterables if the function
we are applying takes more than one argument.
2. Regular Expressions
Regular expressions (regex) offer a powerful method for
searching, matching, and manipulating text based on defined
patterns. They are widely used for tasks such as data
validation, and information extraction.
2.1 Advanced Regular Expression
A Regular Expression or RegEx is a special sequence of
characters that uses a search pattern to find a string or set of
strings.
It can detect the presence or absence of a text by matching it
with a particular pattern and also can split a pattern into one
or more sub-patterns.
• Regex Module in Python
Python provides a built-in module called re for working with
regular expressions. This module can be imported using the
import statement.
import re
• Regex Functions
The re module in Python provides various functions that help
search, match, and manipulate strings using regular
expressions.
The following are the main functions provided by re module :
Function Description
[Link]() finds and returns all matching occurrences in a list
[Link]() Regular expressions are compiled into pattern objects
[Link]() Split string by the occurrences of a character or a
pattern.
[Link]() Replaces all occurrences of a character or patter with a
replacement string.
resubn It's similar to [Link]() method but it returns a tuple:
(new_string, number_of_substitutions)
[Link]() Escapes special character
[Link]() Searches for first occurrence of character or pattern
• [Link]()
Returns all non-overlapping matches of a pattern in the
string as a list. It scans the string from left to right.
Example the following code uses regular expression \d+ to
find all sequences of one or more digits in the given string.
• [Link]()
Compiles a regex into a pattern object, which can be reused
for matching.
Example : This pattern [a-e] matches all lowercase letters
between 'a' and 'e', in the input string
Example 2 : The code uses regular expressions to find and list
all single digits and sequences of digits in the given input
strings. It finds single digits with \d and sequences of digits
with \d+
Example 3 : Word and non-word characters
\w matches a single word character.
\w+ matches a group of word characters.
\W matches non-word characters.
• [Link]()
Splits a string wherever the pattern matches. The remaining
characters are returned as list elements.
Syntax : [Link](pattern, string, maxsplit=0, flags=0)
• pattern: Regular expression to match split points.
• string: The input string to split.
• maxsplit (optional): Limits the number of splits. Default is 0 (no limit).
• flags (optional): Apply regex flags like [Link].
Example 1 : Splitting by non-word characters or digits
Split a string using different patterns like group of word characters (\W+),
and digits (\d+).
Example 2: Using maxsplit and flags
This example shows how to limit the number of splits using maxsplit,
and how flags can control case sensitivity.
Note: In the second and third cases of the above , [a-f]+ splits the
string using any combination of lowercase letters from 'a' to 'f'. The
[Link] flag includes uppercase letters in the match.
• [Link]()
The [Link]() function replaces all occurrences of a pattern in a string
with a replacement string.
[Link](pattern, repl, string, count=0, flags=0)
• pattern: The regex pattern to search for.
• repl: The string to replace matches with.
• string: The input string to process.
• count (optional): Maximum number of substitutions (default is 0, which means
replace all).
• flags (optional): Regex flags like [Link]
Example 1: Using maxsplit and flags
The following examples show different ways to replace the pattern 'ub' with
'~*', using various flags and count values.
import re
# Case-insensitive replacement of all 'ub'
print([Link]('ub', '~*', 'Subject has Uber booked already', flags=[Link]))
# Case-sensitive replacement of all 'ub'
print([Link]('ub', '~*', 'Subject has Uber booked already'))
# Replace only the first 'ub', case-insensitive
print([Link]('ub', '~*', 'Subject has Uber booked already', count=1, flags=[Link]))
# Replace "AND" with "&", ignoring case
print([Link](r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=[Link]))
• [Link]()
[Link]() function works just like [Link](), but instead of returning
only the modified string, it returns a tuple: (new_string,
number_of_substitutions)
[Link](pattern, repl, string, count=0, flags=0)
Example 1: Substitution with count
This example shows how [Link]() gives both the replaced
string and the number of times replacements were made.
import re
# Case-sensitive replacement
print([Link]('ub', '~*', 'Subject has Uber booked already'))
# Case-insensitive replacement
t = [Link]('ub', '~*', 'Subject has Uber booked already', flags=[Link])
print(t)
• [Link]()
[Link]() function adds a backslash (\) before all special characters
in a string. This is useful when you want to match a string literally,
including any characters that have special meaning in regex (like ., *, [,
], etc.).
[Link](string)
Example 1: Escaping special characters
This example shows how [Link]() treats spaces, brackets,
dashes, and tabs as literal characters. It is useful when you
want to match a string exactly as it is, without letting special
characters be interpreted as part of a regular expression.
Explanation :[Link]() automatically adds backslashes
before all characters that have a special meaning in regular
expressions (like [ ,] ,-,$ , , or whitespace), ensuring they are
matched literally.
• [Link]()
The [Link]() function searches for the first occurrence of a pattern
in a string. It returns a match object if found, otherwise None.
Note : Use it when you want to check if a pattern exists or
extract the first match.
Syntax [Link](pattern, string, flags=0)
Parameters:
pattern: A regex pattern to search for.
string: The target string where the pattern is searched.
flags (optional): Modifiers that change matching behavior (e.g., case-
insensitive); default is 0.
Example 1: Search and extract values
This example searches for a date pattern with a month name
(letters) followed by a day (digits) in a sentence.
Example 2: In this example, we search for the first number
that appears in a given string using a regular expression.
1.3 Unit Tests
Unit testing plays a vital role in Python software
development. It focuses on verifying the correctness of small,
independent components of code, known as “units.”
Detecting issues at an early stage helps improve code quality,
minimize production bugs, and ensure that programs remain
reliable and easy to maintain.
Key points:
• Each test focuses on a specific part of the code to verify its
correctness.
• Errors are identified early, preventing issues from spreading.
• Unit tests improve overall code reliability and simplify
future maintenance.
Unit Testing Frameworks
Python has several frameworks to help write and run unit
tests efficiently:
1. unittest: Built into Python’s standard library.
2. pytest: Simplified syntax and powerful features.
3. nose: Extends unittest for easier testing.
4. doctest: Tests examples written in docstrings.
Implementation of Unit Test
1. Unittest
Unittest is Python’s built-in framework for writing and running
tests. It helps to verify that the code behaves as expected by
organizing tests into reusable test cases. To use it, start by
importing library:
import unittest
Example: This example shows how to create a unit test using
the unittest framework. It defines a test class with a method
that checks correctness of a calculation.
If The result of addition is true :
If The result of addition is false(we use 9 as a result) :
Explanation:
• TestAddition inherits from [Link], giving access
to testing methods.
• test_add_numbers calculates sum of data and checks it
using [Link](result, 8).
• If the assertion passes, test succeed if it fails, unittest shows
an error with expected vs. actual values.
TestCase gives you a collection of built-in methods to check whether your
code behaves as expected.
Method Purpose
assertEqual(a, b) Checks that a == b
assertNotEqual(a, b) Checks that a != b
assertTrue(x) Checks that x is True
assertFalse(x) Checks that x is False
assertIsNone(x) Checks that x is None
assertIn(a, b) Checks that a is in b
2. Pytest
Pytest is a powerful and flexible testing framework for Python
that simplifies the process of writing and executing tests. It
supports existing unittest test cases while providing additional
advantages, such as:
• Using Python’s native assert statements for improved
readability.
• Resuming execution from the last failing test without
rerunning the entire test suite.
Example 1: Here, we will make a file named
as math_functions.py containing functions to add and
subtract two numbers.
test_math_functions.py. We are making this file to perform
testing using pytest using sample inputs.
Explanation:
math_functions.py has functions to test
and test_math_functions.py has test cases.
Pytest automatically finds functions (*) exists in
math_functions.py.
assert checks if output matches expected result, failures
are reported by pytest.
Pytest can also run unittest cases, but here we use plain
pytest-style assertions.
3. Using Nose
Nose is a testing framework test runner that extends
capabilities of Python's built-in unittest module. It
provides a simpler syntax for writing tests and offers
additional features for test discovery, parallel test
execution and plugin support.
Example: We will create a file named [Link] with test
functions to check basic addition and subtraction.
Explanation:
• Nose automatically detects functions whose contains
the tests.
• It allows writing simple test functions with plain assert
statements, avoiding boilerplate required by unittest.
4. Using Doctest
Doctest checks that the examples written in your
function’s documentation actually produce the results
shown ensuring that your documentation and code stay
consistent.
• Scans those docstrings.
• Executes the code examples it finds.
• Compares the actual output with the expected output
written in the docstring.
• Reports any mismatches as test failures.
Example: Let’s create a file named [Link] and write doctest-
based tests directly in the function docstrings. These examples
will automatically check if the functions work correctly.
If the output matches the expected values, the test passes.
Else :
Explanation:
Tests are written as examples in the function docstrings
using >>>.
doctest checks if the output matches the expected
results.
1.4 Parsing expressions in Python
Parsing, also called syntactic analysis, is the process of
breaking down a string or sequence of characters into a
structured data format that a computer can understand such
as a syntax tree. The Main Categories of Parsing:
1. Syntactic Parsing (Syntax Analysis) :
• Focuses on checking the grammatical structure of the
input and ensures that the input follows the correct
syntax rules.
2. Semantic Parsing (Semantic Analysis) :
• Deals with the meaning of the input once its syntax
has been validated.
• It checks the logical consistency and validity of the
expression or statement.
Tools and Libraries for Parsing in Python
Module AST (Abstract Syntax Tree):
This module is used to analyze Python source code and
convert it into an Abstract Syntax Tree (AST).
An AST is a tree-like structure that represents the
syntactic structure of the code each node of the tree
corresponds to a language construct (like an expression,
statement, or operation).
Example:
Output :
Pyparsing
simplifies building grammars (rules) that describe how text
should be parsed.
It helps you extract structured information from strings without
writing complex regular expressions.
Example:
Explanation:
• Word(nums) matches a sequence of digits (e.g., “3” or “4”).
• Literal(‘+’)matches the '+' symbol exactly.
• The result ['3', '+', '4'] shows that the string has been
decomposed according to the defined grammar.
1.5 GUI Applications (Graphical User Interface)
A GUI application in Python is a program that uses
graphical elements to provide an interactive interface for
users, enabling them to perform tasks visually through
components like buttons, labels, and text fields, typically
built with libraries such as Tkinter, PyQt, or Kivy
Building a GUI in Python
1. GUI Libraries :
• Tkinter A built-in Python library, ideal for beginners.
• PyQt / PySide Provide advanced, professional-looking
interfaces with greater flexibility and customization
options.
1. Tkinter :
is a built-in Python library for creating Graphical User
Interfaces (GUIs). It offers a collection of tools and
widgets that allow developers to design desktop
applications with interactive graphical elements. Since
Tkinter comes pre-installed with most Python
distributions, it enables developers to build GUI
applications easily without needing to install external
packages or dependencies.
The term "Tkinter" originates from "Tk interface", as it
serves as Python’s interface to the Tk GUI toolkit. It enables
developers to create windows, buttons, labels, text fields,
and other graphical components for building interactive
desktop applications.
Tkinter = Python’s interface to Tk.
Tk = the graphical system that handles how everything looks
and behaves on screen.
Using Tkinter for :
Creating windows and dialog boxes: Tkinter allows
developers to design windows and dialog boxes that
facilitate user interaction. These elements can display
information, collect input, or offer users various options.
Developing custom widgets: In addition to its wide range
of built-in widgets like buttons, labels, and text fields,
Tkinter supports the creation of personalized widgets
tailored to specific application needs.
Designing desktop application interfaces: Tkinter enables
the development of complete desktop GUIs,
incorporating buttons, menus, and other interactive
components to enhance usability.
Prototyping user interfaces: Tkinter is ideal for rapidly
prototyping GUI designs, allowing developers to
experiment with layouts and functionality before
finalizing the application.
Fundamental structure of Tkinter program
Get Tkinter module
Import the tkinter module :
From tkinter import *
Or
Import tkinter
GUI Widgets
• Label
• Entry
• Button
• Frame
• Menu
• Message
• Radio Button
• Checkbox
Basic Structure of a GUI Program
1. Import the library
2. Create a main window using Tk
3. Add widgets (buttons, labels, etc.)
4. Call main event loop.
Label Widgets
Used to show text on the window
Label Widgets
Button
A label that we can click
Button
Get User Input
We can get a user input using entry widgets
Get User Input
We can get a user input using entry widgets
Entry widgets Operation
• [Link]() :
To get user input
• [Link]() :
To delete specific values of complete data
• [Link]() :
To insert values
Entry Operations
Text Operation
• [Link](index,string) :
Inserts the specified text at the given position in the
text box.
• [Link](start_index, end_index) :
Deletes text from the given start index up to the end
index (or one character if no end is specified)
• [Link](start_index, end_index) :
Retrieves the text between the specified start and end
positions.
Text Operation
Frame Widgets
• It is the top level widgets which contains other widgets
• It is used to orgnize the layout of the widgets.
• It is used for the logical grouping of other widgets.
Frame Widgets
Frame types
Frame types
Layout Managment
We can arrange the widgets in different layout
• Pack :
It packs widgets next to each other either vertically or
horizontally.
• Grid:
It organizes widgets in a row-column structure, just like a
spreadsheet or HTML table.
• Place :
It allows you to position widgets exactly where you want
them using x and y coordinates.
Pack()
Pack()
Grid()
Grid()
Place()
Place()
• Not ideal for very complex, highly-customized or
media-rich UIs.
• Typical use cases: small desktop tools, teaching GUI
basics, quick admin utilities.