Robin.te.Hofstee

Python Fundamentals Cheat Sheet for Scripting

Robin te Hofstee5 min readViews1
Python Fundamentals Cheat Sheet for Scripting

A concise guide for developers transitioning into Python scripting, covering core data structures, control flow, functions, and best practices.

Introduction

Welcome to the first installment of the "Python Scripting Series," designed to help developers transition into Python scripting with ease. This guide will cover the core fundamentals of Python, including data structures, control flow, and function definitions. We will also touch on some best practices to ensure your scripts are clean and efficient. Each section includes practical code snippets to illustrate the concepts.

Core Data Structures

Python offers several built-in data structures to help you organize and manipulate data effectively. Let’s explore the most commonly used ones.

Lists

Lists are ordered, mutable sequences of items. You can store any type of data in a list, and elements can be accessed using indices.

# Creating a list
fruits = ['apple', 'banana', 'cherry']
 
# Accessing elements
print(fruits[0])  # Output: apple
 
# Adding elements
fruits.append('date')
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'date']
 
# Removing elements
fruits.remove('banana')
print(fruits)  # Output: ['apple', 'cherry', 'date']

Dictionaries

Dictionaries store key-value pairs. Keys must be unique and immutable, while values can be of any data type.

# Creating a dictionary
person = {'name': 'Alice', 'age': 25}
 
# Accessing values
print(person['name'])  # Output: Alice
 
# Adding key-value pairs
person['location'] = 'New York'
print(person)  # Output: {'name': 'Alice', 'age': 25, 'location': 'New York'}
 
# Removing key-value pairs
del person['age']
print(person)  # Output: {'name': 'Alice', 'location': 'New York'}

Sets

Sets are unordered collections of unique elements. They are useful for operations involving uniqueness and membership testing.

# Creating a set
unique_numbers = {1, 2, 3, 4, 5}
 
# Adding elements
unique_numbers.add(6)
print(unique_numbers)  # Output: {1, 2, 3, 4, 5, 6}
 
# Removing elements
unique_numbers.remove(3)
print(unique_numbers)  # Output: {1, 2, 4, 5, 6}

Tuples

Tuples are similar to lists but are immutable, meaning you cannot change their elements after creation.

# Creating a tuple
coordinates = (10, 20)
 
# Accessing elements
print(coordinates[0])  # Output: 10
 
# Tuples are useful for fixed-length data
point = (10.5, 20.5)
print(point)  # Output: (10.5, 20.5)

Control Flow

Control flow in Python allows you to control the order of execution in your scripts. This is essential for making decisions and handling different scenarios.

If/Elif/Else Statements

Conditional statements are used to execute different blocks of code based on certain conditions.

# Example of if/elif/else
number = 10
if number > 10:
    print("Number is greater than 10")
elif number == 10:
    print("Number is 10")
else:
    print("Number is less than 10")

For Loops

For loops are used to iterate over sequences like lists, tuples, and dictionaries.

# Example of for loop
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

While Loops

While loops continue to execute as long as a certain condition is true.

# Example of while loop
count = 0
while count < 5:
    print(count)
    count += 1

Defining Functions

Functions are blocks of organized, reusable code that perform a specific task. They help make your code more modular and easier to manage.

# Defining a function
def greet(name):
    return f"Hello, {name}!"
 
# Calling the function
print(greet('Alice'))  # Output: Hello, Alice!

Best Practices for Clean Syntax

Writing clean and readable code is crucial for maintaining and scaling your scripts. Here are some best practices to follow:

  1. Use Meaningful Variable Names: Choose names that clearly describe the purpose of the variable.
  2. Keep Functions Small and Focused: Each function should have a single responsibility.
  3. Use Docstrings: Document your functions and modules with docstrings to provide clear explanations.
  4. Consistent Indentation: Use consistent indentation (4 spaces) to make your code easy to read.
  5. Error Handling: Use try-except blocks to handle errors gracefully.
# Example of a function with a docstring and error handling
def divide(a, b):
    """
    Divide two numbers.
    """
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        return "Error: Division by zero"

Conclusion

This guide has covered the essential elements of Python scripting, from data structures to control flow and function definitions. By following these fundamentals, you will be well-prepared to write effective and maintainable scripts. In the next part of the series, we will dive deeper into advanced Python features and best practices. Stay tuned!


Tutorial series

Python Scripting Series

A step-by-step Python series for self-hosters and developers: from your first script and a clean environment to databases and local AI APIs.

  1. 1.Python Fundamentals Cheat Sheet for Scripting

8 more parts coming soon.

Share this post
Robin te Hofstee

Written by Robin te Hofstee

Technology enthusiast with a deep love for programming. Sharing practical guides on React, Next.js, Linux and self-hosting.