Python3: Difference between revisions
No edit summary |
|||
(14 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
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. | == Philosophy == | ||
Type | |||
import this | |||
The Zen of Python, by Tim Peters | |||
Beautiful is better than ugly. | |||
Explicit is better than implicit. | |||
Simple is better than complex. | |||
Complex is better than complicated. | |||
Flat is better than nested. | |||
Sparse is better than dense. | |||
Readability counts. | |||
Special cases aren't special enough to break the rules. | |||
Although practicality beats purity. | |||
Errors should never pass silently. | |||
Unless explicitly silenced. | |||
In the face of ambiguity, refuse the temptation to guess. | |||
There should be one-- and preferably only one --obvious way to do it. | |||
Although that way may not be obvious at first unless you're Dutch. | |||
Now is better than never. | |||
Although never is often better than *right* now. | |||
If the implementation is hard to explain, it's a bad idea. | |||
If the implementation is easy to explain, it may be a good idea. | |||
Namespaces are one honking great idea -- let's do more of those! | |||
Other 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 | |||
== Statements and control flow == | |||
From https://en.wikipedia.org/wiki/Python_(programming_language)#Statements_and_control_flow | |||
Python's statements include: | |||
* The assignment statement, using a single equals sign <code>=</code> | |||
* The <code>if</code> statement, which conditionally executes a block of code, along with <code>else</code> and <code>elif</code> (a contraction of else-if) | |||
* The <code>for</code> statement, which iterates over an iterable object, capturing each element to a local variable for use by the attached block | |||
* The <code>while</code> statement, which executes a block of code as long as its condition is true | |||
* The <code>try</code> statement, which allows exceptions raised in its attached code block to be caught and handled by <code>except</code> clauses (or new syntax <code>except*</code> in Python 3.11 for exception groups; it also ensures that clean-up code in a <code>finally</code> block is always run regardless of how the block exits | |||
* The <code>raise</code> statement, used to raise a specified exception or re-raise a caught exception | |||
* The <code>class</code> statement, which executes a block of code and attaches its local namespace to a class, for use in object-oriented programming | |||
* The <code>def</code> statement, which defines a function or method | |||
* The <code>with</code> statement, which encloses a code block within a context manager (for example, acquiring a lock before it is run, then releasing the lock; or opening and closing a file, allowing resource-acquisition-is-initialization (RAII)-like behaviour and replacing a common try/finally idiom | |||
* The <code>break</code> statement, which exits a loop | |||
* The <code>continue</code> statement, which skips the current iteration and continues with the next | |||
* The <code>del</code> statement, which removes a variable—deleting the reference from the name to the value, and producing an error if the variable is referred to before it is redefined | |||
* The <code>pass</code> statement, serving as a NOP, syntactically needed to create an empty code block | |||
* The <code>assert</code> statement, used in debugging to check for conditions that should apply | |||
* The <code>yield</code> statement, which returns a value from a generator function (and also an operator); used to implement coroutines | |||
* The <code>return</code> statement, used to return a value from a function | |||
* The <code>import</code> statement, used to import modules whose functions or variables can be used in the current program | |||
== Functions == | == Functions == | ||
To create your own functions use the def followed by the name of the function and a list of arguments inside a set of parentheses. | |||
def my_func(): | def my_func(): | ||
Line 12: | Line 75: | ||
print_with_exclamation("spam") | print_with_exclamation("spam") | ||
Note the difference between functions and methods: functions can be called only by its name, as it is defined independently. However methods can not be called by its name only and we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class. | |||
== 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 == | == 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. | 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 | |||
== Useful posts == | |||
* "if __name__ == '__main__'" in Python - https://note.nkmk.me/en/python-if-name-main/ | |||
* List comprehension - https://www.w3schools.com/python/python_lists_comprehension.asp | |||
* What is the purpose of the single underscore "_" variable in Python? - https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python |
Latest revision as of 00:02, 17 August 2022
Philosophy
Type
import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
Other 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
Statements and control flow
From https://en.wikipedia.org/wiki/Python_(programming_language)#Statements_and_control_flow
Python's statements include:
- The assignment statement, using a single equals sign
=
- The
if
statement, which conditionally executes a block of code, along withelse
andelif
(a contraction of else-if) - The
for
statement, which iterates over an iterable object, capturing each element to a local variable for use by the attached block - The
while
statement, which executes a block of code as long as its condition is true - The
try
statement, which allows exceptions raised in its attached code block to be caught and handled byexcept
clauses (or new syntaxexcept*
in Python 3.11 for exception groups; it also ensures that clean-up code in afinally
block is always run regardless of how the block exits - The
raise
statement, used to raise a specified exception or re-raise a caught exception - The
class
statement, which executes a block of code and attaches its local namespace to a class, for use in object-oriented programming - The
def
statement, which defines a function or method - The
with
statement, which encloses a code block within a context manager (for example, acquiring a lock before it is run, then releasing the lock; or opening and closing a file, allowing resource-acquisition-is-initialization (RAII)-like behaviour and replacing a common try/finally idiom - The
break
statement, which exits a loop - The
continue
statement, which skips the current iteration and continues with the next - The
del
statement, which removes a variable—deleting the reference from the name to the value, and producing an error if the variable is referred to before it is redefined - The
pass
statement, serving as a NOP, syntactically needed to create an empty code block - The
assert
statement, used in debugging to check for conditions that should apply - The
yield
statement, which returns a value from a generator function (and also an operator); used to implement coroutines - The
return
statement, used to return a value from a function - The
import
statement, used to import modules whose functions or variables can be used in the current program
Functions
To create your own functions use the def followed by the name of the function and a list of arguments inside a set of parentheses.
def my_func(): print("spam") my_func() def print_with_exclamation(word): print(word + "!") print_with_exclamation("spam")
Note the difference between functions and methods: functions can be called only by its name, as it is defined independently. However methods can not be called by its name only and we need to invoke the class by a reference of that class in which it is defined, i.e. method is defined within a class and hence they are dependent on that class.
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
Useful posts
- "if __name__ == '__main__'" in Python - https://note.nkmk.me/en/python-if-name-main/
- List comprehension - https://www.w3schools.com/python/python_lists_comprehension.asp
- What is the purpose of the single underscore "_" variable in Python? - https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python