Python Snippets
Command Line Snippets
Section titled “Command Line Snippets”# Active an environment## Linux Ubuntubashpython3 -m virtualenv ./venvsource ./venv/bin/activatepip install -r requirements.txtpython3 mypythonprogram.py## or use conda instead
## Windows (PowerShell)python -m venv ./venv./venv/Scripts/Activatepip install -r .\requirements.txtpython mypythonprogram.py
## Upgrade a packagepython3 -m pip install --upgrade pippython3 -m pip install --upgrade ansible## Upgrade a package as userpython3 -m pip install --user --upgrade pip## List installed packagespython3 -m pip list
## Install applications with pipxpipx install ansible## orpython3 -m pipx install ansible## Upgrade all pipx packagespipx upgrade-all
# Debug a script with Python Debugger (PDB)python -m pdb pyfile.py# See https://docs.python.org/3/library/pdb.html# Commands are similar to GDB
Jupyter notebooks
Section titled “Jupyter notebooks”# Start Jupyter Notebook in current directoryjupyter notebook
# Jupyter Notebook - org conversions## https://michaelneuper.com/posts/replace-jupyter-notebook-with-emacs-org-mode/## Importing existing Jupyter Notebooks into Org Mode## Use jupytext (python package) to convert Jupyter Notebooks to Org Mode files:## Convert your Jupyter Notebook (.ipynb) to an Org Mode file (.org) using the following command:jupytext --to org my_notebook.ipynb## Exporting Org files to Jupyter Notebook formatjupytext --to ipynb my_org_file.org
Python Language Snippets
Section titled “Python Language Snippets”Basics
Section titled “Basics”# String"string3"print("string1")
# Numbers as:## Float3.5## Integers2
# String concatenation, adding strings together using +## Convert a float number to string using str()print("20 days are " + str(28800) + " minutes")
# Print with f stringsprint (f"20 days are {28800} minutes")
# Run operating system shell commandimport os# Call commandos.system('echo "hello world"')
# Define a new function called days_to_units# function parameter is num_of_days, a local scope variabledef days_to_units_20(): print(f"20 days are {20 * calculation_to_units} {name_of_unit}")
# Ask users for input and store user's input in a variable# The input function always returns a string variableuser_input = input("Input a number of days and I will convert it to seconds\n")print(user_input)
# Conditional checking# Return number of units in days as string# Validate input is a positive numberdef days_to_units_text_checked(num_of_days): # Check if parameter is a positive number condition_check = num_of_days > 0 # Print the data type of the condition_check variable print(type(condition_check)) # Conditional to check if parameter is a positive number and evaluates to a boolean # true: parameter is a positive number # false: parameter is not a positive number if num_of_days > 0: return f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_unit}" else: return "Enter a positive number, other values or data types are not allowed"
# Exception handlingtry: # logicexcept ValueError: print("Error: Your input is not a valid number.")
# While loopwhile user_input != "exit": user_input = input("Enter number of days that this program will convert to hours or type exit to stop\n") validate_and_execute_try_except()
# Create Listlist_of_months = ["January", "February", "March"]
# List: Add itemslist_of_months.append("April")
# List: Remove itemslist_of_months.remove("January")
# List: Change itemslist_of_months[0] = "New January"
CSV file operations
Section titled “CSV file operations”# Read CSV file with pandasimport pandas as pd
csv_file_path = 'your_file.csv'
# Specify the columns you want to readcolumns_to_read = ['Column1', 'Column2', 'Column3'] # Replace with your actual column names
# Read the specified columns from the CSV filedata = pd.read_csv(csv_file_path, usecols=columns_to_read)
# Display the dataprint(data)