This document provides an introduction to the Python programming language. It covers topics such as data types, control statements, functions, input/output, errors and exceptions, object oriented programming, modules and packages. The document is presented over multiple slides with code examples.
This document introduces Python for network engineers, covering an overview of Python, what tasks it can perform like network automation, how to run Python interactively and with files, differences between Python and shell scripting, Python data types, modules, and includes an example Python program to login to a switch and retrieve interface configuration using Telnet.
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
This is the 3rd part of a multi-part series that teaches the basics of Python programming. It covers list and dict comprehensions, functions, modules and packages.
This document provides a summary of Python concepts including:
1. Python is an interpreted, object-oriented, and high-level programming language with features like being easy to read, productive, portable and having a big library.
2. Key Python concepts covered include variables, data types, objects, lists, dictionaries, tuples, control structures, functions and files.
3. The document uses examples and explanations to introduce Python building blocks like variables, data types, lists, dictionaries, control flow and functions. It also discusses how Python interacts with files.
The document provides an overview of a hands-on workshop on the Python programming language conducted by Abdul Haseeb for a faculty development program. The workshop covers the basics of Python including its history, design philosophy, why it is popular, how to get started with the Python IDE, basic data types, variables, operators, input/output functions, and differences between Python versions 2 and 3. Examples are provided to demonstrate various Python concepts like strings, integers, floats, lists, tuples, dictionaries, functions to convert between types, and string operations. Comparisons between Python and C/C++ highlight differences in syntax, commenting, error handling and code readability.
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
This document provides an overview of the Python programming language tutorial presented over multiple pages. It covers:
1) An introduction to Python, its features, and why it is useful including that it is easy to use, portable, object oriented, and has many standard libraries.
2) An explanation of the different parts of the tutorial covering basic concepts like variables, data types, control structures, functions and exceptions as well as data structures and files.
3) Hands-on examples of using Python's basic types like numbers, strings, lists, tuples and dictionaries along with operations on each and how to use the interactive shell and IDE interfaces.
Python is a high-level, general-purpose programming language that was created by Guido van Rossum in 1985. It is an interpreted, interactive, object-oriented language with features like dynamic typing and memory management. This document provides an overview of Python 3 and its basic syntax, data types, operators, decision making structures like if/else statements, and loops. It covers topics like variables, numbers, strings, lists, tuples, dictionaries, and type conversion between data types.
Biopython is a set of freely available Python tools for bioinformatics and molecular biology. It provides features like parsing bioinformatics files into Python structures, a sequence class to store sequences and features, and interfaces to popular bioinformatics programs. Biopython can be used to address common bioinformatics problems like sequence manipulation, searching for primers, and running BLAST searches. The current version is 1.53 from December 2009 and future plans include updating the multiple sequence alignment object and adding a Bio.Phylo module.
Python is a high-level, interpreted, interactive and object-oriented scripting language that can run on many platforms like Windows, Linux, and Mac. It was created in 1990 by Guido van Rossum and draws influence from languages like C, C++, and Java but has a simpler syntax and emphasizes code readability. Python code is typically more concise than other languages and it has a large standard library, making it useful for tasks like web development, science, and data analysis.
This document provides an introduction to the Python programming language. It begins with an agenda that covers running Python, Python programming concepts like data types and control flows, and hands-on exercises. It then discusses running Python interactively and as programs, Python syntax and basic data types like numbers, strings, lists, dictionaries, and tuples. The document is intended to help users understand the basic structure of Python and write simple Python scripts.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists, and tuples. It explains that lists are mutable while tuples are immutable. The document also covers topics like functions, modules, control flow, and the Python interpreter.
Gurukul Skills Schedule for the Month of March
Time Cohort-10 Cohort-11 Cohort-12
8.00 to 09.25 Revision Revision Revision
5 Minutes Short Break
9.30 to 11.30 Chartered Accountants Chartered Accountants ENGLISH/SOFT SKILLS
15 Minutes Short Break
11.45 to 01.45 ICT ENGLISH/SOFT SKILLS R&A
45 Minutues Lunch Break
2.30 to 04.30 ENGLISH/SOFT SKILLS R&A ICT
15 Minutes Short Break
4.45 to 06.30 R&A ICT ACCOUNTS
5 Minutes Short Break
6.35 to 08.00 Assingments Assingments Assingments
This document provides an overview of the Python programming language. It discusses that Python is a popular, object-oriented scripting language that emphasizes code readability. The document summarizes key Python features such as rapid development, automatic memory management, object-oriented programming, and embedding/extending with C. It also outlines common uses of Python and when it may not be suitable.
This document provides an overview of the basics of the Python programming language. It discusses Python's history and features, data types like numbers, strings, lists, tuples and dictionaries. It also covers Python concepts like variables, operators, control flow statements and functions. Specific topics covered include Python interpreters, comments, variables and scopes, data structures, conditional statements like if/else, and exceptions handling.
This presentation contains a quick tour in Python world. First by By comparing Java code, and the equivalent Python side by side, Second by listing some cool features in Python, finally by listing downs and ups of Python in usage; when to use python and when not.
This presentation about Python Interview Questions will help you crack your next Python interview with ease. The video includes interview questions on Numbers, lists, tuples, arrays, functions, regular expressions, strings, and files. We also look into concepts such as multithreading, deep copy, and shallow copy, pickling and unpickling. This video also covers Python libraries such as matplotlib, pandas, numpy,scikit and the programming paradigms followed by Python. It also covers Python library interview questions, libraries such as matplotlib, pandas, numpy and scikit. This video is ideal for both beginners as well as experienced professionals who are appearing for Python programming job interviews. Learn what are the most important Python interview questions and answers and know what will set you apart in the interview process.
Simplilearn’s Python Training Course is an all-inclusive program that will introduce you to the Python development language and expose you to the essentials of object-oriented programming, web development with Django and game development. Python has surpassed Java as the top language used to introduce U.S. students to programming and computer science. This course will give you hands-on development experience and prepare you for a career as a professional Python programmer.
What is this course about?
The All-in-One Python course enables you to become a professional Python programmer. Any aspiring programmer can learn Python from the basics and go on to master web development & game development in Python. Gain hands on experience creating a flappy bird game clone & website functionalities in Python.
What are the course objectives?
By the end of this online Python training course, you will be able to:
1. Internalize the concepts & constructs of Python
2. Learn to create your own Python programs
3. Master Python Django & advanced web development in Python
4. Master PyGame & game development in Python
5. Create a flappy bird game clone
The Python training course is recommended for:
1. Any aspiring programmer can take up this bundle to master Python
2. Any aspiring web developer or game developer can take up this bundle to meet their training needs
Learn more at https://www.simplilearn.com/mobile-and-software-development/python-development-training
Raish Khanji GTU 8th sem Internship Report.pdfRaishKhanji
This report details the practical experiences gained during an internship at Indo German Tool
Room, Ahmedabad. The internship provided hands-on training in various manufacturing technologies, encompassing both conventional and advanced techniques. Significant emphasis was placed on machining processes, including operation and fundamental
understanding of lathe and milling machines. Furthermore, the internship incorporated
modern welding technology, notably through the application of an Augmented Reality (AR)
simulator, offering a safe and effective environment for skill development. Exposure to
industrial automation was achieved through practical exercises in Programmable Logic Controllers (PLCs) using Siemens TIA software and direct operation of industrial robots
utilizing teach pendants. The principles and practical aspects of Computer Numerical Control
(CNC) technology were also explored. Complementing these manufacturing processes, the
internship included extensive application of SolidWorks software for design and modeling tasks. This comprehensive practical training has provided a foundational understanding of
key aspects of modern manufacturing and design, enhancing the technical proficiency and readiness for future engineering endeavors.
Ad
More Related Content
Similar to Python_Fundamentals_for_Everyone_Usefull (20)
This document provides an overview of the Python programming language tutorial presented over multiple pages. It covers:
1) An introduction to Python, its features, and why it is useful including that it is easy to use, portable, object oriented, and has many standard libraries.
2) An explanation of the different parts of the tutorial covering basic concepts like variables, data types, control structures, functions and exceptions as well as data structures and files.
3) Hands-on examples of using Python's basic types like numbers, strings, lists, tuples and dictionaries along with operations on each and how to use the interactive shell and IDE interfaces.
Python is a high-level, general-purpose programming language that was created by Guido van Rossum in 1985. It is an interpreted, interactive, object-oriented language with features like dynamic typing and memory management. This document provides an overview of Python 3 and its basic syntax, data types, operators, decision making structures like if/else statements, and loops. It covers topics like variables, numbers, strings, lists, tuples, dictionaries, and type conversion between data types.
Biopython is a set of freely available Python tools for bioinformatics and molecular biology. It provides features like parsing bioinformatics files into Python structures, a sequence class to store sequences and features, and interfaces to popular bioinformatics programs. Biopython can be used to address common bioinformatics problems like sequence manipulation, searching for primers, and running BLAST searches. The current version is 1.53 from December 2009 and future plans include updating the multiple sequence alignment object and adding a Bio.Phylo module.
Python is a high-level, interpreted, interactive and object-oriented scripting language that can run on many platforms like Windows, Linux, and Mac. It was created in 1990 by Guido van Rossum and draws influence from languages like C, C++, and Java but has a simpler syntax and emphasizes code readability. Python code is typically more concise than other languages and it has a large standard library, making it useful for tasks like web development, science, and data analysis.
This document provides an introduction to the Python programming language. It begins with an agenda that covers running Python, Python programming concepts like data types and control flows, and hands-on exercises. It then discusses running Python interactively and as programs, Python syntax and basic data types like numbers, strings, lists, dictionaries, and tuples. The document is intended to help users understand the basic structure of Python and write simple Python scripts.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists, and tuples. It explains that lists are mutable while tuples are immutable. The document also covers topics like functions, modules, control flow, and the Python interpreter.
Gurukul Skills Schedule for the Month of March
Time Cohort-10 Cohort-11 Cohort-12
8.00 to 09.25 Revision Revision Revision
5 Minutes Short Break
9.30 to 11.30 Chartered Accountants Chartered Accountants ENGLISH/SOFT SKILLS
15 Minutes Short Break
11.45 to 01.45 ICT ENGLISH/SOFT SKILLS R&A
45 Minutues Lunch Break
2.30 to 04.30 ENGLISH/SOFT SKILLS R&A ICT
15 Minutes Short Break
4.45 to 06.30 R&A ICT ACCOUNTS
5 Minutes Short Break
6.35 to 08.00 Assingments Assingments Assingments
This document provides an overview of the Python programming language. It discusses that Python is a popular, object-oriented scripting language that emphasizes code readability. The document summarizes key Python features such as rapid development, automatic memory management, object-oriented programming, and embedding/extending with C. It also outlines common uses of Python and when it may not be suitable.
This document provides an overview of the basics of the Python programming language. It discusses Python's history and features, data types like numbers, strings, lists, tuples and dictionaries. It also covers Python concepts like variables, operators, control flow statements and functions. Specific topics covered include Python interpreters, comments, variables and scopes, data structures, conditional statements like if/else, and exceptions handling.
This presentation contains a quick tour in Python world. First by By comparing Java code, and the equivalent Python side by side, Second by listing some cool features in Python, finally by listing downs and ups of Python in usage; when to use python and when not.
This presentation about Python Interview Questions will help you crack your next Python interview with ease. The video includes interview questions on Numbers, lists, tuples, arrays, functions, regular expressions, strings, and files. We also look into concepts such as multithreading, deep copy, and shallow copy, pickling and unpickling. This video also covers Python libraries such as matplotlib, pandas, numpy,scikit and the programming paradigms followed by Python. It also covers Python library interview questions, libraries such as matplotlib, pandas, numpy and scikit. This video is ideal for both beginners as well as experienced professionals who are appearing for Python programming job interviews. Learn what are the most important Python interview questions and answers and know what will set you apart in the interview process.
Simplilearn’s Python Training Course is an all-inclusive program that will introduce you to the Python development language and expose you to the essentials of object-oriented programming, web development with Django and game development. Python has surpassed Java as the top language used to introduce U.S. students to programming and computer science. This course will give you hands-on development experience and prepare you for a career as a professional Python programmer.
What is this course about?
The All-in-One Python course enables you to become a professional Python programmer. Any aspiring programmer can learn Python from the basics and go on to master web development & game development in Python. Gain hands on experience creating a flappy bird game clone & website functionalities in Python.
What are the course objectives?
By the end of this online Python training course, you will be able to:
1. Internalize the concepts & constructs of Python
2. Learn to create your own Python programs
3. Master Python Django & advanced web development in Python
4. Master PyGame & game development in Python
5. Create a flappy bird game clone
The Python training course is recommended for:
1. Any aspiring programmer can take up this bundle to master Python
2. Any aspiring web developer or game developer can take up this bundle to meet their training needs
Learn more at https://www.simplilearn.com/mobile-and-software-development/python-development-training
Raish Khanji GTU 8th sem Internship Report.pdfRaishKhanji
This report details the practical experiences gained during an internship at Indo German Tool
Room, Ahmedabad. The internship provided hands-on training in various manufacturing technologies, encompassing both conventional and advanced techniques. Significant emphasis was placed on machining processes, including operation and fundamental
understanding of lathe and milling machines. Furthermore, the internship incorporated
modern welding technology, notably through the application of an Augmented Reality (AR)
simulator, offering a safe and effective environment for skill development. Exposure to
industrial automation was achieved through practical exercises in Programmable Logic Controllers (PLCs) using Siemens TIA software and direct operation of industrial robots
utilizing teach pendants. The principles and practical aspects of Computer Numerical Control
(CNC) technology were also explored. Complementing these manufacturing processes, the
internship included extensive application of SolidWorks software for design and modeling tasks. This comprehensive practical training has provided a foundational understanding of
key aspects of modern manufacturing and design, enhancing the technical proficiency and readiness for future engineering endeavors.
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
Passenger car unit (PCU) of a vehicle type depends on vehicular characteristics, stream characteristics, roadway characteristics, environmental factors, climate conditions and control conditions. Keeping in view various factors affecting PCU, a model was developed taking a volume to capacity ratio and percentage share of particular vehicle type as independent parameters. A microscopic traffic simulation model VISSIM has been used in present study for generating traffic flow data which some time very difficult to obtain from field survey. A comparison study was carried out with the purpose of verifying when the adaptive neuro-fuzzy inference system (ANFIS), artificial neural network (ANN) and multiple linear regression (MLR) models are appropriate for prediction of PCUs of different vehicle types. From the results observed that ANFIS model estimates were closer to the corresponding simulated PCU values compared to MLR and ANN models. It is concluded that the ANFIS model showed greater potential in predicting PCUs from v/c ratio and proportional share for all type of vehicles whereas MLR and ANN models did not perform well.
This paper proposes a shoulder inverse kinematics (IK) technique. Shoulder complex is comprised of the sternum, clavicle, ribs, scapula, humerus, and four joints.
ELectronics Boards & Product Testing_Shiju.pdfShiju Jacob
This presentation provides a high level insight about DFT analysis and test coverage calculation, finalizing test strategy, and types of tests at different levels of the product.
The role of the lexical analyzer
Specification of tokens
Finite state machines
From a regular expressions to an NFA
Convert NFA to DFA
Transforming grammars and regular expressions
Transforming automata to grammars
Language for specifying lexical analyzers
Value Stream Mapping Worskshops for Intelligent Continuous SecurityMarc Hornbeek
This presentation provides detailed guidance and tools for conducting Current State and Future State Value Stream Mapping workshops for Intelligent Continuous Security.
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxRishavKumar530754
LiDAR-Based System for Autonomous Cars
Autonomous Driving with LiDAR Tech
LiDAR Integration in Self-Driving Cars
Self-Driving Vehicles Using LiDAR
LiDAR Mapping for Driverless Cars
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
In tube drawing process, a tube is pulled out through a die and a plug to reduce its diameter and thickness as per the requirement. Dimensional accuracy of cold drawn tubes plays a vital role in the further quality of end products and controlling rejection in manufacturing processes of these end products. Springback phenomenon is the elastic strain recovery after removal of forming loads, causes geometrical inaccuracies in drawn tubes. Further, this leads to difficulty in achieving close dimensional tolerances. In the present work springback of EN 8 D tube material is studied for various cold drawing parameters. The process parameters in this work include die semi-angle, land width and drawing speed. The experimentation is done using Taguchi’s L36 orthogonal array, and then optimization is done in data analysis software Minitab 17. The results of ANOVA shows that 15 degrees die semi-angle,5 mm land width and 6 m/min drawing speed yields least springback. Furthermore, optimization algorithms named Particle Swarm Optimization (PSO), Simulated Annealing (SA) and Genetic Algorithm (GA) are applied which shows that 15 degrees die semi-angle, 10 mm land width and 8 m/min drawing speed results in minimal springback with almost 10.5 % improvement. Finally, the results of experimentation are validated with Finite Element Analysis technique using ANSYS.
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
2. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 2
3. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 3
4. Member
of
the
Helmholtz-Association
What is Python?
Python: Dynamic programming language which supports several
different programing paradigms:
Procedural programming
Object oriented programming
Functional programming
Standard: Python byte code is executed in the Python interpreter
(similar to Java)
→ platform independent code
Python slide 4
5. Member
of
the
Helmholtz-Association
Why Python?
Syntax is clear, easy to read and learn (almost pseudo code)
Intuitive object oriented programming
Full modularity, hierarchical packages
Error handling via exceptions
Dynamic, high level data types
Comprehensive standard library for many tasks
Simply extendable via C/C++, wrapping of C/C++ libraries
Focus: Programming speed
Python slide 5
6. Member
of
the
Helmholtz-Association
History
Start implementation in December 1989 by Guido van Rossum
(CWI)
16.10.2000: Python 2.0
Unicode support
Garbage collector
Development process more community oriented
3.12.2008: Python 3.0
Not 100% backwards compatible
2007 & 2010 most popular programming language
(TIOBE Index)
Recommendation for scientific programming
(Nature News, NPG, 2015)
Current version: Python 2.7.14 bzw. Python 3.6.3
Python slide 6
7. Member
of
the
Helmholtz-Association
Zen of Python
20 software principles that influence the design of Python:
1 Beautiful is better than ugly.
2 Explicit is better than implicit.
3 Simple is better than complex.
4 Complex is better than complicated.
5 Flat is better than nested.
6 Sparse is better than dense.
7 Readability counts.
8 Special cases aren’t special enough to break the rules.
9 Although practicality beats purity.
10 Errors should never pass silently.
11 Unless explicitly silenced.
12 ...
Python slide 7
8. Member
of
the
Helmholtz-Association
Is Python fast enough?
For compute intensive algorithms: Fortran, C, C++ might be
better
For user programs: Python is fast enough!
Most parts of Python are written in C
Performance-critical parts can be re-implemented in C/C++
if necessary
First analyse, then optimise!
Python slide 8
11. Member
of
the
Helmholtz-Association
Strong and Dynamic Typing
Strong Typing:
Object is of exactly one type! A string is always a string, an
integer always an integer
Counterexamples: PHP, JavaScript, C: char can be
interpreted as short, void * can be everything
Dynamic Typing:
No variable declaration
Variable names can be assigned to different data types in the
course of a program
An object’s attributes are checked only at run time
Duck typing (an object is defined by its methods and attributes)
When I see a bird that walks like a duck and swims like
a duck and quacks like a duck, I call that bird a duck.1
1
James Whitcomb Riley
Python slide 11
12. Member
of
the
Helmholtz-Association
Example: Strong and Dynamic Typing
types.py
#!/usr/bin/env python3
number = 3
print(number , type(number ))
print(number + 42)
number = "3"
print(number , type(number ))
print(number + 42)
3 <class ’int ’>
45
3 <class ’str ’>
Traceback (most recent call last ):
File "types.py", line 7, in <module >
print(number + 42)
TypeError: must be str , not int
Python slide 12
13. Member
of
the
Helmholtz-Association
Interactive Mode
The interpreter can be started in interactive mode:
$ python3
Python 3.3.5 (default , Mar 27 2014, 17:16:46) [GCC]
on linux
Type "help", "copyright", "credits" or "license" for
more information.
>>> print("hello world")
hello world
>>> a = 3 + 4
>>> print(a)
7
>>> 3 + 4
7
>>>
Python slide 13
15. Member
of
the
Helmholtz-Association
Documentation
Online help in the interpreter:
help(): general Python help
help(obj): help regarding an object, e.g. a function or a
module
dir (): all used names
dir (obj): all attributes of an object
Official documentation: http://docs.python.org/
Python slide 15
17. Member
of
the
Helmholtz-Association
Differences Python 2 – Python 3 (incomplete)
Python 2 Python 3
shebang1 #!/usr/bin/python #!/usr/bin/python3
IDLE cmd1 idle idle3
print cmd (syntax) print print()
input cmd (syntax) raw_input() input()
unicode u"..." all strings
integer type int/long int (infinite)
... hints in each chapter
⇒http://docs.python.org/3/whatsnew/3.0.html
1
linux specific
Python slide 17
18. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 18
20. Member
of
the
Helmholtz-Association
Operators on Numbers
Basic arithmetics: + , - , * , /
hint: Python 2 ⇒ 1/2 = 0
Python 3 ⇒ 1/2 = 0.5
Div and modulo operator: // , % , divmod(x, y)
Absolute value: abs(x)
Rounding: round(x)
Conversion: int(x) , float(x) , complex(re [, im=0])
Conjugate of a complex number: x.conjugate()
Power: x ** y , pow(x, y)
Result of a composition of different data types is of the “bigger”
data type.
Python slide 20
21. Member
of
the
Helmholtz-Association
Bitwise Operation on Integers
Operations:
AND: x & y
OR: x | y
exclusive OR (XOR) : x ^ y
invert: ~x
shift left n bits: x << n
shift right n bits: x >> n
Use bin(x) to get binary
representation string of x .
>>> print(bin(6),bin (3))
0b110 0b11
>>> 6 & 3
2
>>> 6 | 3
7
>>> 6 ^ 3
5
>>> ~0
-1
>>> 1 << 3
8
>>> pow (2,3)
8
>>> 9 >> 1
4
>>> print(bin(9),bin (9>>1))
0b1001 0b100
Python slide 21
22. Member
of
the
Helmholtz-Association
Strings
Data type: str
s = ’spam’ , s = "spam"
Multiline strings: s = """spam"""
No interpretation of escape sequences: s = r"spnam"
Generate strings from other data types: str(1.0)
>>> s = """hello
... world"""
>>> print(s)
hello
world
>>> print("spnam")
sp
am
>>> print(r"spnam") # or: print ("spnam")
spnam
Python slide 22
23. Member
of
the
Helmholtz-Association
String Methods
Count appearance of substrings:
s.count(sub [, start[, end]])
Begins/ends with a substring?
s.startswith(sub[, start[, end]]) ,
s.endswith(sub[, start[, end]])
All capital/lowercase letters: s.upper() , s.lower()
Remove whitespace: s.strip([chars])
Split at substring: s.split([sub [,maxsplit]])
Find position of substring: s.index(sub[, start[, end]])
Replace a substring: s.replace(old, new[, count])
More methods: help(str) , dir(str)
Python slide 23
24. Member
of
the
Helmholtz-Association
Lists
Data type: list
s = [1, "spam", 9.0, 42] , s = []
Append an element: s.append(x)
Extend with a second list: s.extend(s2)
Count appearance of an element: s.count(x)
Position of an element: s.index(x[, min[, max]])
Insert element at position: s.insert(i, x)
Remove and return element at position: s.pop([i])
Delete element: s.remove(x)
Reverse list: s.reverse()
Sort: s.sort([cmp[, key[, reverse]]])
Sum of the elements: sum(s)
Python slide 24
25. Member
of
the
Helmholtz-Association
Tuple
Data type: tuple
s = 1, "spam", 9.0, 42
s = (1, "spam", 9.0, 42)
Constant list
Count appearance of an element: s.count(x)
Position of an element: s.index(x[, min[, max]])
Sum of the elements: sum(s)
Python slide 25
26. Member
of
the
Helmholtz-Association
Tuple
Data type: tuple
s = 1, "spam", 9.0, 42
s = (1, "spam", 9.0, 42)
Constant list
Count appearance of an element: s.count(x)
Position of an element: s.index(x[, min[, max]])
Sum of the elements: sum(s)
Multidimensional tuples and lists
List and tuple can be nested (mixed):
>>> A=([1 ,2 ,3] ,(1 ,2 ,3))
>>> A
([1, 2, 3], (1, 2, 3))
>>> A[0][2]=99
>>> A
([1, 2, 99], (1, 2, 3))
Python slide 25
27. Member
of
the
Helmholtz-Association
Operations on Sequences
Strings, lists and tuples have much in common: They are
sequences.
Does/doesn’t s contain an element?
x in s , x not in s
Concatenate sequences: s + t
Multiply sequences: n * s , s * n
i-th element: s[i] , i-th to last element: s[-i]
Subsequence (slice): s[i:j] , with step size k: s[i:j:k]
Subsequence (slice) from beginning/to end: s[:-i] , s[i:] ,
s[:]
Length (number of elements): len(s)
Smallest/largest element: min(s) , max(s)
Assignments: (a, b, c) = s
→ a = s[0] , b = s[1] , c = s[2]
Python slide 26
28. Member
of
the
Helmholtz-Association
Indexing in Python
positive index 0 1 2 3 4 5 6 7 8 9 10
element P y t h o n K u r s
negative index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
>>> kurs = "Python Kurs"
>>> kurs [2:2]
>>> kurs [2:3]
t
>>> kurs [2]
t
>>> kurs [-4:-1]
Kur
>>> kurs [-4:]
Kurs
>>> kurs [-6:-8:-1]
no
Python slide 27
29. Member
of
the
Helmholtz-Association
Lists, Strings and Tuples
Lists are mutable
Strings and tuples are immutable
No assignment s[i] = ...
No appending and removing of elements
Functions like x.upper() return a new string!
>>> s1 = "spam"
>>> s2 = s1.upper ()
>>> s1
’spam ’
>>> s2
’SPAM ’
Python slide 28
30. Member
of
the
Helmholtz-Association
Boolean Values
Data type bool: True , False
Values that are evaluated to False :
None (data type NoneType )
False
0 (in every numerical data type)
Empty strings, lists and tuples: ’’ , [] , ()
Empty dictionaries: {}
Empty sets set([])
All other Objects of built-in data types are evaluated to True !
>>> bool ([1, 2, 3])
True
>>> bool("")
False
Python slide 29
31. Member
of
the
Helmholtz-Association
References
Every object name is a reference to this object!
An assignment to a new name creates an additional reference
to this object.
Hint: copy a list
s2 = s1[:] oder s2 = list(s1)
Operator is compares two references (identity),
operator == compares the contents of two objects
Assignment: different behavior depending on object type
Strings, numbers (simple data types): create a new object with
new value
Lists, dictionaries, ...: the original object will be changed
Python slide 30
38. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 32
39. Member
of
the
Helmholtz-Association
The If Statement
if a == 3:
print("Aha!")
Blocks are defined by indentation! ⇒Style Guide for Python
Standard: Indentation with four spaces
if a == 3:
print("spam")
elif a == 10:
print("eggs")
elif a == -3:
print("bacon")
else:
print("something else")
Python slide 33
40. Member
of
the
Helmholtz-Association
Relational Operators
Comparison of content: == , < , > , <= , >= , !=
Comparison of object identity: a is b , a is not b
And/or operator: a and b , a or b
Negation: not a
if not (a==b) and (c <3):
pass
Hint: pass is a No Operation (NOOP) function
Python slide 34
41. Member
of
the
Helmholtz-Association
For Loops
for i in range (10):
print(i) # 0, 1, 2, 3, ..., 9
for i in range(3, 10):
print(i) # 3, 4, 5, ..., 9
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
else:
print("Loop completed.")
End loop prematurely: break
Next iteration: continue
else is executed when loop didn’t end prematurely
Python slide 35
42. Member
of
the
Helmholtz-Association
For Loops (continued)
Iterating directly over sequences (without using an index):
for item in ["spam", "eggs", "bacon"]:
print(item)
The range function can be used to create a list:
>>> list(range(0, 10, 2))
[0, 2, 4, 6, 8]
If indexes are necessary:
for (i, char) in enumerate("hello world"):
print(i, char)
Python slide 36
43. Member
of
the
Helmholtz-Association
While Loops
i = 0
while i < 10:
i += 1
break and continue work for while loops, too.
Substitute for do-while loop:
while True:
# important code
if condition:
break
Python slide 37
45. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 38
46. Member
of
the
Helmholtz-Association
Functions
def add(a, b):
""" Returns the sum of a and b."""
mysum = a + b
return mysum
>>> result = add(3, 5)
>>> print(result)
8
>>> help(add)
Help on function add in module __main__:
add(a, b)
Returns the sum of a and b.
Python slide 39
47. Member
of
the
Helmholtz-Association
Return Values and Parameters
Functions accept arbitrary objects as parameters and return
values
Types of parameters and return values are unspecified
Functions without explicit return value return None
def hello_world ():
print("Hello World!")
a = hello_world ()
print(a)
$ python3 my_program.py
Hello World
None
Python slide 40
49. Member
of
the
Helmholtz-Association
Optional Parameters – Default Values
Parameters can be defined with default values.
Hint: It is not allowed to define non-default parameters after
default parameters
def fline(x, m=1, b=0): # f(x) = m*x + b
return m*x + b
for i in range (5):
print(fline(i),end=" ")
for i in range (5):
print(fline(i,-1,1),end=" ")
$ python3 plot_lines.py
0 1 2 3 4
1 0 -1 -2 -3
Hint: end in print defines the last character, default is linebreak
Python slide 42
50. Member
of
the
Helmholtz-Association
Positional Parameters
Parameters can be passed to a function in a different order than
specified:
def printContact(name ,age ,location ):
print("Person: ", name)
print("Age: ", age , "years")
print("Address: ", location)
printContact(name="Peter Pan", location="Neverland",
age =10)
$ python3 displayPerson.py
Person: Peter Pan
Age: 10 years
Address: Neverland
Python slide 43
51. Member
of
the
Helmholtz-Association
Functions are Objects
Functions are objects and as such can be assigned and passed on:
>>> a = float
>>> a(22)
22.0
>>> def foo(fkt):
... print(fkt (33))
...
>>> foo(float)
33.0
>>> foo(str)
33
>>> foo(complex)
(33+0j)
Python slide 44
52. Member
of
the
Helmholtz-Association
Online Help: Docstrings
Can be used in function, modul, class and method definitions
Is defined by a string as the first statement in the definition
help(...) on python object returns the docstring
Two types of docstrings: one-liners and multi-liners
def complex(real =0.0, imag =0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
...
Python slide 45
53. Member
of
the
Helmholtz-Association
Functions & Modules
Functions thematically belonging together can be stored in a
separate Python file. (Same for objects and classes)
This file is called module and can be loaded in any Python
script.
Multiple modules available in the Python Standard Library
(part of the Python installation)
Command for loading a module: import <filename>
(filename without ending .py)
import math
s = math.sin(math.pi)
More information for standard modules and how to create your
own module see chapter Modules and Packages on slide 90
Python slide 46
55. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 47
56. Member
of
the
Helmholtz-Association
String Formatting
Format string + class method x.format()
“replacement fields”: curly braces around optional arg_name
(default: 0,1,2,. . .)
print("The answer is {0:4d}".format (42))
s = "{0}: {1:08.3f}".format("spam", 3.14)
format purpose
default: string
m.nf floating point: m filed size, n digits after the decimal point (6)
m.ne floating point (exponential): m filed size, 1 digit before and n
digits behind the decimal point (default: 6)
m.n% percentage: similar to format f, value ∗ 100 with finalizing ’%’
md Integer number: m field size (0m ⇒leading “0”)
format d can be replaced by b (binary), o (octal) or x (hexadeci-
mal)
Python slide 48
57. Member
of
the
Helmholtz-Association
String Formatting (outdated, Python 2 only)
String formatting similar to C:
print "The answer is %4i." % 42
s = "%s: %08.3f" % ("spam", 3.14)
Integer decimal: d, i
Integer octal: o
Integer hexadecimal: x, X
Float: f, F
Float in exponential form: e, E, g, G
Single character: c
String: s
Use %% to output a single % character.
Python slide 49
58. Member
of
the
Helmholtz-Association
Command Line Input
User input in Python 3:
user_input = input("Type something: ")
User input in Python 2:
user_input = raw_input("Type something: ")
Hint: In Python 2 is input("...") ⇐⇒ eval(raw_input("..."))
Command line parameters:
import sys
print(sys.argv)
$ python3 params.py spam
[’params.py ’, ’spam ’]
Python slide 50
59. Member
of
the
Helmholtz-Association
Files
file1 = open("spam", "r")
file2 = open("/tmp/eggs", "wb")
Read mode: r
Write mode (new file): w
Write mode, appending to the end: a
Handling binary files: e.g. rb
Read and write (update): r+
for line in file1:
print(line)
Python slide 51
60. Member
of
the
Helmholtz-Association
Operations on Files
Read: f.read([size])
Read a line: f.readline()
Read multiple lines: f.readlines([sizehint])
Write: f.write(str)
Write multiple lines: f.writelines(sequence)
Close file: f.close()
file1 = open("test", "w")
lines = ["spamn", "eggsn", "hamn"]
file1.writelines(lines)
file1.close ()
Python automatically converts n into the correct line ending!
Python slide 52
61. Member
of
the
Helmholtz-Association
The with statement
File handling (open/close) can be done by the context manager
with .
(⇒section Errors and Exceptions on slide 64).
with open("test.txt") as f:
for line in f:
print(line)
After finishing the with block the file object is closed, even if an
exception occurred inside the block.
Python slide 53
63. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 54
64. Member
of
the
Helmholtz-Association
Syntax Errors, Indentation Errors
Parsing errors: Program will not be executed.
Mismatched or missing parenthesis
Missing or misplaced semicolons, colons, commas
Indentation errors
print("I’m running ...")
def add(a, b)
return a + b
$ python3 add.py
File "add.py", line 2
def add(a, b)
^
SyntaxError: invalid syntax
Python slide 55
65. Member
of
the
Helmholtz-Association
Exceptions
Exceptions occur at runtime:
import math
print("I’m running ...")
math.foo()
$ python3 test.py
I’m running ...
Traceback (most recent call last ):
File "test.py", line 3, in <module >
math.foo()
AttributeError : module ’math ’ has no
attribute ’foo ’
Python slide 56
66. Member
of
the
Helmholtz-Association
Handling Exceptions (1)
try:
s = input("Enter a number: ")
number = float(s)
except ValueError:
print("That ’s not a number!")
except block is executed when the code in the try block
throws an according exception
Afterwards, the program continues normally
Unhandled exceptions force the program to exit.
Handling different kinds of exceptions:
except (ValueError , TypeError , NameError ):
Built-in exceptions:
http://docs.python.org/library/exceptions.html
Python slide 57
67. Member
of
the
Helmholtz-Association
Handling Exceptions (2)
try:
s = input("Enter a number: ")
number = 1/ float(s)
except ValueError:
print("That ’s not a number!")
except ZeroDivisionError :
print("You can’t divide by zero!")
except:
print("Oops , what ’s happened?")
Several except statements for different exceptions
Last except can be used without specifying the kind of
exception: Catches all remaining exceptions
Careful: Can mask unintended programming errors!
Python slide 58
68. Member
of
the
Helmholtz-Association
Handling Exceptions (3)
else is executed if no exception occurred
finally is executed in any case
try:
f = open("spam")
except IOError:
print("Cannot open file")
else:
print(f.read ())
f.close ()
finally:
print("End of try.")
Python slide 59
69. Member
of
the
Helmholtz-Association
Exception Objects
Access to exception objects:
EnvironmentError ( IOError , OSError ):
Exception object has 3 attributes ( int , str , str )
Otherwise: Exception object is a string
try:
f = open("spam")
except IOError as e:
print(e.errno , e.filename , e.strerror)
print(e)
$ python3 test.py
2 spam No such file or directory
[Errno 2] No such file or directory: ’spam ’
Python slide 60
70. Member
of
the
Helmholtz-Association
Exceptions in Function Calls
draw()
rectangle()
line() Exception!
Function calls another function.
That function raises an exception.
Is exception handled?
No: Pass exception to calling function.
Python slide 61
72. Member
of
the
Helmholtz-Association
Exceptions vs. Checking Values Beforehand
Exceptions are preferable!
def square(x):
if type(x) == int or type(x) == float:
return x ** 2
else:
return None
What about other numerical data types (complex numbers,
own data types)? Better: Try to compute the power and
catch possible exceptions! → Duck-Typing
Caller of a function might forget to check return values for
validity. Better: Raise an exception!
Python slide 63
73. Member
of
the
Helmholtz-Association
Exceptions vs. Checking Values Beforehand
Exceptions are preferable!
def square(x):
if type(x) == int or type(x) == float:
return x ** 2
else:
return None
def square(x):
return x ** 2
...
try:
result = square(value)
except TypeError:
print(" ’{0}’: Invalid type".format(value ))
Python slide 63
74. Member
of
the
Helmholtz-Association
The with Statement
Some objects offer context management2, which provides a more
convenient way to write try ... finally blocks:
with open("test.txt") as f:
for line in f:
print(line)
After the with block the file object is guaranteed to be closed
properly, no matter what exceptions occurred within the block.
2
Class method __enter__(self) will be executed at the beginning and
class method __exit__(...) at the end of the context
Python slide 64
76. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 65
77. Member
of
the
Helmholtz-Association
Sets
Set: unordered, no duplicated elements
s = {sequence} since Python 2.7
alternative s = set([sequence]) , required for empty sets.
Constant set: s = frozenset([sequence])
e.g. empty set: empty = frozenset()
Subset: s.issubset(t) , s <= t , strict subset: s < t
Superset: s.issuperset(t) , s >= t , strict superset: s > t
Union: s.union(t) , s | t
Intersection: s.intersection(t) , s & t
Difference: s.difference(t) , s - t
Symmetric Difference: s.symmetric_difference(t) , s ^ t
Copy: s.copy()
As with sequences, the following works:
x in s , len(s) , for x in s , s.add(x) , s.remove(x)
Python slide 66
78. Member
of
the
Helmholtz-Association
Dictionaries
Other names: Hash, Map, Associative Array
Mapping of key → value
Keys are unordered
>>> store = { "spam": 1, "eggs": 17}
>>> store["eggs"]
17
>>> store["bacon"] = 42
>>> store
{’eggs ’: 17, ’bacon ’: 42, ’spam ’: 1}
Iterating over dictionaries:
for key in store:
print(key , store[key])
Compare two dictionaries: store == pool
Not allowed: > , >= , < , <=
Python slide 67
79. Member
of
the
Helmholtz-Association
Operations on Dictionaries
Delete an entry: del
Delete all entries: store.clear()
Copy: store.copy()
Does it contain a key? key in store
Get an entry: store.get(key[, default])
Remove and return entry: store.pop(key[, default])
Remove and return arbitrary entry: store.popitem()
Python slide 68
80. Member
of
the
Helmholtz-Association
Operations on Dictionaries
Delete an entry: del
Delete all entries: store.clear()
Copy: store.copy()
Does it contain a key? key in store
Get an entry: store.get(key[, default])
Remove and return entry: store.pop(key[, default])
Remove and return arbitrary entry: store.popitem()
Views on Dictionaries
Create a view: items() , keys() und values()
List of all (key, value) tuples: store.items()
List of all keys: store.keys()
List all values: store.values()
Caution: Dynamical since Python 3
Python slide 68
81. Member
of
the
Helmholtz-Association
Views Behavior: Python 2.X versus Python 3.X
Python 2 (static)
>>> mdict ={"a":2, "d":5}
>>> mdict
{’a’: 2, ’d’: 5}
>>> s=mdict.items ()
>>> for i in s:
print(i)
(’a’, 2)
(’d’, 5)
>>> mdict[’a’]=-1
>>> mdict
{’a’: -1, ’d’: 5}
>>> for i in s:
print(i)
(’a’, 2)
(’d’, 5)
Python 3 (dynamic)
>>> mdict ={"a":2, "d":5}
>>> mdict
{’a’: 2, ’d’: 5}
>>> s=mdict.items ()
>>> for i in s:
print(i)
(’a’, 2)
(’d’, 5)
>>> mdict[’a’]=-1
>>> mdict
{’a’: -1, ’d’: 5}
>>> for i in s:
print(i)
(’a’, -1)
(’d’, 5)
Python slide 69
83. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 70
84. Member
of
the
Helmholtz-Association
Object Oriented Programming (OOP)
So far: procedural programming
Data (values, variables, parameters, . . .)
Functions taking data as parameters and returning results
Alternative: Group data and functions belonging together to
form custom data types
→ Extensions of structures in C/Fortran
Python slide 71
85. Member
of
the
Helmholtz-Association
Using Simple Classes as Structs
class Point:
pass
p = Point ()
p.x = 2.0
p.y = 3.3
Class: Custom date type (here: Point )
Object: Instance of a class (here: p )
Attributes (here x , y ) can be added dynamically
Hint: pass is a No Operation (NOOP) function
Python slide 72
87. Member
of
the
Helmholtz-Association
Methods on Objects
class Point:
def __init__(self , x, y):
self.x = x
self.y = y
def norm(self ):
n = math.sqrt(self.x**2 + self.y**2)
return n
p = Point (2.0, 3.0)
print(p.x, p.y, p.norm ())
Method call: automatically sets the object as first parameter
→ traditionally called self
Careful: Overloading of methods not possible!
Python slide 74
88. Member
of
the
Helmholtz-Association
Converting Objects to Strings
Default return value of str(...) for objects of custom classes:
>>> p = Point (2.0, 3.0)
>>> print(p) # --> print(str(p))
<__main__.Point instance at 0x402d7a8c >
Python slide 75
89. Member
of
the
Helmholtz-Association
Converting Objects to Strings
Default return value of str(...) for objects of custom classes:
>>> p = Point (2.0, 3.0)
>>> print(p) # --> print(str(p))
<__main__.Point instance at 0x402d7a8c >
This behaviour can be overwritten:
def __str__(self ):
return "({0}, {1})".format(self.x, self.y)
>>> print(p)
(2, 3)
Python slide 75
91. Member
of
the
Helmholtz-Association
Comparing Objects
Default: == checks for object identity of custom objects.
>>> p1 = Point (2.0, 3.0)
>>> p2 = Point (2.0, 3.0)
>>> p1 == p2
False
This behaviour can be overwritten:
def __eq__(self , other ):
return (self.x == other.x) and (self.y == other.y)
>>> p1 == p2 # Check for equal values
True
>>> p1 is p2 # Check for identity
False
Python slide 76
93. Member
of
the
Helmholtz-Association
Emulating Existing Data Types
Classes can emulate built-in data types:
Numbers: arithmetics, int(myobj) , float(myobj) , . . .
Functions: myobj(...)
Sequences: len(myobj) , myobj[...] , x in myobj , ...
Iteratores: for i in myobj
See documentation:
http://docs.python.org/3/reference/datamodel.html
Python slide 78
94. Member
of
the
Helmholtz-Association
Class Variables
Have the same value for all instances of a class:
class Point:
count = 0 # Count all point objects
def __init__(self , x, y):
Point.count += 1 #self.__class__.count += 1
...
>>> p1 = Point(2, 3); p2 = Point (3, 4)
>>> p1.count
2
>>> p2.count
2
>>> Point.count
2
Python slide 79
95. Member
of
the
Helmholtz-Association
Class Methods and Static Methods
class Spam:
spam = "I don’t like spam."
@classmethod
def cmethod(cls):
print(cls.spam)
@staticmethod
def smethod ():
print("Blah blah.")
Spam.cmethod ()
Spam.smethod ()
s = Spam ()
s.cmethod ()
s.smethod ()
Python slide 80
96. Member
of
the
Helmholtz-Association
Inheritance (1)
There are often classes that are very similar to each other.
Inheritance allows for:
Hierarchical class structure (is-a-relationship)
Reusing of similar code
Example: Different types of phones
Phone
Mobile phone (is a phone with additional functionality)
Smart phone (is a mobile phone with additional functionality)
Python slide 81
97. Member
of
the
Helmholtz-Association
Inheritance (2)
class Phone:
def call(self ):
pass
class MobilePhone(Phone ):
def send_text(self ):
pass
MobilePhone now inherits methods and attributes from Phone.
h = MobilePhone ()
h.call () # inherited from Phone
h.send_text () # own method
Python slide 82
99. Member
of
the
Helmholtz-Association
Multiple Inheritance
Classes can inherit from multiple parent classes. Example:
SmartPhone is a mobile phone
SmartPhone is a camera
class SmartPhone(MobilePhone , Camera ):
pass
h = SmartPhone ()
h.call () # inherited from MobilePhone
h.take_photo () # inherited from Camera
Attributes are searched for in the following order:
SmartPhone, MobilePhone, parent class of MobilePhone
(recursively), Camera, parent class of Camera (recursively).
Python slide 84
100. Member
of
the
Helmholtz-Association
Private Attributes / Private Class Variables
There are no private variables or private methods in Python.
Convention: Mark attributes that shouldn’t be accessed from
outside with an underscore: _foo .
To avoid name conflicts during inheritance: Names of the
form __foo are replaced with _classname__foo :
class Spam:
__eggs = 3
_bacon = 1
beans = 5
>>> dir(Spam)
>>> [’_Spam__eggs ’, ’__doc__ ’, ’__module__ ’,
’_bacon ’, ’beans ’]
Python slide 85
101. Member
of
the
Helmholtz-Association
Classic (old Style) Classes
The only class type until Python 2.1
In Python 2 default class
New Style Classes
Unified class model (user-defined and build-in)
Descriptores (getter, setter)
The only class type in Python 3
Available as basic class in Python 2: object
Python slide 86
102. Member
of
the
Helmholtz-Association
Properties (1)
If certain actions (checks, conversions) are to be executed while
accessing attributes, use getter and setter:
class Spam:
def __init__(self ):
self._value = 0
def get_value(self ):
return self._value
def set_value(self , value ):
if value <= 0:
self._value = 0
else:
self._value = value
value = property(get_value , set_value)
Python slide 87
103. Member
of
the
Helmholtz-Association
Properties (2)
Properties can be accessed like any other attributes:
>>> s = Spam ()
>>> s.value = 6 # set_value (6)
>>> s.value # get_value ()
>>> 6
>>> s.value = -6 # set_value (-6)
>>> s.value # get_value ()
>>> 0
Getter and setter can be added later without changing the API
Access to _value still possible
Python slide 88
105. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 89
106. Member
of
the
Helmholtz-Association
Importing Modules
Reminder: Functions, classes and object thematically belonging
together are grouped in modules.
import math
s = math.sin(math.pi)
import math as m
s = m.sin(m.pi)
from math import pi as PI , sin
s = sin(PI)
from math import *
s = sin(pi)
Online help: dir(math) , help(math)
Python slide 90
107. Member
of
the
Helmholtz-Association
Creating a Module (1)
Every Python script can be imported as a module.
"""My first module: my_module.py"""
def add(a, b):
""" Add a and b."""
return a + b
print(add(2, 3))
>>> import my_module
5
>>> my_module.add(17, 42)
59
Top level instructions are executed during import!
Python slide 91
108. Member
of
the
Helmholtz-Association
Creating a Module (2)
If instructions should only be executed when running as a script,
not importing it:
def add(a, b):
return a + b
def main ():
print(add(2, 3))
if __name__ == "__main__":
main ()
Useful e.g. for testing parts of the module.
Python slide 92
109. Member
of
the
Helmholtz-Association
Creating a Package
Modules can be grouped into hierarchically structured packages.
numeric
__init__.py
linalg
__init__.py
decomp.py
eig.py
solve.py
fft
__init__.py
...
Packages are subdirectories
In each package directory: __init__.py
(may be empty)
import numeric
numeric.foo() # from __init__.py
numeric.linalg.eig.foo()
from numeric.linalg import eig
eig.foo()
Python slide 93
110. Member
of
the
Helmholtz-Association
Modules Search Path
Modules are searched for in (see sys.path ):
The directory of the running script
Directories in the environment variable PYTHONPATH
Installation-dependent directories
>>> import sys
>>> sys.path
[’’, ’/usr/lib/python33.zip ’,
’/usr/lib64/python3 .3’,
’/usr/lib64/python3 .3/plat -linux ’, ...]
Python slide 94
112. Member
of
the
Helmholtz-Association
Mathematics: math
Constants: e , pi
Round up/down: floor(x) , ceil(x)
Exponential function: exp(x)
Logarithm: log(x[, base]) , log10(x)
Power and square root: pow(x, y) , sqrt(x)
Trigonometric functions: sin(x) , cos(x) , tan(x)
Conversion degree ↔ radiant: degrees(x) , radians(x)
>>> import math
>>> math.sin(math.pi)
1.2246063538223773e-16
>>> math.cos(math.radians (30))
0.86602540378443871
Python slide 96
113. Member
of
the
Helmholtz-Association
Random Numbers: random
Random integers:
randint(a, b) , randrange([start,] stop[, step])
Random floats (uniform distr.): random() , uniform(a, b)
Other distibutions: expovariate(lambd) ,
gammavariate(alpha, beta) , gauss(mu, sigma) , . . .
Random element of a sequence: choice(seq)
Several unique, random elements of a sequence:
sample(population, k)
Shuffled sequence: shuffle(seq[, random])
>>> import random
>>> s = [1, 2, 3, 4, 5]
>>> random.shuffle(s)
>>> s
[2, 5, 4, 3, 1]
>>> random.choice("Hello world!")
’e’
Python slide 97
114. Member
of
the
Helmholtz-Association
Time Access and Conversion: time
Classical time() functionality
Time class type is a 9-tuple of int values ( struct_time )
Time starts at epoch (for UNIX: 1.1.1970, 00:00:00)
Popular functions:
Seconds since epoch (as a float): time.time()
Convert time in seconds (float) to struct_time :
time.localtime([seconds])
If seconds is None the actual time is returned.
Convert struct_time in seconds (float): time.mktime(t)
Convert struct_time in formatted string:
time.strftime(format[, t])
Suspend execution of current thread for secs seconds:
time.sleep(secs)
Python slide 98
115. Member
of
the
Helmholtz-Association
Date and Time: datetime
Date and time objects:
d1 = datetime.date (2008 , 3, 21)
d2 = datetime.date (2008 , 6, 22)
dt = datetime.datetime (2011 , 8, 26, 12, 30)
t = datetime.time (12, 30)
Calculating with date and time:
print(d1 < d2)
delta = d2 - d1
print(delta.days)
print(d2 + datetime.timedelta(days =44))
Python slide 99
117. Member
of
the
Helmholtz-Association
Files and Directories: os
Working directory: getcwd() , chdir(path)
Changing file permissions: chmod(path, mode)
Changing owner: chown(path, uid, gid)
Creating directories: mkdir(path[, mode]) ,
makedirs(path[, mode])
Removing files: remove(path) , removedirs(path)
Renaming files: rename(src, dst) , renames(old, new)
List of files in a directory: listdir(path)
for myfile in os.listdir("mydir"):
os.chmod(os.path.join("mydir", myfile),
os.path.stat.S_IRGRP)
Python slide 101
118. Member
of
the
Helmholtz-Association
Files and Directories: shutil
Higher level operations on files and directories. Mighty wrapper
functions for os module.
Copying files: copyfile(src, dst) , copy(src, dst)
Recursive copy: copytree(src, dst[, symlinks])
Recursive removal:
rmtree(path[, ignore_errors[, onerror]])
Recursive move: move(src, dst)
shutil.copytree("spam/eggs", "../ beans",
symlinks=True)
Python slide 102
119. Member
of
the
Helmholtz-Association
Directory Listing: glob
List of files in a directory with Unix-like extension of wildcards:
glob(path)
>>> glob.glob("python /[a-c]*.py")
[’python/confitest.py ’,
’python/basics.py ’,
’python/curses_test2.py ’,
’python/curses_keys.py ’,
’python/cmp.py ’,
’python/button_test.py ’,
’python/argument.py ’,
’python/curses_test.py ’]
Python slide 103
120. Member
of
the
Helmholtz-Association
Run Processes: subprocess
Simple execution of a program:
p = subprocess.Popen (["ls", "-l", "mydir"])
returncode = p.wait () # wait for p to end
Access to the program’s output:
p = Popen (["ls"], stdout=PIPE , stderr=STDOUT)
p.wait ()
output = p.stdout.read ()
Pipes between processes ( ls -l | grep txt )
p1 = Popen (["ls", "-l"], stdout=PIPE)
p2 = Popen (["grep", "txt"], stdin=p1.stdout)
Python slide 104
121. Member
of
the
Helmholtz-Association
Access to Command Line Parameters: argparse (1)
Python program with standard command line option handling:
$ ./ argumentParser.py -h
usage: argumentParse.py [-h] -f FILENAME [-v]
Example how to use argparse
optional arguments:
-h, --help show this help message and exit
-f FILENAME , --file FILENAME
output file
-v, --verbosity increase output verbosity
$ python3 argumentParse.py -f newfile.txt -v
newfile.txt
True
Python slide 105
122. Member
of
the
Helmholtz-Association
Access to Command Line Parameters: argparse (2)
Simple list of parameters: → sys.argv
More convenient for handling several options: argparse
Deprecated module optparse (since Python 2.7/3.2)
parser = argparse. ArgumentParser (
description=’Example how to use argparse ’)
parser.add_argument("-f", "--file",
dest="filename",
default="out.txt",
help="output file")
parser.add_argument("-v","--verbosity",
action="store_true",
help="increase output verbosity")
args = parser.parse_args ()
print(args.filename)
print(args.verbosity)
Python slide 106
123. Member
of
the
Helmholtz-Association
CSV Files: csv (1)
CSV: Comma Seperated Values
Data tables in ASCII format
Import/Export by MS Excel R
Columns are delimited by a predefined character (most often
comma)
f = open("test.csv", "r")
reader = csv.reader(f)
for row in reader:
for item in row:
print(item)
f.close ()
f = open(outfile , "w")
writer = csv.writer(f)
writer.writerow ([1, 2, 3, 4])
Python slide 107
124. Member
of
the
Helmholtz-Association
CSV Files: csv (2)
Handling different kinds of formats (dialects):
reader(csvfile , dialect=’excel ’) # Default
writer(csvfile , dialect=’excel_tab ’)
Specifying individual format parameters:
reader(csvfile , delimiter=";")
Further format parameters: lineterminator , quotechar ,
skipinitialspace , . . .
Python slide 108
125. Member
of
the
Helmholtz-Association
Lightweight Database: sqlite3 (1)
Database in a file or in memory; in Python’s stdlib since 2.5.
conn = sqlite3.connect("bla.db")
c = conn.cursor ()
c.execute(""" CREATE TABLE Friends
(firstname TEXT , lastname TEXT)""")
c.execute(""" INSERT INTO Friends
VALUES (" Jane", "Doe")""")
conn.commit ()
c.execute(""" SELECT * FROM Friends """)
for row in c:
print(row)
c.close ();
conn.close ()
Python slide 109
127. Member
of
the
Helmholtz-Association
Lightweight Database: sqlite3 (3)
Instead: Use the placeholder the database API provides:
c.execute("... WHERE name = ?", symbol)
friends = (("Janis", "Joplin"), ("Bob", "Dylan"))
for item in friends:
c.execute(""" INSERT INTO Friends
VALUES (?,?) """, item)
⇒ Python module cx_Oracle to access Oracle data base
Web page: http://cx-oracle.sourceforge.net/
Python slide 111
128. Member
of
the
Helmholtz-Association
XML based Client-Server Communication: xmlrpc (1)
XML-RPC: Remote Procedure Call uses XML via HTTP
Independent of platform and programming language
For the client use xmlrpc.client
import xmlrpc.client
s = xmlrpc.client.Server("http :// localhost :8000")
# print list of available methods
print(s.system.listMethods ())
# use methods
print(s.add (2 ,3))
print(s.sub (5 ,2))
Automatic type conversion for the standard data types: boolean,
integer, floats, strings, tuple, list, dictionarys (strings as keys),
. . .
Python slide 112
129. Member
of
the
Helmholtz-Association
XML based Client-Server Communication: xmlrpc (2)
For the server use xmlrpc.server
from xmlrpc.server import SimpleXMLRPCServer
# methods which are to be offered by the server:
class MyFuncs:
def add(self , x, y):
return x + y
def sub(self , x, y):
return x - y
# create and start the server:
server = SimpleXMLRPCServer (("localhost", 8000))
server. register_instance (MyFuncs ())
server.serve_forever ()
Python slide 113
130. Member
of
the
Helmholtz-Association
More Modules
readline : Functionallity for command line history and
auto-complition
tempfile : Generate temporary files and directories
numpy : Numeric Python package
N-dimensional arrays
Supports linear algebrar, Fourier transform and random number
capabilities
Part of the SciPy stack
mathplotlib : 2D plotting library, part of the SciPy stack
...
Python slide 114
132. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 115
134. Member
of
the
Helmholtz-Association
List Comprehension
Allows sequences to be build by sequences. Instead of using for :
a = []
for i in range (10):
a.append(i**2)
List comprehension can be used:
a = [i**2 for i in range (10)]
Conditional values in list comprehension:
a = [i**2 for i in range (10) if i != 4]
Since Python 2.7: set and dictionary comprehension
s = {i*2 for i in range (3)}
d = {i: i*2 for i in range (3)}
Python slide 117
136. Member
of
the
Helmholtz-Association
getattr, setattr, hasattr
Attributes of an object can be accessed by name (string):
import math
f = getattr(math , "sin")
print(f(x)) # sin(x)
a = Empty ()
setattr(a, "spam", 42)
print(a.spam)
Useful if depending on user or data input.
Check if attribute is defined:
if not hasattr(a,"spam"):
setattr(a, "spam", 42)
print(a.spam)
Python slide 119
137. Member
of
the
Helmholtz-Association
Anonymous Function Lambda
Also known as lambda expression and lambda form
>>> f = lambda x, y: x + y
>>> f(2, 3)
5
>>> (lambda x: x**2)(3)
9
Useful if only a simple function is required as an parameter in a
function call:
>>> friends = ["alice", "Bob"]
>>> friends.sort ()
>>> friends
[’Bob ’, ’alice ’]
>>> friends.sort(key = lambda a: a.upper ())
>>> friends
[’alice ’, ’Bob ’]
Python slide 120
138. Member
of
the
Helmholtz-Association
Functions Parameters from Lists and Dictionaries
def spam(a, b, c, d):
print(a, b, c, d)
Positional parameters can be created by lists:
>>> args = [3, 6, 2, 3]
>>> spam (* args)
3 6 2 3
Keyword parameters can be created by dictionaries:
>>> kwargs = {"c": 5, "a": 2, "b": 4, "d":1}
>>> spam (** kwargs)
2 4 5 1
Python slide 121
139. Member
of
the
Helmholtz-Association
Variable Number of Parameters in Functions
def spam (*args , ** kwargs ):
for i in args:
print(i)
for i in kwargs:
print(i, kwargs[i])
>>> spam(1, 2, c=3, d=4)
1
2
c 3
d 4
Python slide 122
140. Member
of
the
Helmholtz-Association
Global and Static Variables in Functions
global links the given name to a global variable
Static variable can be defined as an attribute of the function
def myfunc ():
global max_size
if not hasattr(myfunc , "_counter"):
myfunc._counter = 0 # it doesn ’t exist yet ,
# so initialize it
myfunc._counter += 1
print("{0:d}. call".format(myfunc._counter ))
print("max size is {0:d}".format(max_size ))
...
>>> max_size = 222
>>> myfunc ()
1. call
max size is 222
Python slide 123
141. Member
of
the
Helmholtz-Association
Map
Apply specific function on each list element:
>>> li = [1, 4, 81, 9]
>>> mapli = map(math.sqrt , li)
>>> mapli
<map object at 0x7f5748240b90 >
>>> list(mapli)
[1.0, 2.0, 9.0, 3.0]
>>> list(map(lambda x: x * 2, li))
[2, 8, 162, 18]
Functions with more then one parameter requires an additional
list per parameter:
>>> list(map(math.pow , li , [1, 2, 3, 4]))
[1.0, 16.0, 531441.0 , 6561.0]
Python slide 124
142. Member
of
the
Helmholtz-Association
Filter
Similar to map , but the result is a new list with the list elements,
where the functions returns True .
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
liFiltered = filter(lambda x: x % 2, li)
print("li =", li)
print("liFiltered =", list(liFiltered ))
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
liFiltered = [1, 3, 5, 7, 9]
Python slide 125
143. Member
of
the
Helmholtz-Association
Zip
Join multiple sequences to one list of tuples:
>>> list(zip("ABC", "123"))
[(’A’, ’1’), (’B’, ’2’), (’C’, ’3’)]
>>> list(zip([1, 2, 3], "ABC", "XYZ"))
[(1, ’A’, ’X’), (2, ’B’, ’Y’), (3, ’C’, ’Z’)]
Useful when iterating on multiple sequences in parallel
Example: How to create a dictionary by two sequences
>>> dict(zip(("apple", "peach"), (2 ,0)))
{’apple ’: 2, ’peach ’: 0}
Python slide 126
144. Member
of
the
Helmholtz-Association
Iterators (1)
What happens, if for is applied on an object?
for i in obj:
pass
The __iter__ method for obj is called, return an iterator.
On each loop cycle the iterator.__next__() method will be
called.
The exception StopIteration is raised when there are no
more elements.
Advantage: Memory efficient (access time)
Python slide 127
145. Member
of
the
Helmholtz-Association
Iterators (2)
class Reverse:
def __init__(self , data ):
self.data = data
self.index = len(data)
def __iter__(self ):
return self
def __next__(self ):
if self.index == 0:
self.index = len(self.data)
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
>>> for char in Reverse("spam"):
... print(char , end=" ")
...
m a p s
Python slide 128
146. Member
of
the
Helmholtz-Association
Generators
Simple way to create iterators:
Methods uses the yield statement
⇒ breaks at this point, returns element and continues there
on the next iterator.__next__() call.
def reverse(data ):
for element in data [:: -1]:
yield element
>>> for char in reverse("spam"):
... print(char , end=" ")
...
m a p s
Python slide 129
149. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 131
151. Member
of
the
Helmholtz-Association
IPython (II)
Tab-completion
Command history retrieval across session
User-extensible ‘magic’ commands
%timeit ⇒Time execution of a Python statement or expression
using the timeit module
%cd ⇒Change the current working directory
%edit ⇒Bring up an editor and execute the resulting code
%run ⇒Run the named file inside IPython as a program
⇒more ’magic’ commands
⇒IPython documentation
Python slide 133
152. Member
of
the
Helmholtz-Association
PIP Installs Python/Packages (I)
Command pip
A tool for installing Python packages
Python 2.7.9 and later (on the python2 series), and Python
3.4 and later include pip by default
Installing Packages
$ pip3 install SomePackage
$ pip3 install --user SomePackage #user install
Uninstall Packages
$ pip3 uninstall SomePackage
Python slide 134
153. Member
of
the
Helmholtz-Association
PIP Installs Python/Packages (II)
Listing Packages
$ pip3 list
docutils (0.9.1)
Jinja2 (2.6)
Pygments (1.5)
Sphinx (1.1.2)
$ pip3 list --outdated
docutils (Current: 0.9.1 Latest: 0.10)
Sphinx (Current: 1.1.2 Latest: 1.1.3)
Searching for Packages
$ pip3 search "query"
⇒pip documentation
Python slide 135
154. Member
of
the
Helmholtz-Association
pyenv - Simple Python Version Management (I)
Easily switch between multiple versions of Python
Doesn’t depend on Python itself
Inserts directory of shims3 at the front of your PATH
Easy Installation:
$ git clone https :// github.com/yyuu/pyenv.git ~/. pyenv
$ echo ’export PYENV_ROOT="$HOME /. pyenv"’ >> ~/. bashrc
$ echo ’export PATH=" $PYENV_ROOT/bin:$PATH"’ >> ~/. bashrc
$ echo ’eval "$(pyenv init -)"’ >> ~/. bashrc
⇒pyenv repository
3
kind of infrastructure to redirect system/function calls
metaphor: A shim is a piece of wood or metal to make two things fit together
Python slide 136
155. Member
of
the
Helmholtz-Association
pyenv - Simple Python Version Management (II)
Install Python versions into $PYENV_ROOT/versions
$ pyenv install --list # available Python versions
$ pyenv install 3.5.2 # install Python 3.5.2
Change the Python version
$ pyenv global 3.5.2 # global Python
$ pyenv local 3.5.2 # per -project Python
$ pyenv shell 3.5.2 # shell -specific Python
List all installed Python versions (asterisk shows the active)
$ pyenv versions
system
2.7.12
* 3.5.2 (set by PYENV_VERSION environment variable)
Python slide 137
156. Member
of
the
Helmholtz-Association
Virtual Environments
Allow Python packages to be installed in an isolated location
Use cases
Two applications need different versions of a library
Install an application and leave it be
Can’t install packages into the global site-packages directory
Virtual environments have their own installation directories
Virtual environments don’t share libraries with other virtual
environments
Available implementations:
virtualenv (Python 2 and Python 3)
venv (Python 3.3 and later)
Python slide 138
157. Member
of
the
Helmholtz-Association
virtualenv
Install (Python 3.3 and later include venv by default)
$ pip3 install virtualenv
Create virtual environment
$ python3 -m virtualenv /path/to/env
Activate
$ source /path/to/env/bin/activate
Deactivate
$ deactivate
⇒Virtualenv documentation
Python slide 139
158. Member
of
the
Helmholtz-Association
pep8 - Python Enhancement Proposal
PEP8 is a style guide for Python and gives coding conventions
for:
Code layout / String Quotes / Comments / ...
pep8 is a tool to check your Python code against some of the
style conventions in PEP 8.
Usage
$ python3 -m pep8 example.py
example.py :6:6: E225 missing whitespace around
operator
⇒PEP8 documentation
Python slide 140
159. Member
of
the
Helmholtz-Association
Pylint (I)
pylint is the lint implementation for python code
Checks for errors in Python code
Tries to enforce a coding standard
Looks for bad code smells
Displays classified messages under various categories such as
errors and warnings
Displays statistics about the number of warnings and errors
found in different files
Python slide 141
160. Member
of
the
Helmholtz-Association
Pylint (II)
The code is given an overall mark
$ python3 -m pylint example.py
...
Global evaluation
-----------------
Your code has been rated at 10.00/10
(previous run: 9.47/10 , +0.53)
⇒Pylint documentation
Python slide 142
161. Member
of
the
Helmholtz-Association
Software testing
Part of quality management
Point out the defects and errors that were made during the
development phases
It always ensures the users or customers satisfaction and
reliability of the application
The cost of fixing the bug is larger if testing is not done
⇒testing saves time
Python testing tools
pytest
unittest
. . .
Python slide 143
162. Member
of
the
Helmholtz-Association
pytest
Easy to get started
test_ prefixed test functions or methods are test items
Asserting with the assert statement
pytest will run all files in the current directory and its
subdirectories of the form test_*.py or *_test.py
Usage:
$ python3 -m pytest
...
$ python3 -m pytest example.py
...
⇒pytest documentation
Python slide 144
163. Member
of
the
Helmholtz-Association
pytest Example: Check Function Return Value
def incr(x):
return x + 11
def test_incr ():
assert incr (3) == 4
$ python3 -m pytest -v example1_test.py
...
____________________ test_incr _____________________
def test_incr ():
> assert incr (3) == 4
E assert 14 == 4
E + where 14 = incr (3)
example1_test.py:5: AssertionError
============= 1 failed in 0.00 seconds =============
Python slide 145
168. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 148
169. Member
of
the
Helmholtz-Association
Regular Expressions – Introduction
Regular expression (RegExp):
Formal language for pattern matching in strings
Motivation: Analyze various text files:
Log files
Data files (e.g. experimental data, system configuration, . . .)
Command output
. . .
Python modul: import re
>>> re.findall(r"a.c", "abc aac aa abb")
[’abc ’, ’aac ’]
Remember:
r"..." ⇒ raw string (escape sequences are not
interpreted)
Python slide 149
170. Member
of
the
Helmholtz-Association
Regular Expressions – Character Classes
Class/set of possible characters: [!?:.,;]
^ at the beginning negates the class.
e.g.: [^aeiou] ⇒ all character beside the vocals
Character class in pattern tests for one character
The . represents any (one) character
Predefined character classes:
name c h a r a c t e r Acr . negated
whitespace [ t n r f ] s S
word c h a r a c t e r [ a−zA−Z_0−9] w W
d i g i t [0 −9] d D
>>> re.findall(r"sds", "1 22 4 22 1 a b c")
[’ 4 ’, ’ 1 ’]
>>> re.findall(r"[^ aeiou]", "Python Kurs")
[’P’, ’y’, ’t’, ’h’, ’n’, ’ ’, ’K’, ’r’, ’s’]
Python slide 150
171. Member
of
the
Helmholtz-Association
Regular Expressions – Quantifiers
Quantifier can be defined in ranges (min,max):
d{5,7} matches sequences of 5-7 digits
Acronym:
{1} one−time occurrence Default
{0 ,} none to m u l t i p l e occurrence ∗
{0 ,1} none or one−time occurrence ?
{1 ,} at l e a s t one−time occurrence +
>>> re.findall(r"[ab]{1 ,2}", "a aa ab ba bb b")
[’a’] [’aa ’] [’ab ’] [’ba ’] [’bb ’] [’b’]
>>> re.findall(r"d+", "1. Python Kurs 2012")
[’1’, ’2012’]
Python slide 151
172. Member
of
the
Helmholtz-Association
Regular Expressions – Anchors
Anchors define special restriction to the pattern matching:
b word boundary , switch between w and W
B negate b
^ s t a r t of the s t r i n g
$ end of the s t r i n g
>>> re.findall(r"^d+", "1. Python Course 2015")
[’1’]
Look-around anchors (context):
Lookahead
ab(?=c ) matches "ab" i f it ’ s part of "abc"
ab ( ? ! c ) matches "ab" i f not f o l l o w e d by a "c"
Lookbehind
(<=c ) ab matches "ab" i f it ’ s part of "cab"
(<!c ) ab matches "ab" i f not behind a "c"
Python slide 152
173. Member
of
the
Helmholtz-Association
Regular Expression – Rules for Pattern Matching
Pattern analyzes will start at the beginning of the string.
If pattern matches, analyze will continue as long as the
pattern is still matching (greedy).
Pattern matching behavior can be changed to non-greedy by
using the "?" behind the quantifier.
⇒ the pattern analyzes stops at the first (minimal) matching
>>> re.findall(r"Py.*on", "Python ... Python")
[’Python ... Python ’]
>>> re.findall(r"Py.*?on", "Python ... Python")
[’Python ’, ’Python ’]
Python slide 153
174. Member
of
the
Helmholtz-Association
Regular Expressions – Groups
() brackets in a pattern creates a group
Group name is numbered serially (starting with 1)
The first 99 groups ( 1 - 99 ) can be referenced in the same
pattern
Patterns can be combined with logical or ( | ) inside a group
>>> re.findall(r"(w+) 1", "Py Py abc Test Test")
[’Py ’, ’Test ’]
>>>
>>> re.findall(r"([A-Za -z]+|d+)","uid =2765( zdv124)")
[’uid ’, ’2765’, ’zdv ’, ’124’]
>>>
>>> re.findall(r"([.*?]| <.*? >)", "[hi]s<b>sd <hal >")
[’[hi]’, ’<b>’, ’<hal >’]
Python slide 154
175. Member
of
the
Helmholtz-Association
Regular Expressions – Group Usage
Some re.* methods return a re.MatchObject
⇒ contain captured groups
text="adm06:x:706:1000: St.Graf :/ home/adm06 :/bin/bash"
grp=re.match(
r"^([a-z0 -9]+):x:[0 -9]+:[0 -9]+:(.+):.+:.+$",text)
if (grp):
print("found:", grp.groups ())
print(" user ID=",grp.group (1))
print(" name=",grp.group (2))
$ python3 re_groups.py
found: (’adm06 ’, ’St.Graf ’)
user ID= adm06
name= St.Graf
Python slide 155
176. Member
of
the
Helmholtz-Association
Regular Expressions – Matching Flags
Special flags can changes behavior of the pattern matching
re.I : Case insensitive pattern matching
re.M : ^ or. $ will match at begin/end of each line
(not only at the begin/end of string)
re.S : . also matches newline ( n )
>>> re.findall("^abc", "Abcnabc")
[]
>>> re.findall("^abc", "Abcnabc",re.I)
[’Abc ’]
>>> re.findall("^abc", "Abcnabc",re.I|re.M)
[’Abc ’, ’abc ’]
>>> re.findall("^Abc.", "Abcnabc")
[]
>>> re.findall("^Abc.", "Abcnabc",re.S)
[’Abcn’]
Python slide 156
177. Member
of
the
Helmholtz-Association
Regular Expressions – Methods (I)
findall: Simple pattern matching
⇒ list of strings (hits)
>>> re.findall(r"[.*?]", "a[bc]g[hal]def")
[’[bc]’, ’[hal]’]
sub: Query replace ⇒ new (replaced) string
>>> re.sub(r"[.*?]", "!", "a[bc]g[hal]def")
’a!g!def ’
search: Find first match of the pattern
⇒ returns re.MatchObject or None
if re.search(r"[.*?]", "a[bc]g[hal]def"):
print("pattern matched!")
Python slide 157
178. Member
of
the
Helmholtz-Association
Regular Expressions – Methods (II)
match: Starts pattern matching at beginning of the string
⇒ returns re.MatchObject or None
text="adm06:x:706:1000: St.Graf :/ home/adm06 :/bin/bash"
grp=re.match(
"([a-z0 -9]+):x:[0 -9]+:[0 -9]+:(.+):.+:.+$",text)
compile: Regular expressions can be pre-compiled
⇒ gain performance on reusing these RegExp multiple times
(e.g. in loops)
>>> pattern = re.compile(r"[.*?]")
>>> pattern.findall("a[bc]g[hal]def")
[’[bc]’, ’[hal]’]
Python slide 158
180. Member
of
the
Helmholtz-Association
Table of Contents
Introduction
Data Types I
Control Statements
Functions
Input/Output
Errors and Exceptions
Data Types II
Object Oriented Programming
Modules and Packages
Advanced Technics
Tools
Regular Expressions (optional)
Summary and Outlook
Python slide 159
181. Member
of
the
Helmholtz-Association
Summary
We have learned:
Multiple data types (e.g. „high level“)
Common statements
Declaration and usage of functions
Modules and packages
Errors and Exceptions, exception handling
Object oriented programming
Some of the often used standard modules
Popular tools for Python developers
Python slide 160
182. Member
of
the
Helmholtz-Association
Not covered yet
Closures, decorators (function wrappers)
Meta classes
More standard modules: mail, WWW, XML, . . .
→ https://docs.python.org/3/library
Profiling, debugging, unit-testing
Extending and embedding: Python & C/C++
→ https://docs.python.org/3/extending
Third Party-Modules: Graphic, web programming, data bases,
. . . → http://pypi.python.org/pypi
Python slide 161
183. Member
of
the
Helmholtz-Association
Web Programming
CGI scripts: Module cgi (standard lib)
Web frameworks: Django, Flask, Pylons, . . .
Template systems: Cheetah, Genshi, Jinja, . . .
Content Management Systems (CMS): Zope, Plone,
Skeletonz, . . .
Wikis: MoinMoin, . . .
Python slide 162
185. Member
of
the
Helmholtz-Association
And more ...
jupyter Notebook (interactive computational environment)
Python IDEs
PyCharm
Eclipse (PyDev)
. . .
Python and other languages:
Jython: Python code in Java VM
Ctypes: Access C-libraries in Python (since 2.5 in standard lib)
SWIG: Access C- and C++ -libraries in Python
PIL: Python Imaging Library for image manipulation
SQLAlchemy: ORM-Framework
Abstraction: Object oriented access to database
Python slide 164
186. Member
of
the
Helmholtz-Association
Advanced Python Course at JSC
High-performance computing with Python (2018)
Interactive parallel programming with IPython
Profiling and optimization
High-performance NumPy and SciPy, numba
Distributed-memory parallel programming with Python and
MPI
Bindings to other programming languages and HPC libraries
Interfaces to GPUs
Python slide 165