Python Fundamentals: Built-in Functions, User-defined Functions, and Path Manipulation ¶

This notebook demonstrates Python's built-in functions, such as print(), range(), and enumerate(), as well as user-defined functions and key language concepts. It also covers file-system navigation and path manipulation using the pathlib library, including rglob(), Path.cwd(), Path.exists(), and Path.resolve()

Major Topics Covered¶

  • Python print() function

    • Printing text
    • Printing variables
    • Formatting output
    • Using sep and end
  • Python User-defined functions

    • Defining functions
    • Calling functions
    • Using parameters
  • File searching with pathlib

    • Creating Path objects
    • Recursive searches with rglob()
    • Finding files by name
    • Displaying file paths
  • Practical examples

    • Custom report headers
    • Searching for Jupyter notebooks
    • Working with directories and files

Explanation of the Code Block Below¶

This code demonstrates Python's print() function with strings, newline characters, and numeric data types.¶
In [118]:
print("Hello, World!")
print("\nNumbers:")
print(100)
print(3.14159)
Hello, World!

Numbers:
100
3.14159

Explanation of the Code Block Below¶

This code demonstrates how Python's print() function can display multiple arguments and handle variables alongside string literals¶
  • print("\nLabels and Values:")

    • "\n" inserts a newline character, creating a blank line before the text for better readability
    • "Labels and Values:" is a string literal that prints as a section header
    • Output: Creates visual separation, then displays Labels and Values:
  • print("Name:", name)

    • print() accepts multiple arguments separated by commas
    • "Name:" is a string literal (the label)
    • Name is a variable whose value will be displayed
    • Python automatically adds a space between arguments when printing
    • Output example: Name: Alice (if name = "Alice")
In [87]:
print("\nLabels and Values:")
print("Name:", name) 
print("Age:", age)
Labels and Values:
Name: Alice
Age: 25

Explanation of the Code Block Below¶

This code demonstrates how print() displays variable values that have been defined elsewhere in the program.¶
  • print(name)
    • Prints the value stored in the variable name
    • The variable must be defined earlier in the code (e.g., name = "Alice")

Output: Whatever value name holds (e.g., Alice)

In [85]:
print("\nVariables:")
print(name)
print(age)
Variables:
Alice
25

Explanation of the Code Block Below¶

This code demonstrates how print() displays a Python dictionary, a built-in data structure for storing key-value pairs.¶
  • print("\nDictionary Example:")

    • "\n" creates a newline (blank line) for visual separation
    • "Dictionary Example:" prints as a section header
    • Output: Creates spacing, then displays Dictionary Example:
  • person = {"Name": "Alice", "Age": 25}

    • Creates a dictionary named person
    • Dictionaries use curly braces {} with key-value pairs
    • "Name": "Alice" — key is "Name", value is "Alice" (a string)
    • "Age": 25 — key is "Age", value is 25 (an integer)
    • Key-value pairs are separated by commas
  • print(person)

    • Prints the entire dictionary object
    • Output displays the dictionary in its string representation

This code shows how Python handles structured data with dictionaries, a fundamental concept for data organization.

In [14]:
print("\nDictionary Example:")
person = {"Name": "Alice", "Age": 25}
print(person)
Dictionary Example:
{'Name': 'Alice', 'Age': 25}

Explanation of the Code Block Below¶

This code demonstrates how print() can display the result of arithmetic operations on variables.¶
In [16]:
print("\nCalculation:")
x = 10
y = 20
print(x + y)
Calculation:
30

Explanation of the Code Block Below¶

This code demonstrates the sep parameter of the print() function, which controls how multiple arguments are separated in the output.¶
In [18]:
print("\nSeparator Example:")
print("A", "B", "C", sep="-")
Separator Example:
A-B-C

Explanation of the Code Block Below¶

This code demonstrates the end parameter of the print() function, which controls what appears at the end of each printed line.¶
In [110]:
print("\nEnd Example:")
print("Python", end=" ")
print("Programming")
End Example:
Python Programming

Explanation of the Code Block Below¶

This code demonstrates how print() displays a Python list, a built-in data structure for storing ordered collections of items.¶
In [80]:
print("\nList Example:")
colors = ["Red", "Green", "Blue"]
print(colors)
List Example:
['Red', 'Green', 'Blue']

Explanation of the Code Block Below¶

  • Create a list named fruits containing three strings.
  • Find the length of the list: len() returns the number of items in the list.
  • Create a range of index numbers using range(len(fruits)).
  • The for loop iterates through the index numbers and prints each index and its corresponding fruit.
In [35]:
fruits = ["Apple", "Banana", "Orange"]  # create the list containing three strings

for i in range(len(fruits)):
    print(i, fruits[i])
0 Apple
1 Banana
2 Orange

Explanation of the Code Block Below¶

This code demonstrates Python's enumerate() built-in function, which adds a counter to iterable objects like lists, making it easy to loop through items with their index positions.¶
enumerate() in Python¶

In Python, compared to range(), enumerate() is often clearer because it avoids repeatedly writing fruits[i] and directly provides both the index and the corresponding item.

enumerate(iterable, start=1)
  • iterable — a list, tuple, string, or other iterable object.
  • start — the starting index; 1 in this example.
In [56]:
fruits = ["Apple", "Banana", "Orange"]

for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
1 Apple
2 Banana
3 Orange

Explanation of the Code Block Below¶

This code defines a user-defined function named print_header() that creates a formatted section header with decorative lines.¶
  • def print_header(title):

    • def keyword defines a new function
    • print_header is the function name
    • (title) is a parameter that accepts input when the function is called
    • The colon : indicates the start of the function body
  • print("\n" + "=" * 70)

    • "\n" creates a newline for spacing before the header
    • "=" * 70 uses string multiplication to repeat "=" 70 times
      • concatenates the newline with the 70 equal signs
    • Output: A blank line followed by a line of 70 equal signs
  • print(title)

    • Prints the title argument passed to the function
    • This is the customizable header text
  • print("=" * 70)

    • Prints another line of 70 equal signs to close the header box
In [135]:
def print_header(title):
    print("\n" + "=" * 70)
    print(title)
    print("=" * 70)

User-Defined Function Above: Code explanation¶

  • Function definition: def creates reusable code blocks
  • Parameters: title accepts input values
  • String multiplication: "=" * 70 repeats characters
  • String concatenation: + joins strings together
In [99]:
# Code reusability: Call the function multiple times with different titles
print_header("BASIC PRINT EXAMPLES")
======================================================================
BASIC PRINT EXAMPLES
======================================================================

Explanation of the Code Block Below¶

This code demonstrates file-system navigation using Python's pathlib library, specifically the rglob() method to recursively search for Jupyter Notebook files matching a pattern.¶
In [102]:
from pathlib import Path

root = Path(r"C:\Explore")
count = 0
for file in root.rglob("*.ipynb"):

    if "understandpythonenvironment" in file.stem.lower():

        count += 1
        print(file.resolve())

print(f"\nTotal matches found: {count}")
C:\Explore\Python\UnderstandPythonEnvironment.ipynb
C:\Explore\Python\.ipynb_checkpoints\UnderstandPythonEnvironment-checkpoint.ipynb

Total matches found: 2
The above code shows how to efficiently search and filter files in a directory tree using pathlib.¶

Explanation of the Code Block Below¶

This code demonstrates how to retrieve and display the current working directory and home directory using pathlib, formatted with the custom print_header() function defined earlier.¶
In [182]:
# ------------------------------------------------------------------
# Environment Information
# ------------------------------------------------------------------

print(Path.cwd())

print(Path.home())

print_header("SCRIPT COMPLETE")
c:\Explore\Python
C:\Users\pmuhuri

======================================================================
SCRIPT COMPLETE
======================================================================

Explanation of the Code Block Below¶

This code demonstrates file-system searching using pathlib's rglob() method to find a specific Jupyter Notebook file while excluding virtual document copies.¶
In [45]:
from pathlib import Path

root = Path(r"C:\Explore")

for file in root.rglob("PrintFunctionsAndPathlib.ipynb"):
    if ".virtual_documents" not in str(file):
        print(file)        
C:\Explore\Python\PrintFunctionsAndPathlib.ipynb

What This Notebook Demonstrates¶

Functions¶
  • print()
  • print_header()
  • range()
  • enumerate()
Path Methods¶
  • exists()
  • resolve()
  • rglob()
  • cwd()
  • home()
Library and Class¶
  • pathlib
  • Path
Python Concepts¶
  • Variables
  • Strings
  • Numbers
  • Lists
  • Dictionaries
  • Loops
  • Conditional statements (if)
  • Function definitions
  • File-system navigation with pathlib
  • Recursive file searching
In [ ]: