Why Python for Mechanical Engineers?
Python is a great solution for non-software engineers to get things done.
It has a robust library of tools and a supportive community that makes it easy to find solutions.
It is fast (compared to most engineering tools) and flexible for data analysis, automation, and visualization.
It's similar to Matlab, but Python is free and open source.
It can overlap with Excel, but Python can handle large datasets and complex calculations with ease - no waiting for a plot to load or hitting the row limits in a spreadsheet.
Also, due to how it installs, at least in my experience, it is not typically blocked by corporate IT limitations - you're not sneaking, it's just not a problem
Setting Expectations
This is an introduction to help you get things done, with the methods I've found best for me - this is not exhaustive nor will it qualify you as a software engineer.
If you work through this page you've merely passed your driver's test - you are not even close to being a professional racer.
Setting Up Your System
This setup works well for me, and should for you too - but there is no shortage of good alternatives to try out!
Important Note
This is setup for Windows machines - process on Mac or Linux will be similar, but different
Install an IDE
An IDE is an Integrated Development Environment - a tool that helps you write, manage, and run your code more easily.
You don't have to use and IDE, but it makes a lot of things easier and faster
- Download VSCode and install it
- Open VSCode, go to the Extensions tab (left sidebar, square icon), search for "Python" and install the extension by Microsoft
- Also install the Jupyter extension by Microsoft
- Restart VSCode and you should be good to go - you can customize settings and additional extensions as you want
Create your first Virtual Environment
This is another thing you don't have to do, but wlearn the habit now and it will keep projects organized for future you
Note on Virtual Environments
This is a self contained environment for your project (a specific folder with its own Python installation and packages) - you will need to do this again for each project.
- Create a folder for your first project - do it in command prompt if you want, or just a new folder in Windows Explorer or VSCode
- Navigate to that folder in command prompt or powershell
- In command prompt/powershell use "cd [filepath]" to get there
- In VSCode, open the folder and then open the integrated terminal and you'll be in the right spot - see it's a handy tool!
- Create the virtual environment by running the command:
python -m venv .venv
- Activate the virtual environment:
- You should see the terminal prompt change to show the virtual environment is active - something like:
(.venv) C:\Users\you\path\to\project>
- While in here, let's install some packages via pip - these are essentially python toolboxes; run
pip install pandas numpy matplotlib plotly
- These are the packages we'll be using in this guide - pandas for data manipulation, numpy for numerical operations, matplotlib and plotly for plotting
- We will likely install more later, but this is a good start.
- To deactivate the virtual environment when you're done working, just run the command:
deactivate
- Next time you come back, just re-run the activation script and the environment will how you left it.
How to Run Code
Objectives
- Understand how to run Python code in different environments
- Learn the basics of using an IDE (VSCode)
- Learn how to use Jupyter Notebooks
Running Python In the Terminal
This is the most basic way to run Python code - directly in your terminal.
It isn't a bad way to start, but it's not the most efficient and will have you jumping between tools.
We'll walk through here for the sake of completeness, but I recommend mostly forgetting about this after this section, until you find a reason to come back to it.
- Open your terminal (command prompt, powershell, or VSCode terminal)
- Make sure your virtual environment is activated (see previous section)
- Create a new Python file in your project folder - you can do this in VSCode or any text editor. Name it
hello.py
- Add the following code to the file (using VSCode or a text editor such as Notepad):
print("Hello, World!")
- Save the file
- In the terminal, run the script by typing:
python hello.py
- You should see the output:
Hello, World!
And there you have it - running your first Python script in the terminal - you're a real hackerman!
But now let's move on to more practical and efficient ways to run Python code.
Running Python in VSCode
VSCode makes it easy to write and run Python code with its built-in features and extensions.
- Open your project folder in VSCode
- Create a new Python file named
hello_vscode.py
- Add the same code as before, with a small modification:
print("Hello, World from VSCode!")
- Save the file
- Right-click anywhere in the file or click the "Run" button and select "Run Python File in Terminal"
- You should see the output:
Hello, World from VSCode! show up in the integrated terminal (probably the bottom of your screen)
VSCode also offers features like IntelliSense (code completion), debugging, and version control integration, making it a powerful tool for Python development.
It's not a dedicated Python IDE, but it's very effective and will let you work well with other file types as well.
VSCode also has a lot of extensions for convenience - we've installed some alreayd, but go ahead and epxlore if any catch your attention or you think there should be a certain capability.
Running Python in Jupyter Notebooks
Jupyter Notebooks are an interactive way to write and run Python code, combining code, text, and visualizations in a single document.
- In your terminal (with the virtual environment activated), install Jupyter by running:
pip install jupyter (you only need to do this once per virtual environment)
- In VSCode, create a new file titled
hello_jupyter.ipynb
- Open the file in VSCode - it should open in the Jupyter Notebook interface
- In the first cell (should be code type by default), type:
print("Hello, World from Jupyter!")
- Press Shift + Enter to run the cell
- You should see the output:
Hello, World from Jupyter! below the cell
Jupyter Notebooks are great for data analysis, visualization, and sharing your work with others.
They allow you to document your code and results in a clear and organized manner via markdown cells interspersed within the code blocks.
Basic Python
Objectives
- Understand basic Python syntax and structure
- Learn about variables, data types, and control flow
- Get familiar with functions and modules
Limitations of this Section
This may be the most underdeveloped section of this page -
my goal is to give you just enough information to get things done.
Python is known for its simple and readable syntax, making it easy to learn and use.
Here are some basic concepts to get you started:
- White Space: Python uses indentation (I use 4 spaces)to define blocks of code. Proper indentation is crucial for the code to run correctly.
def function_with_proper_whitespace():
print("Hello, World!")
def function_with_wrong_whitespace():
print("This will cause an IndentationError")
- Variables: Used to store data values. Python has dynamic typing, so you don't need to declare variable types explicitly.
x = 10
- Data Types: Common data types include integers, floats, strings, lists, tuples, and dictionaries.
my_list = [1, 2, 3]
- Control Flow: Includes conditional statements (if, elif, else) and loops (for, while).
if x > 5:
print("x is greater than 5")
- Functions: Blocks of reusable code defined using the def keyword.
def greet(name):
print(f"Hello, {name}!")
- Modules: Files containing Python code that can be imported and used in other Python files.
import math
print(math.sqrt(16)) # Outputs: 4.0
- Comments: Use the # symbol for single-line comments and triple quotes (''' or """) for multi-line comments.
# This is a single-line comment
"""This is a
multi-line comment"""
And there you have it - a very incomplete introduction to Python. As you work through the examples and labs, you'll become more familiar with Python's capabilities and syntax.