User Tools

Site Tools


coding:python

Python

We will do most of our every day coding in Python, because it is very versatile and easy. It is very important to improve your python skills for this reason.

First, pick one (or more) of the tutorials and go over it. Look at different ones to figure out which one appeals to your learning style the most. Don't worry if you don't get everything or you don't complete everything. Most more advanced skills will come when you use python more and more for your research.

Tutorials

Useful Python packages

Install packages using pip or conda (Andaconda, miniconda).

Useful links

General tips

  • avoid “spaghetti” code with lots of nested loops and long code. If that happens, I try to reorganize into functions/classes so that I can actually see what the algorithm is doing and it looks more simple
  • use packages once you know what you want to calculate, otherwise you might end up using packages as “black” boxes. Good ones to look into: freud, mdanalysis, scipy, numpy, networkx,…
  • copying code from other sources it totally fine, but make sure to rename/clean up such that it is consistent
  • avoid global variables at all costs. they are just going to confuse everything in python. variable names should be unique and descriptive
  • use general idea that one piece of code should only be in one spot of your script. think of it in “units” (related to unit testing) a function should do one thing with well-defined input and output. I.e., if you calculate distances with pbc, don’t copy paste the equations all over the place, instead write a function or class. this means if you need to fix something or change it, you only need to change it in one spot. it also means the code is shorter and more readable. It also means you can test the functions independently to make sure they do work properly (unit testing)
  • be consistent with naming schemes. Ie I do “velocity_x” not VelocityX or XVelocity,… and I always follow the same style
  • be super consistent with indentation
  • no trailing commas or other useless leftover stuff, clean up your code regularly to delete old comments/leftover lines.

Useful snippets of code

Find numbers (floats/ints) in a string:

import re
re.findall(r"[-+]?(?:\d*\.*\d+)", "Some string with some (5) numbers in it, for example 14.2 or 3, +6.7 and 4.")
# output: ['5', '14.2', '3', '+6.7', '4']
coding/python.txt · Last modified: 2023/08/01 04:26 by tk16

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki