Python3: Difference between revisions

From Dave's wiki
Jump to navigation Jump to search
No edit summary
Line 53: Line 53:
  for a in argv:
  for a in argv:
     print(a)
     print(a)
Use exists to check for a file existence.
from os.path import exists
exists(my_file) # returns boolean

Revision as of 04:36, 9 August 2022

Philosophy

Some principles/styles that Python programmers follow:

  • Abide by the Don't Repeat Yourself, or DRY, principle. Bad, repetitive code is said to abide by the WET principle, which stands for Write Everything Twice, or We Enjoy Typing.
  • A line of code should not exceed 80 characters; split it on multiple lines

Documentation

The Python documentation tool is called pydoc. You can use it to find out more about a module

pydoc re

Functions

def my_func():
   print("spam")

my_func()

def print_with_exclamation(word):
   print(word + "!")

print_with_exclamation("spam")

Installing

Old way.

conda create -n dbf2csv python=3.8
conda activate dbf2csv
git clone https://github.com/akadan47/dbf2csv.git
cd dbf2csv
pip install -r requirements.txt
python setup.py install

dbf2csv --version
dbf2csv 1.3

Modules

There are three main types of modules in Python, those you write yourself, those you install from external sources, and those that are preinstalled with Python. The last type is called the standard library, and contains many useful modules. Some of the standard library's useful modules include string, re, datetime, math, random, os, multiprocessing, subprocess, socket, email, json, doctest, unittest, pdb, argparse and sys.

Many third-party Python modules are stored on the Python Package Index (PyPI). The best way to install these is using a program called pip. This comes installed by default with modern distributions of Python. If you don't have it, it is easy to install online. Once you have it, installing libraries from PyPI is easy. Look up the name of the library you want to install, go to the command line (for Windows it will be the Command Prompt), and enter pip install library_name. Once you've done this, import the library and use it in your code.

Using pip is the standard way of installing libraries on most operating systems, but some libraries have prebuilt binaries for Windows. These are normal executable files that let you install libraries with a GUI the same way you would install other programs.

Useful modules

Use argv for command line parameters.

from sys import argv
for a in argv:
    print(a)

Use exists to check for a file existence.

from os.path import exists
exists(my_file) # returns boolean