8  Python Primer

8.1 1. What is Python?

Python is a high-level, dynamically typed programming language created in the late 1980s by Guido van Rossum. It emphasizes readability, simplicity, and developer productivity. Python code often looks more like pseudocode, making it accessible and easy to learn. It is widely used for web development, scientific computing, data analysis, artificial intelligence, scripting, and general software engineering. Its large standard library and active open-source ecosystem allow developers to tackle nearly any problem domain.

One of Python’s chief advantages is its community support: PyPI (the Python Package Index) hosts hundreds of thousands of open-source packages ranging from numeric and scientific libraries (NumPy, Pandas, SciPy) to web frameworks (Django, Flask) and more. Because Python is so popular, you will find plenty of tutorials, books, and community forums to guide you as you learn.

8.2 2. Getting Started

With Microsoft Fabric, Python is already available in all notebooks! If you plan to just use Python and not PySpark, don’t forget to switch to “Python” in the kernel selection. Your code will work with “PySpark”, but it will require more resources than necessary.

The language selector in a Fabric notebook

8.3 3. Basic Syntax and Data Types

8.3.1 Hello World

print("Hello, world!")
Unable to display output for mime type(s): application/vnd.jupyter.statement-meta+json
Hello, world!

Printing to the screen in Python is as simple as calling print(). That function can handle strings, numbers, and more complex data structures.

8.3.2 Variables and Types

Python is dynamically typed, which means you don’t explicitly declare a variable’s type. Instead, you assign a value and Python infers its type:

# Different types of variables
my_int = 10                  # Integer
my_float = 3.14              # Float
my_string = "Hello, Python!" # String
my_bool = True               # Boolean
Unable to display output for mime type(s): application/vnd.jupyter.statement-meta+json

8.3.2.1 Inspecting and Dumping Variables

  • Check the type:

    print(type(my_int))  # e.g., <class 'int'>
  • Dump or print the value:

    print(my_int)        # 10
  • See available attributes/methods:

    print(dir(my_int))
  • Get built-in documentation:

    help(my_int)

    These commands are extremely helpful when you’re trying to understand or debug your code.

print(type(my_int))
print("---")
print(my_int)
print("---")
print(dir(my_int))
print("---")
help(my_int)

8.3.3 Printing more than a number

Sometimes, you need to print or save a properly formatted string, composed of several values. This is where F-String comes handy. It allows you to write a string as it should be, and replace placeholders with values from the current context. You can even call your own function! (Just think about performance first)

def greet():
    return "Please welcome on stage, "

firstName = "Christopher"
role = "Cloud Advocate"
company = "Microsoft"
print(f"{greet()}{firstName} is a {role} at {company}")
Unable to display output for mime type(s): application/vnd.jupyter.statement-meta+json
Please welcome on stage, Christopher is a Cloud Advocate at Microsoft

8.3.4 Built-In Data Structures

  1. Lists: Mutable sequences for storing ordered collections of items.

    fruits = ["apple", "banana", "cherry"]
    fruits.append("orange")
  2. Tuples: Immutable sequences, used for storing fixed collections.

    coordinates = (10, 20)
  3. Dictionaries: Key-value stores, similar to hash maps in other languages.

    person = {"name": "Alice", "age": 30}
    person["location"] = "New York"
  4. Sets: Unordered collections of unique items.

    colors = {"red", "green", "blue"}
    colors.add("yellow")
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
coordinates = (10, 20)
person = {"name": "Alice", "age": 30}
person["location"] = "New York"
colors = {"red", "green", "blue"}
colors.add("yellow")

print(person["location"])
Unable to display output for mime type(s): application/vnd.jupyter.statement-meta+json
New York

8.4 4. Control Flow

8.4.1 Conditionals

Python uses if, elif, and else for conditional logic. Indentation is syntax, meaning blocks of code are separated by consistent whitespace (usually four spaces).

if my_int > 10:
    print("Greater than 10")
elif my_int == 10:
    print("Exactly 10")
else:
    print("Less than 10")

8.4.2 Loops

  1. for loops typically iterate over lists, ranges, or other iterables:

    for fruit in fruits:
        print(fruit)

    You can also iterate over a sequence of numbers:

    for i in range(5):  # 0 through 4
        print(i)
  2. while loops execute a block of code as long as a condition remains true:

    count = 0
    while count < 5:
        print(count)
        count += 1

8.5 5. Functions and Modules

8.5.1 Defining Functions

You create functions in Python using the def keyword, followed by a name and parentheses. Indentation defines the function body:

def greet(name):
    return f"Hello, {name}!"

message = greet("Alice")
print(message)

Python also supports default parameter values:

def greet(name="World"):
    print(f"Hello, {name}!")

8.5.2 Modules and Imports

Any .py file can serve as a module. You can import your own or third-party modules to reuse code:

# my_module.py
def add(a, b):
    return a + b

# main.py
import my_module
result = my_module.add(2, 3)
print(result)

Use from my_module import add to import only specific functions.


8.6 6. Object-Oriented Programming (OOP)

Python supports OOP with classes, inheritance, and more. Here’s a quick example: - The __init__ method is the constructor.
- self refers to the instance.
- Subclasses inherit properties and methods from their parent classes.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"{self.name} makes a sound.")

class Dog(Animal):
    def speak(self):
        print(f"{self.name} barks!")

dog = Dog("Fido")
dog.speak()  # Output: "Fido barks!"
Unable to display output for mime type(s): application/vnd.jupyter.statement-meta+json
Fido barks!

8.7 7. Error Handling

Python uses exceptions to handle errors. You can raise and catch exceptions:

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("Cannot divide by zero:", e)
finally:
    print("This block always executes.")
Unable to display output for mime type(s): application/vnd.jupyter.statement-meta+json
Cannot divide by zero: division by zero
This block always executes.

8.8 8. Next Steps

  • Package Management: Use pip install or Fabric environments to manage external libraries.
  • Coding Style: Follow PEP 8 for style guidelines.
  • Testing: Use unittest or pytest for writing and running automated tests.
  • Documentation: Python’s built-in docstrings allow you to document your functions and classes inline. You could also access the Python documentation at docs.python.org.
Back to top