What is python¶
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.
(python.org)
interpreted An Interpreted Language is a Programming language in which the code is executed line by line by the interpreter. They differ from Compiled Languages in which the code is compiled into the machine language.
object-oriented Object-Oriented Programming (OOP) is a programming paradigm in computer science that relies on the concept of classes and objects. A class is an abstract blueprint that creates more specific, concrete objects. Classes often represent broad categories, like Car or Dog that share attributes. These classes define what attributes an instance of this type will have, like color, but not the value of those attributes for a specific object.
Classes can also contain functions called methods that are available only to objects of that type. These functions are defined within the class and perform some action helpful to that specific object type.
Class templates are used as a blueprint to create individual objects. These represent specific examples of the abstract class, like myCar or goldenRetriever. Each object can have unique values to the properties defined in the class.
dynamic typing means that a compiler or an interpreter assigns a type to all the variables at run-time. The type of a variable is decided based on its value.
dynamic binding languages perform type checking at runtime and the different objects respond differently to the same method call based on their individual implementations.
dynamic allocation memory resources are not declared previously, but dynamically adapted, i.e. no number is too big
How to install python¶
There are different ways to install Python and related packages, but the best way is to start from Miniconda, or Miniforge (Mambaforge). They cames with a package and enviroment manager and it make the difference
No need to administration privilege¶
https://conda-forge.org/miniforge/#latest-release
download execute
to start python seach prompt on windows start
and type python on the shell
first step on python¶
on the shell
>print('hello word')
>2+3
>sin(3.14)
NameError: name 'sin' is not defined. Did you mean: 'bin'?
pure python is quite limited, use of modules and packages are necessary for many applications
>import math
>math.sin(3.14)
Python modules and Package¶
Python modules and Python packages are two mechanisms that facilitate modular programming.
Modular programming refers to the process of breaking a large, unwieldy programming task into separate, smaller, more manageable subtasks or modules. Individual modules can then be cobbled together like building blocks to create a larger application.
There are several advantages to modularizing code in a large application:
Simplicity: Rather than focusing on the entire problem at hand, a module typically focuses on one relatively small portion of the problem. If you’re working on a single module, you’ll have a smaller problem domain to wrap your head around. This makes development easier and less error-prone.
Maintainability: Modules are typically designed so that they enforce logical boundaries between different problem domains. If modules are written in a way that minimizes interdependency, there is decreased likelihood that modifications to a single module will have an impact on other parts of the program. (You may even be able to make changes to a module without having any knowledge of the application outside that module.) This makes it more viable for a team of many programmers to work collaboratively on a large application.
Reusability: Functionality defined in a single module can be easily reused (through an appropriately defined interface) by other parts of the application. This eliminates the need to duplicate code.
Scoping: Modules typically define a separate namespace, which helps avoid collisions between identifiers in different areas of a program. (One of the tenets in the Zen of Python is Namespaces are one honking great idea—let’s do more of those!)
https://realpython.com/python-modules-packages/
Some nomeclature¶
A module
module is basically a bunch of related code saved in a file with the extension .py.\ Could containfunctions, classes, or variables in a module, but also runnable code.
Python packages
are basically a directory with hierarchical structured collection of modules and other package.
On the use are quite the same
Module : import and namespace¶
Module contents are made available to the caller with the import
statement.
All methods and object defined in the module could be available on the sintax name_module.object
lets do a module¶
exit from python
exit()
notepad Torino.py
club = 'Torino F.C.'
song = 'Forza Toro'
nemesis = 'Juventus'
championchip= [1927, 1942, 1945, 1946, 1947, 1948, 1975]
def team(player):
print(f'player = {player}')
class FCteam(object):
pass
if __name__ == "__main__":
import webbrowser
url = "https://www.youtube.com/watch?v=prdK3znXk4M"
webbrowser.open(url, new=0, autoraise=True)
save Torino.py
Several objects are defined in mod.py:
- club (a string)
- championchip (a list)
- team() (a function)
- FCteam (a class)
start again python
import Torino
>print(Torino.song)
>Torino.team("Pulici")
>Torino.championchip
Library : import and namespace¶
Library contents are made available to the caller with the import
statement.
All methods and object defined in the module could be available on the sintax name_library.object
To use internal module the name of the path should be assured
from tkinter import filedialog as fd # from library tkinter import module filedialog renaming as fd
def open_file_selection():
file = fd.askopenfilename() # use of the function askopenfilename of module filedialog in tkinter
print(file)
open_file_selection()
How to install other moldules library and accessory¶
3 methods (from safer to dangerous):¶
- put the files/directory in a place that python know. (typically in the same directory), what happen, Happen.
- use
conda
(ormamba
aka conda on steroids). It is a package manager that check the dependencies of the module and possible conflict with the other installed modules, install what it is needed if a compromise is found. It could also create different environment in order to let coexist incompatible module. - use
pip
. It is a package manager that check the dependencies of the module and install what it is needed. It doesn't care if raise some incompatibility
Location, Location, Location¶
- place the module/library in the same directory
- use library site and and the site.addsitedir(sitedir)
mamba/conda¶
- mamba install name_module
- mamba install name_module -c biopython
- mamba uninstall name_module
- mamba update name_module
pip¶
- pip install name_module
- pip uninstall name_module
- pip update name_module
Time to install something safe¶
# few tools for different kind of python
mamba install jupyterlab notebook ipython ipympl
# few tools for science
mamba install numpy scipy matplotlib lmfit py3Dmol
mamba/conda cheatsheet¶
Getting Started¶
conda info | Verify Conda is installed, check version number
conda update -n base conda | Update Conda to the current version
conda update anaconda | Update all packages to the latest version of Anaconda
Working with Environments¶
conda create --name ENVNAME python=3.9 | Create a new environment named ENVNAME with specific version of Python
conda activate ENVNAME | Activate a named Conda environment
conda deactivate | Deactivate current environment
conda list | List all packages and versions in the active environment
conda list --name ENVNAME | List all packages and versions in a named environment
conda list --revisions | List all revisions made within the active environment
conda list --name ENVNAME --revisions | List all revisions made in a specified environment
conda install --name ENVNAME --revision REV_NUMBER | Restore an environment to a previous revision
conda remove --name ENVNAME --all | Delete an entire environment
Sharing Environments¶
conda create --clone ENVNAME --name NEWENV | Make an exact copy of an environment
conda env export --name ENVNAME > envname.yml | Export an environment to a YAML file that can be read on Windows, macOS, and Linux
conda env create --file envname.yml | Create an environment from YAML file
conda env create | Create an environment from the file named environment.yml in the current directory
conda list --explicit > pkgs.txt | Export an environment with exact package versions for one OS
conda create --name NEWENV --file pkgs.txt | Create an environment based on exact package versions
Using Packages and Channels¶
anaconda search PKGNAME | Find a package on all channels using the Anaconda Client
conda install conda-forge::PKGNAME | Install package from a specific channel
conda install PKGNAME==3.1.4 | Install a package by exact version number (3.1.4)
conda install "PKGNAME>2.5,<3.2" | Install one of the listed versions (OR)
conda config --add channels CHANNELNAME | Install following several constraints (AND) Add a channel to your Conda configuration
conda clean --all | Remove unused cached files including unused packages
conda uninstall PKGNAME --name ENVNAME | Remove a package from an environment
Three methods to run Python:¶
All start from the shell need to open a configured shell (linux mac users just open a shell)
Windows users
- press button windows
- type prompt -> open miniconda prompt
1) Interactive shell¶
as before but we type ipython
now the enviroment allow introspection and autocomplete
import Torino
print(Torino.\tab)
>Torino.\tab
>Torino.\tab
2) executing a program¶
from the shell python Torino.py
club = 'Torino F.C.'
song = 'Forza Toro'
nemesis = 'Juventus'
championchip= [1927, 1942, 1945, 1946, 1947, 1948, 1975]
def team(player):
print(f'player = {player}')
class FCteam(object):
pass
if name == "main":
import webbrowser
url = "https://www.youtube.com/watch?v=prdK3znXk4M"
webbrowser.open(url, new=0, autoraise=True)
the python is executing last part of the file
3) jupyter notebook¶
from the shell jupyter notebook
open a new browser window
Command cell are here¶
few shortcuts¶
If you are on a Mac, substitute command
for control
. Don't type the + (it means press both keys at once).
Shortcuts when in either command mode (outside the cells) or edit mode (inside a cell):¶
Shift
+Enter
run selected cell or cells - if no cells below, insert a code cell belowCtrl
+B
toggle hide/show left sidebarCtrl
+S
save and checkpointCtrl
+Shift
+S
save asCtrl
+F
find
Shortcuts when in command mode (outside the cells, no blinking cursor):¶
Enter
enter edit mode in the active cellScroll up with the up arrow
Scroll down with the down arrow
A
insert a new cell above the active cellB
insert a new cell below the active cellM
make the active cell a Markdown cellY
make the active cell a code cellShift
+Up Arrow
select the current cell and the cell aboveShift
+Down Arrow
select the current cell and the cell belowCtrl
+A
select all cellsX
cut the selected cell or cellsC
copy the selected cell or cellsV
paste the cell(s) which were copied or cut most recentlyShift + M
merge multiple selected cells into one cellDD
(D
twice) delete the active cell00
(Zero twice) restart the kernelZ
undo most recent command mode action
Shortcuts when in edit mode (inside a cell with a blinking cursor):¶
Esc
enter command modeTab
code completion (or indent if at start of line)Shift
+Tab
tooltip helpCtrl
+Shift
+-
split the active cell at the cursor
The usual commands for code editors:
Ctrl
+]
indentCtrl
+[
dedentCtrl
+/
toggle comment
Plus the usual shortcuts for select all, cut, copy, paste, undo, etc.
Help¶
Well done modules and libraries are well documented.
To access to the help of modules library function etc. just use the function help
import numpy
help(numpy)
in ipython just type '?' after the object of your curiosity
in jupyter just shift + tab after the object
Good References¶
Python Programming and Numerical Methods Kong et al
Paper Book
https://www.amazon.fr/Python-Programming-Numerical-Methods-Scientists/dp/0128195495
Free website
https://pythonnumericalmethods.berkeley.edu/notebooks/Index.html
python like you mean it
http://www.pythonlikeyoumeanit.com/
First TEST¶
try to install pyXRD from prestipino https://github.com/Prestipino/pyXRD
but you can try to install the package that you needed