a gentle introduction to python

29
A Gentle Introduction to Python Iraklis Akritas Pipeline TD/Plugin-Tools Programmer Candidate

Upload: kishor-paul

Post on 20-Nov-2015

248 views

Category:

Documents


0 download

DESCRIPTION

it is judst jkkh jkhkk hjhk hjhkjhbubi

TRANSCRIPT

A Gentle Introduction to Python

A Gentle Introduction to Python

Iraklis Akritas Pipeline TD/Plugin-Tools Programmer Candidate

Presenter Information

Please feel free to email me with any questions as well as connect with me: EmailLinkedInTwitterGoogle+Website

Where does the name Python come from?

TheBurmese Python(Python molurus bivittatus) is the largest subspecies of theIndian Pythonand one of the six largest snakesin the world. [Wikipedia]

We wish

Python A fun language to learn and use

An important goal of the Python developers is making Python fun to use. This is reflected in the origin of the name which is derived from the television seriesMonty Python's Flying Circus.

Python CreatorGuido van Rossum is aDutchcomputer programmerwho is best known as the author of thePython programming language. In the Python community, Van Rossum is known as a "Benevolent Dictator For Life" (BDFL), meaning that he continues to oversee the Python development process, making decisions where necessary. He was employed byGoogleuntil 7 December 2012, where he spent half his time developing the Python language. In January, Guido will be moving toDropbox. [Wikipedia]

In December 1989, I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. My office would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language...

Python LingoA commonneologismin the Python community ispythonic, which can have a wide range of meanings related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is natural or shows fluency in the language, that it conforms with Python's minimalist philosophy and emphasis on readability. In contrast, code that is difficult to understand or reads like a rough transcription from another programming language is calledunpythonic.Users and admirers of Pythonmost especially those considered knowledgeable or experiencedare often referred to asPythonists,Pythonistas, andPythoneers.HINT: When googling how to get something done in python preppend pythonic way of

Advice and Resources for Python newcomersPython has a lot of free material online, do not rush to buy expensive books. One of the best books available is Dive into Python.Code Academy and Mechanical MOOC have great series about learning Python.Google also offers a Python class.Python Best Practises Stackoverflow When programming or shall I say scripting in Python, ensure that you are following a valid code formatting standard to the letter. When posting your code for help in various forums, unformatted Python code normally leads to complaints about unreadability, you will be instructed to re-format your code before getting an answer. I highly recommend Googles style guide or for the hard-core amongst us you can head to the official PEP(Python enhancement proposals). As we will see soon, formatting is a big part of Python scripting.One of my favourites, learn Python in ten minutes.

Python FAQIs Python a dead language?On the contrary Python user base is actually growing!Why use Python?Python is extremely fun to develop in.Everything can be done with Python.If something can't be done, you can create an extension for it.Everything can not only be done, but it can be done fast. For example a program that takes you weeks in C++ might take you a day in Python.Great for prototyping, and even for usage in a commercial setting.Because it is a modern, elegant, highest level OO language.Because it is highly expressive, i.e., you will earn higher productivity.Because it comes with "batteries included" i.e. libraries for whatever you want.Because it is well documented and has a well-established and growing community.

Where is Python used?Everywhere! Both in industry and AcademiaArt Middleware Tools and PluginsResearchWeb Development and Web ApplicationsGame DevelopmentWindows Applications

Python Hello World

Really Simple:

Simple:

Python Hello WorldWhat do we notice?The interchangeable use of single and double quotes in Python

Where did all the braces go? Avoid mixing tabs and spaces in the indentation of a given single block, unless you know what every system that touches your code may do with tabs. Otherwise, what you see in your editor may not be what Python sees when it counts tabs as a number of spaces. It's safer to use all tabs or all spaces for each block; how many is up to you.First of all, you can write the inner block all on one line if you like, therefore not having to care about indentation at all. The following three versions of an "if" statement are all valid and do exactly the same thing (output omitted for brevity):

Python - Why not just use braces?C/C++ code Any Problems?

The "else" always applies to the nearest "if", unless you use braces. This is an essential problem in C and C++. Of course, you could resort to always use braces, no matter what, but that's tiresome and bloats the source code, and it doesn't prevent you from accidentally obfuscating the code by still having the wrong indentation. (And that's just a very simple example. In practice, C code can be much more complex.)In Python, the above problems can never occur, because indentation levels and logical block structure are always consistent. The program always does what you expect when you look at the indentation.

Python Hello WorldDefining functions and using control flow statements Use of the def keyword and colonNo need for braces when using control flow statementsWhat are those weird variables that have two leading and ending underscores such as __name__ and what is the use of __main__?rather than devising a new syntax for special kinds of class methods (such as initializers and destructors), I decided that these features could be handled by simply requiring the user to implement methods with special names such as __init__, __del__, and so forth. This naming convention was taken from C where identifiers starting with underscores are reserved by the compiler and often have special meaning (e.g., macros such as __FILE__ in the C preprocessor).The if __name__ == "__main__": ... trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. -- [Demo 5]

When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value __main__. If this file is being imported from another module, __name__ will be set to a different value.12

Python VersionsPlease note that Python has different versions:Newer versions add new functionality but many times also modify existing functionality, beware of the changes! You may be unpleasantly surprised that a function you used to use in the past takes additional or fewer arguments or does not require brackets etc Current stable version is Python 2.7.3Current development version is Python 3.3.0Massive discussion amongst the community about moving to Python 3 or staying with 2.HINT: The virtualenv kit provides the ability to create virtual Python environments that do not interfere with either each other, or the main Python installation.

Python VariablesPython uses hash # for commentsDynamic typingIn Java, C++, and other statically typed languages, you must specify the data type of the function return value and each function argument. On the other hand, Python is a dynamically typed language. In Python you never have to explicitly specify the data type of anything. Based on what value you assign, Python will keep track of the data type internally.IntFloatStringsLists - like one-dimensional arraysTuplesDictionaries - associative arraysBooleans and NoneDecimal and set types are also availableMutable vs UnmutableThe value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. An objects mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

Python Integers and floatsPython will *always convert integer variables to floats during.

A perfect time to talk about casting any suggestions of how it is done?

Funny moment [discovered yesterday ]Remember when I was talking about Python different versions? Well when I was trying to divide two integers together I was always getting a float result! Why?You need to know at least that the math functionalityischanging, even if you don't care as much about the actual implementation. Many programmers recognize that this is one of the most controversial updates to Python so far.What is "true division" you ask? It means that even if with a pair of integer operands, the result is a floating-point value instead of a truncated integer result.

Python - Stringsstr classString functionsString concatenation

Python - ListsList functionalityUse for homogenous collectionsMutable - that is, you can delete or add elements, or change the value of any of the elements inside the list.Lists uses [] notation in PythonLists cannot be used in certain contexts. For example, you can't use a list as the key in a dictionary.List slicing/steppingHow do we go about retrieving list members in popular languages such as C++ and Java? Last, first, first five, last six, reverse etc?

From simple all element printing

To

17

Python - TuplesUse for heterogeneous collections.Similar to what you'd use structs for in C/C++Immutable - Once you have assembled a tuple, you cannot add or delete elements or change the value of an element inside the tuple.You can't add elements to a tuple. Tuples have no append or extend method.You can't remove elements from a tuple. Tuples have no remove or pop method.You can't find elements in a tuple. Tuples have no index method.You can, however, use in to see if an element exists in the tuple.Tuples use the () notation in PythonWhen shall I use them?Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.

Python - DictionariesPython dictionaries are like hash tablesDictionaries use the {} notation in PythonGood alternative for switch statements Capabilities:Ability to iterate over keys or values.Ability to add key-value pairs dynamically.Look-up by key.

Python Booleans - NonePython uses True and False for bool operations. Please note the capitalized first letter.None. Basically, the data type means non existent, not known or empty. Use for error checking etc

Python Control Flow StatementsIf/elseParentheses arenotneeded around the condition. Use parentheses to group sub-expressions and control order of evaluation when the natural operator precedence is not what you want.For loopWhile loop

Python FunctionsAs mentioned before functions in Python use the def keyword.Remember the indentation rules and the colon after the parenthesis.Python functions do not need to specify return types, if you need to return one or more values (data structure) then just use the return keyword.Python functions do not specify parameter types.Depending on who will use the program you may have to validate input parameters.Default parameters -> non-default arguments come before default argumentsWe will briefly revisit functions in a moment.

Python - ClassesA brief demo about classesPython encapsulation Many Python users don't feel the need for private variable. Some considerinformation hidingto beunpythonic, in that it suggests that the class in question contains ill-planned internals

Use of _ for methods, variables

Python Few of my favourite tricks ComparisonTernary operatorPython module and class informationPower of operator

A taste of advanced topicsList comprehensionsLambdas

How to get started?Install Python and use the guide to set it upUse one of the available learning resources mentioned in these slidesGet yourself a nice IDE or a text editorText EditorsSublime TextNotepad++IDEsEclipsePyCharmWingStart Coding!

SummaryPython is a flexible and versatile language to usePython has a lot of hidden gems, I am amazed that every time I sit down to code in Python I encounter something new. Angry about the lack of braces? How about from __future__ import braces? [discovered last night]How many people think I had to install Python on the machine today to show you the demos?Python usage and community is rapidly growing. Community is also as fun and friendly as Python itself -> comments about the ability to import braces

As we are moving towards the cloud era, web languages are useful to knowPython has countless sources online to help you learn, making it tantalizingly hard to resist!

Thank you for your time and attention

Q&ADemo Plugin How do I use Python?Any questions or remarks?