The Python "with" Statement by Example Python’s with statement was first introduced five years ago, in Python 2.5. It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it: with open('output.txt', 'w') as f: f.write('Hi there!') The above with statement will automatically close the file after the nested block of code. Here’s another example. This code sample uses a Context object (“cairo context”) to draw six rectangles, each with a different rotation. cr.translate(68, 68) for i in xrange(6): cr.save() cr.rotate(2 * math.pi * i / 6) cr.rectangle(-25, -60, 50, 40) cr.stroke() cr.restore() That’s a fairly simple example, but for larger scripts, it can become cumbersome to keep track of which save goes with which restore, and to keep them correctly matched. By themselves, pycairo’s save and restore methods do not support the with statement, so we’ll have to add the support on our own.
PEP 8 -- Style Guide for Python Code Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such).For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead.
Learn Python The Hard Way This exercise has no code. It is simply the exercise you complete to get your computer to run Python. You should follow these instructions as exactly as possible. Go to with your browser, get the Notepad++ text editor, and install it. From now on, when I say "Terminal" or "shell" I mean PowerShell and that's what you should use. Warning Sometimes you install Python on Windows and it doesn't configure the path correctly. > python ActivePython 22.214.171.124 (ActiveState Software Inc.) based on Python 2.6.5 (r265:79063, Mar 20 2010, 14:22:52) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> quit()> mkdir mystuff > cd mystuff ... It is still correct if you see different information than mine, but yours should be similar. A major part of this book is learning to research programming topics online. Thanks to search engines such as Google you can easily find anything I tell you to find.
An Overview of Cryptography As an aside, the AES selection process managed by NIST was very public. A similar project, the New European Schemes for Signatures, Integrity and Encryption (NESSIE), was designed as an independent project meant to augment the work of NIST by putting out an open call for new cryptographic primitives. NESSIE ran from about 2000-2003. While several new algorithms were found during the NESSIE process, no new stream cipher survived cryptanalysis. As a result, the ECRYPT Stream Cipher Project (eSTREAM) was created, which has approved a number of new stream ciphers for both software and hardware implementation. Similar — but different — is the Japanese Government Cryptography Research and Evaluation Committees (CRYPTREC) efforts to evaluate algorithms submitted for government and industry applications. CAST-128/256: CAST-128, described in Request for Comments (RFC) 2144, is a DES-like substitution-permutation crypto algorithm, employing a 128-bit key operating on a 64-bit block. 3.3.
Python - Advanced List Sorting Consider a list of tuples. We could get such a list when processing information that was extracted from a spreadsheet program. For example, if we had a spreadsheet with raw census data, we can easily transform it into a sequence of tuples that look like the following. jobData= [ (001,'Albany','NY',162692), (003,'Allegany','NY',11986), ... (121,'Wyoming','NY',8722), (123,'Yates','NY',5094) ] Each tuple can be built from a row of the spreadsheet. In this case, we wrote a simple forumla in our spreadsheet to make each row into a tuple. Once we have each row as a tuple, we can put some 's around the tuples to make a list. Sorting this list can be done trivially with the list sort method. jobData.sort() Note that this updates the list in place. This kind of sort will simply compare each tuple with each other tuple. We can provide a compare function to the sort method of a list. Sorting With a Compare Function. We must define a function that behaves like the built-in cmp function.
Invent Your Own Computer Games with Python - Learn how to program with a free ebook programming tutorial Chapter 1 Read online: Chapter 1 - Installing Python Videos: Chapter 2 Read online: Chapter 2 - The Interactive Shell Chapter 3 Read online: Chapter 3 - Strings Download source: hello.py Copy source to clipboard: Use the online diff tool to find typos in your code: hello.py Chapter 4 Read online: Chapter 4 - Guess the Number Download source: guess.py Use the online diff tool to find typos in your code: guess.py Chapter 5 Read online: Chapter 5 - Jokes Download source: jokes.py Use the online diff tool to find typos in your code: jokes.py Chapter 6 Read online: Chapter 6 - Dragon Realm Download source: dragon.py Use the online diff tool to find typos in your code: dragon.py Chapter 7 Read online: Chapter 7 - Using the Debugger Chapter 8 Read online: Chapter 8 - Flow Charts Chapter 9 Read online: Chapter 9 - Hangman Download source: hangman.py Use the online diff tool to find typos in your code: hangman.py Chapter 10 Read online: Chapter 10 - Tic Tac Toe Download source: tictactoe.py Chapter 11 Download source: bagels.py
2. Built-in Functions Open a file, returning an object of the file type described in section File Objects. If the file cannot be opened, IOError is raised. When opening a file, it’s preferable to use open() instead of invoking the file constructor directly. The first two arguments are the same as for stdio‘s fopen(): name is the file name to be opened, and mode is a string indicating how the file is to be opened. The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). The optional buffering argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file.
A Quick, Painless Tutorial on the Python Language Norman Matloff University of California, Davis June 17, 2008 ©2003-2008, N. Matloff Contents What Are Scripting Languages? Languages like C and C++ allow a programmer to write code at a very detailed level which has good execution speed (especially in the case of C). The term scripting language has never been formally defined, but here are the typical characteristics: Used often for system administration, Web programming, text processing, etc. Why Python? The first really popular scripting language was Perl. Advocates of Python, often called pythonistas, say that Python is so clear and so enjoyable to write in that one should use Python for all of one's programming work, not just for scripting work. Background Needed Anyone with even a bit of programming experience should find the material through Section 8 to be quite accessible. The material beginning with Section 10 will feel quite comfortable to anyone with background in an object-oriented programming (OOP) language such as C++ or Java.
(How to Write a (Lisp) Interpreter (in Python)) Syntax and Semantics of the Lispy Scheme Subset The syntax of a language is what it looks like; the semantics is what it means. For example, in the language of mathematical expressions, the syntax for adding two plus two is "2 + 2" and the semantics of that expression is the number four. We say we are evaluating a syntactic expression when we determine its semantic referent; we would say that "2 + 2" evaluates to 4, and write that as "2 + 2" ⇒ 4. Most computer languages have a variety of syntactic conventions (keywords, infix operators, brackets, operator precedence, dot notation, semicolons, etc.), but as a member of the Lisp family of languages, all of Scheme's syntax is based on lists in parenthesized prefix notation. This may seem unfamiliar, but it has the virtues of simplicity and consistency. Note that the exclamation mark is not a special character in Scheme; it is just part of the name "set!". What A Language Interpreter Does >>> eval(parse(program))28.274333877 Execution: eval
Tutorial - Learn Python in 10 minutes - Stavros' Stuff NOTE: If you would like some Python development done, my company, Stochastic Technologies, is available for consulting. This tutorial is available as a short ebook. The e-book features extra content from follow-up posts on various Python best practices, all in a convenient, self-contained format. Preliminary fluff So, you want to learn the Python programming language but can't find a concise and yet full-featured tutorial. Properties Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e. you don't have to declare variables), case sensitive (i.e. var and VAR are two different variables) and object-oriented (i.e. everything is an object). Getting help Help in Python is always available right in the interpreter. >>> help(5)Help on int object:(etc etc) >>> dir(5)['__abs__', '__add__', ...] >>> abs. Syntax Python has no mandatory statement termination characters and blocks are specified by indentation. Data types You can access array ranges using a colon (:).
Cheatsheet - Python & R codes for common Machine Learning Algorithms In his famous book – Think and Grow Rich, Napolean Hill narrates story of Darby, who after digging for a gold vein for a few years walks away from it when he was three feet away from it! Now, I don’t know whether the story is true or false. But, I surely know of a few Data Darby around me. These people understand the purpose of machine learning, its execution and use just a set 2 – 3 algorithms on whatever problem they are working on. They don’t update themselves with better algorithms or techniques, because they are too tough or they are time consuming. Like Darby, they are surely missing from a lot of action after reaching this close! Today’s cheat sheet aims to change a few Data Darby’s to machine learning advocates. For the super lazy Data Darbies, we will make your life even easier. Keep this cheat sheet handy when you work on data sets. download the complete cheat sheet here: PDF Version Related Year in Review: Best of Analytics Vidhya from 2015 December 28, 2015 August 10, 2015
Generator Tricks for Systems Programmers Generator Tricks for Systems Programmers Copyright (C) 2008David M. Presented at PyCon'08, March 13, 2008, Chicago, Illinois. Related Tutorials Introduction This tutorial discusses various techniques for using generator functions and generator expressions in the context of systems programming. Support Data Files The following file contains some supporting data files that are used by the various code samples. Code Samples Here are various code samples that are used in the course. Part 2 : Processing Data Files nongenlog.py.
Understanding Python's "with" statement Fredrik Lundh | October 2006 | Originally posted to online.effbot.org Judging from comp.lang.python and other forums, Python 2.5’s new with statement (dead link) seems to be a bit confusing even for experienced Python programmers. As most other things in Python, the with statement is actually very simple, once you understand the problem it’s trying to solve. Consider this piece of code: set things up try: do something finally: tear things down Here, “set things up” could be opening a file, or acquiring some sort of external resource, and “tear things down” would then be closing the file, or releasing or removing the resource. If you do this a lot, it would be quite convenient if you could put the “set things up” and “tear things down” code in a library function, to make it easy to reuse. def controlled_execution(callback): set things up try: callback(thing) finally: tear things down def my_function(thing): do something controlled_execution(my_function) This wasn’t very difficult, was it?