2015-10-02 23:12:30

(Disclaimer: I have never written a tutorial worth anything. This does not try to explain programming concepts, and instead focuses on input/output. First post is basics. Will try to continue into external modules, since those are where all the power lies.)



So they say that Python is awesome.
But let's just give the tour, and you can decide.

This will be fairly thorough, but you absolutely should not try to absorb everything at once. Install Python, get the basics of the command line, and meet me at the next heading, if you don't feel like it's time for all those packages and complex command line features.

Here are some important links:
Python official site: http://python.org
Installer for Python 2.7: https://www.python.org/downloads/release/python-2710/
Googling "Python Tutorial" might also come in handy.
Lots of Python libraries, particularly accessibility-related: http://hg.q-continuum.net/
- Specifically, accessible_output2 is the most straightforward way to use text-to-speech and braille output: http://hg.q-continuum.net/accessible_ou … ve/tip.zip

You might also want Pygame: http://pygame.org/
Or Pyglet: http://pyglet.org
And if you do anything complex enough, you'll want to find Numpy or Scipy, both of which are great if you wan to do low-level audio manipulation.
(People who have spent more time with Python will tell you that Pip is an excellent way to easy-install packages. I haven't bothered, so can't comment.)

Anyway, let's get on to the instructions.

It is advisable to be comfortable using the Command Prompt. You can get away with a few basics easily enough:
- you can find the command prompt in Windows, either by using the built-in search feature, or by typing "cmd" or "command" into the run dialog (windows+r). It's probably in c:\windows\system32\cmd.exe.
- The most common commands:
cd documents
^ changes directory to documents, if possible.
cd ..
^ Moves to the parent directory. SO if you're in c:\my documents, and type cd .., you will move to c:\.
c:, d:, e:, f:, etc
^ change drive. You need to do this explicitly instead of trying to use cd /d.
cd /d c:\users\
^ change directory, given the absolute path.
pushd c:\users\
^ Pushes the current directory onto the stack, then changes to c:\users\. This is useful if you'll want to go back to the previous directory later.
popd
^ Returns to the last directory on the stack.

That's pretty much it. You can use tab and shift+tab to cycle through files and folders, including searching or autocompleting based on what you've already entered.
And any file or directory name with spaces or special characters should be surrounded in quotes. So if you want to move to c:\my documents, you'd type:
cd /d "c:\my documents"
Entering a filename and pressing enter will have windows try to open said file.
Some programs take extra command line arguments. This is relevant here, because a lot of packages use a setup.py script, and you need to cd into the corresponding directory and type:
setup.py install
And it will either install the package, or tell you what other packages you need to hunt down. Luckily, just about everything you'd need will be either at one of the above links, or at http://pypi.python.org/

If you want to mess with environment variables, you can set it so that you can run the python console by just typing "python" at the command line. But I'm too lazy for that, since I just installed python in c:\python27.

Getting started

I'm assuming you have the python console up and running. If not, try typing this at the command line:
c:\python27\python.exe
The important part is running python.exe, from wherever it installed.
If it works, it should display a message with version number and OS information, then leave you at a prompt that looks like this:

>>>

I have no idea how to save console sessions. It's probably something straightforward once you figure out what the session is called internally. But, basically, I treat the console as a place to test and debug things.

Anyway, basics of syntax:

C:\Users\CAE>c:\Python27\python.exe
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Hello, jys"
Hello, jys
>>> my_number=5
>>> my_number
5
>>> print my_number
5
>>> print "My number is " + my_number + "."
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "With the str function, we see that my number is " + str(my_number) +
"!"
With the str function, we see that my number is 5!
>>> a=my_number+1
>>> a
6
>>> b=a/2
>>> b
3
>>> c=b/2
>>> c
1
>>> c=b/2.0 # explicitly use floating point division.
>>> c
1.5
>>> a%my_number
1
>>> b*c
4.5
>>> type(a)
<type 'int'>
>>> type(b)
<type 'int'>
>>> type(c)
<type 'float'>
>>> if a>b:
...     print str(a) + " is greater than " + str(b)
... else :
...     print str(a) + " is not greater than " + str(b) + "!"
...
6 is greater than 3
>>> while a>0 :
...     a-=1
...     print str(a)
...
5
4
3
2
1
0
>>> for i in xrange(10) :
...     print i
...
0
1
2
3
4
5
6
7
8
9
>>> my_list=[2, 4, 8, 19]
>>> for i in my_list : print i
...
2
4
8
19

You should be able to type everything after >>> and get the same output.
Python detects blocks like if, else, while, and for, by indentation level. This is not as hard to keep track of as it sounds, though I still feel better adding a comment at the bottom, to indicate what block just closed.
Python comments work in two ways:
single-line comments begin with #

>>> #This is a comment.

And multi-line comments use tripple quotes:

"""
This is a multi-line comment.
These are usually used for documentation, at the start of modules, functions, classes, etc.
"""

Speaking of documentation:

>>> def my_function(a, b) :
...     """Prints the sum of a and b. """
...     print str(a+b)
...
>>> help(my_function)
Help on function my_function in module __main__:

my_function(a, b)
    Prints the sum of a and b.

>>> my_function(2, 2)
4

Anything with halfway decent documentation can be accessed using the help function.
Anything without decent documentation can be accessed, if all you want to see is function definitions and such.
You could type help(int), or help(5), but I don't recommend it.


Ho, a game!
I'm doing this from scratch, and don't remember everything. Watch as the help function saves loads of time:

>>> import random
>>> help(random)
Help on module random:

NAME
    random - Random variable generators.

FILE
    c:\python27\lib\random.py

DESCRIPTION
        integers
        --------
               uniform within range

        sequences
        ---------
               pick random element
               pick random sample
               generate random permutation

        distributions on the real line:
        ------------------------------
               uniform
               triangular
               normal (Gaussian)
-- More  --
>>> help(random.random)
Help on built-in function random:

random(...)
    random() -> x in the interval [0, 1).
>>> def guess() :
...     """ Generates a random number, and asks the user to guess it."""
...     answer=int(10.0*random)+1 # from 1-10
...     tries=0
...     response=-1
...     while response!=answer :
...             print "Guess:"
...             response=int(raw_input())
...             if response<answer : print "Too low"
...             elif response>answer : print "Too high"
...             else :
...                     print "Correct!"
...                     tries-=1
...             tries+=1
...     print "You completed the game in " + str(tries) + " tries"
...
>>> guess()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in guess
TypeError: unsupported operand type(s) for *: 'float' and 'module'

Awe, crud, it seems I used random() when I should have used random.random(). But don't worry, for you can repeat previous lines with the up arrow key.
(Also, this is why you usually type programs into notepad.)

>>> def guess() :
...     """ Generates a random number, and asks the user to guess it."""
...     answer=int(10.0*random.random())+1 # from 1-10
...     tries=0
...     response=-1
...     while response!=answer :
...             print "Guess:"
...             response=int(raw_input())
...             if response<answer : print "Too low"
...             elif response>answer : print "Too high"
...             else :
...                     print "Correct!"
...                     tries-=1
...             tries+=1
...     print "You completed the game in " + str(tries) + " tries"
...
>>> guess()
Guess:
1
Too low
Guess:
7
Too high
Guess:
3
Too low
Guess:
5
Too low
Guess:
6
Correct!
You completed the game in 4 tries

OK, since we're using randomness, now, you shouldn't get the same outputs. Also, I have no idea why I opened by guessing 1. (The correct move is 5.)

Also, you generally shouldn't use print, then raw_input, the way I did here. I am out of practice, as you can plainly read.
You can do this instead:

>>> raw_input("Echo:")
Echo:Moose
'Moose'

Well, that was fun.

看過來!
"If you want utopia but reality gives you Lovecraft, you don't give up, you carve your utopia out of the corpses of dead gods."
MaxAngor wrote:
    George... Don't do that.

2015-10-02 23:28:53

Hi all
This is another subject.
I'm wondering, why many audiogame developers are use python 2.7.10? The latest version is python 3.5.0. Is there any technical reasons? Or python 2.7.10 is better than the latest python?
Thanks

2015-10-02 23:43:07

A word on Dependency Scavenger Hunts: I don't even remember what dependencies different packages require, only that some require more than others. They are usually either in the same place where you found the package in the first place, or can be found at pypi.python.org or by googling the package name.
(In this post, I'll put code in blockquotes, so it's easier to jump in/out of.)

Oh, and if you want to run a program from an external .py file (notepad *.py is how I create them), import it, like so:
import my_module



Here's an excerpt from my attempt at giving Pygame easier 2D audio (will explain afterward):

import math


def convert(pan=0.0, volume=0.0):
 v = ((volume+50.0)/50.0)
 if v<0.0 :
  v=0.0
 elif v>1.0 :
  v=1.0
 pan/=10.0 # or 100.0, I forget which BGT uses.
 if pan<-1.0 :
  pan=-1.0
 elif pan>1.0 :
  pan=1.0
 
 vl = v if pan<=0.0 else v*(1.0-pan)
 vr = v if pan>=0.0 else v*(1.0+pan)
 return (vl, vr)
Explanation:

To play sound using pygame, one must setup the mixer, get a sound pointing to the correct file, then invoke its play method.
To adjust the volume and balance, however, we work with the channel that ultimately plays the sound.
(It's something of a mess. Hence, everyone trying to come up with something better.)

For example, this should play a sound in the right speaker:

import pygame
from os.path import normpath as np

pygame.mixer.init()
my_sound=pygame.mixer.Sound(np("c:\\windows\\media\\ding.wav"))
my_channel=my_sound.play()
my_channel.set_volume(0.0, 1.0)

Meh, not impressive enough.

Box2D

So, here's a Box2D example. To run it, you'll need my port of Philip_bennefall's sound_pool: https://www.sendspace.com/file/h0m7ty

Just to note, it is kinda monstrous to just read without having looked into Box2D enough to understand what half the stuff does. I basically use this tutorial as my primary reference:
http://www.iforce2d.net/b2dtut/
The point of this example is to have a ball drop onto a box, then bounce it.

from Box2D import *
import pygame
import os.path
from sound_pool import *

pygame.mixer.pre_init()
pygame.mixer.init()

world=b2World(b2Vec2(0, -10), True)
true=True
false=False
none=None
null=None

statdef=b2BodyDef()
statdef.type=b2_staticBody
statdef.position.Set(10, 0)
statbod=world.CreateBody(statdef)
box=b2PolygonShape()
box.SetAsBox(100, 1)
fixdef=b2FixtureDef()
fixdef.shape=box
fixdef.density=1
fix=statbod.CreateFixture(fixdef)

balldef=b2BodyDef()
balldef.position.Set(10, 10)
balldef.type=b2_dynamicBody
ball=world.CreateBody(balldef)
circle=b2CircleShape()
circle.m_radius=1
circdef=b2FixtureDef()
circdef.shape=circle
circdef.density=1
circfix=ball.CreateFixture(circdef)
circfix.restitution=0.25
circfix.friction=0.5

snd=os.path.normpath("c:\\users\\cae\\aviewer\\sounds\\red.wav")
pool=sound_pool()
slot=pool.play_2d(snd, 0, 0, ball.position.x, ball.position.y, True)

frame=0

class CL(b2ContactListener) :
    def BeginContact(this, contact) :
        
        print "Begin Contact..." + str(frame)
        pool.play_stationary("ball.wav", False)
        
    
    def EndContact(this, contact) :
        print "End contact. " + str(frame)
        
    

cl=CL()
world.contactListener=cl

clock=pygame.time.Clock()

while (frame<1000) :
    world.Step(clock.tick(50)*0.001, 8, 3)
    frame+=1
    pose=ball.position
    pool.update_sound_2d(slot, pose.x, pose.y)
    if(frame==500) :
        #help(ball.ApplyLinearImpulse)
        ball.ApplyLinearImpulse(b2Vec2(-30, 50), ball.position, True) # I have no idea what the last value does.
        print "SERVE!\n"
        pool.play_stationary("ball.wav", False)
    # Force.
    

If you run the above, you should notice... ur, nothing, since I didn't include the sound files. But let's assume you have the two files it needs, then run it.
You should hear a looping sound get louder, until it bounces a bit--at which point the bounce sound should play.
Then it stops for a couple seconds, then there is another bounce, and it goes flying into oblivion.
It really shouldn't go flying into oblivion. I goofed up somewhere.
The solution to the oblivion problem is to use Edges. I seem to remember some confusion as to how to use those with my copy of PyBox2D, so I went with the Rectangle, for the basic test.

I could explain that code monstrosity, but I should have started packing by now. So... HTH?

看過來!
"If you want utopia but reality gives you Lovecraft, you don't give up, you carve your utopia out of the corpses of dead gods."
MaxAngor wrote:
    George... Don't do that.

2015-10-03 02:47:15

I do recommend python 3.x, however that's just my viewpoint. Most code is easily portable to python3 using lib2to3 but some of it does not port properly and requires editing to work properly. The tutorial I'm about to give, which expands on cae_jones's tutorial, is for Python 3 programmers, although some of it will work on python 2 as well.

Functions, conditionals, and loops

If you did not understand the code writtein in post 3, I will try and explain, in some detail, most of the elements used in that post to clerify exactly what is done. I will, however, not relate to such elements.

Functions

A function is a way of categorizing a lot of code into a simple one liner. For instance, a call to a function called play_3d_sound does a lot of things using that one function call. The function is defined using the def keyword. The code is indented; tabs or spaces are accepted, but a mix of both will result in a syntax error.
The syntax for defining a function is as follows:

def <function name> ():
# code

or

def <function name> (<argument 1>, <argument 2>, ...):
# code

If you look at each portion of the function definition syntax, you will notice that the items after the colon (":") are indented by one space. This is called the "indent level" and must always remain the same through the code while writing the function. The only time this should ever differ is if your inside a loop, conditional, class, try-accept block, or with block, or if you have finished the function. We will cover with blocks and try-accept blocks later.
An example function would be as follows:

def hello (name):
print ("Hello,", str(name))

Let's break this function down into segments:

def hello (name):

This creates the function. A function cannot be called unless it has been defined beforehand.

print ("hello", str(name))

This is the code of the function. Think of a function as a document on your computer. Inside the function is code that the function utilizes, so think of that code as text you write. The function is your document, which was blank upon definition of the function, but when you add code, your writing paragraphs for, say, a book or thesis paper.
Did you notice the str() call inside of the print() statement? It is possible to call functions inside of other functions, just like you can open more doors inside of a building.
Keep in mind that if you write this function and never call it, it will sit in memory, never being used. So, let's rewrite the function, this time calling it:

def hello (name):
print ("Hello,", str(name))

hello("Ethin")

Output:

>>> hello("Ethin")
Hello, Ethin!
>>>

Did you notice the blank line after the function definition? This is the terminator of the function. This is not required; Pythonists just use it as an indicator to them that says "Hey, this function ends here." This is also used for terminating loops, classes, exception catchers, etc. You will see it quite often.

Conditionals

If you paid attention in geometry class, you will no that a conditional says "if so and so, then so and so." Of course, you will know that a conditional can be conversed and inversed: "if A, then B.", "if B, then A.", and "If not A, then B." or "If A is not B, then C."
Python has its own way of doing this:

if A:
# code

if not A:
# code

Of course, there are if... else... elif... conditionals, which go like this:

if A:
# code
elif B:
# code
else:
#code

An example conditional would be as follows:

i = 15
if i * i = 225:
print ("i is 225!")
elif i * i * i = 3375:
print ("i is 3375!")
else:
print ("i is not 225 or 3375!")

As you noticed, we defined a variable. A variable must be defined before we could use it.

Loops

A loop is a block which basically says, "If A is B, then do B until C."
There is also a loop which says, "While A is B, then C" and "while A is in B, then C."
These loops are called the for and while loops. The for syntax is as follows:

for a in b:
# code

Replace 'a' with a variable, and replace 'b' with a list, dictionary, or function call. For instance, here's the most common for loop I use:

for i in range (1, 101):
print (i)

or

for i in xrange (1, 101, 5):
print (i)

A while loop looks similar:

i = 0
while i < 100:
print (i)
i = i + 1

This does the following:

  1. Declare the variable i with the value 0.

  2. Enter the while loop, which conditionally says, "while i is less than 100: <code>"

  3. Print i's value.

  4. Increase i by 1, while keeping the current value.

If we had simply done:

i = i

We would have caused an infinite loop, which would have run, indefinitely until control+c (CIGINT (signal interrupt)) was pressed.

Well, folks, that's all for now. See you later.

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2015-10-03 04:22:50 (edited by dhruv 2015-10-03 04:27:31)

I have no clue if this will help anyone. But here goes, anyway:

classes

Think of classes as factories. They produce class instances, which are just class objects but just configured differently. Classes hold functions and variables (which are methods and...something? properties? I have no clue, I just use the damn thing.). Classes are made like this:

#a class example
class foo(object):
    def __init__(self, num):
        self.num = num
    def print_num(self):
        print self.num
d = foo(5)
d.print_num()
inheritance

You might have noticed the (object) tag at the end of our class declaration. That means that class foo inherits from the object class. Inheritance, for those of you who are new at programming, is a way to give classes the attributes of their superclasses. Essentially what this means is that I can call any method that exists on object from class foo. You generally inherit from object in python 2 because of old python language stuff (if you wanna know more, just google why use object class python2). Python3 has new style classes (classes which inherit automatically from object) so you don't have to worry about this in python3.

list comprehensions (intermediate)

List comprehensions are a way to concisely express a concept. I'm not correctly explaining this. Let me go pull a description from google, brb...
Okay. So wikipedia tells me that a list comprehension is a syntactic construct available in some programming languages for creating a list from existing lists. Basically, you do modifications on lists to produce a new list. Example:

l = [i for i in [1, 2, 3, 4, 5]]
print l

This does nothing fancy, just iterates (more on that in a little bit) through the list [1, 2, 3, 4, 5] and produces a list. Now, to do something a little more fancy...

l = [i**2 for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
print l

This provides us with a list that has i squared. Basically, the list that has numbered is being looped on with the for loop, i is assigned to the current item the loop is working on. i**2 (** is exponentiation) is called, and afterwards i is appended to the list that this list comprehension will produce. The syntax of a list comprehension is as follows:

 [variable for variable in list if conditional]
generator expressions (intermediate)

Generator expressions are in some way pretty much same as a list, but they work differently. In a list coprehension, every value gets generated at the time that you type the code for the list comprehension. This easily becomes painful when you're working with huge data. That's where generators become handy. Generators are "lazy", which essentially means that they will only produce the next value when your program asks it to produce it. They aren't generally used, but they become helpful in the specific case when you're working with large data.

This is not a signature.

2015-10-03 22:41:15

classes

A class is like a template. You say "I want to make a cat" and you create a cat class:

class Cat(object):
    pass


Now you have a class for a cat. Next we need to figure out what a cat has and what it does. A cat has an age, so we can identify an age. It also has a name, so we can name it. It also purrs and it catches mice.
So lets create this template for a class with age, name, purr and catch mice.
We are going to use something called an init function. init is short for initialize and is run every time you create an object. We can pass the init function arguments, so we will do that. We can identify the attributes of the cat class by using the "self" keyword. So in the init function we pass in some variables as arguments and we set the self.variables to equal the passed in variables.
Cat class:

class Cat(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def purr(self):
        print("purr... purr...")

    def catch_mice(self):
        print("%s goes and stocks a hapless mouse and at the last moment the cat pounces on it! Yummm..." % self.name)


OK, so now we have a cat class with a self.age and a self.name. This Cat class is not a cat, it is all cats, so we need to create a cat that we can pet and play with:

midnight = Cat("midnight", 3)

Now we have a cat named midnight. Lets look at his age:

print(midnight.age)
3

This means that when we were creating the Cat class "self" just identified this nebulous, unidentified object. We needed to actually "create" a cat by saying "I am god, let there be midnight that is a Cat!" Now if you needed to change something to only midnight, you would need to use midnight rather than self. Otherwise you would change all cats.
For example:

midnight.age = 5

print(midnight.age)
5

So we have midnight who is an object of Cat. What else can he do? He can purr! Lets watch him purr:

midnight.purr()
purr... purr...

Awesome! Now your midnight cat purrs and has an age. He also has a catch_mice function he can do as well! But what happens if we try and make our midnight bark? We will get an error that midnight doesn't have that function. We can make it though:

def bark():
    print("Midnight expands his neck into a veritably massive lump of flesh and lets out the strangest woof ever!")

midnight.bark = bark

So now we have, in a sense, trained our midnight to bark. Lets say we would like another cat, lets create one:

frisky = Cat("Frisky", 7)

Now we have 2 cats, frisky and midnight. Lets check that they are both cats:

print(frisky.age)
7

print(midnight.age)
5

frisky.purr()
purr... purr...

midnight.purr()
purr... purr...

midnight.bark()
Midnight expands his neck into a veritably massive lump of flesh and lets out the strangest woof ever!

frisky.bark()
ERROR ERROR!!!! Cats can't bark!

Frisky has all the properties of a cat, but not the special property we gave to midnight. we would have to give him special training in order to have him bark.

This is a class. It is really simple, so sorry for taking such a long post to explain it. A class is just a template, like a document or email. You create the class which has fields and properties that you specify (an email has subject, to and body for the properties and send, reply and forward for the functions). Then you create an instance of that object. midnight = Cat("Midnight", 3). When we create the object, our __init__ function is run, setting the self.name as name and the self.age as age. Then it replaces self with midnight.
That's all, when you create midnight, you are saving that specific template under the name of midnight. It is an instance of the template Cat, but is it THE template Cat? no! midnight is just 1 Cat.

2015-10-04 03:20:57

string formatting

There are 2 ways to format a string in python. String formatting essentially means that you replace some words in the string where denoted. Strings are like templates and you fill them with stuff.
Example 1. string formatting with %s:

mystring = "hi, %s! how are you doing?"
print mystring%("dhruv")

Essentially, you denote where words should be replaced in the string with the %s tag. This can do a lot more crazy stuff, like digits and floating point numbers and whatnot, so googling might be helpful.
example 2. string formatting with .format:

mystring = "Hi, {}! how are you doing?"
print mystring.format("bob")

In this example, we use {} to denote the place where stuff should be put. .format and %s are pretty much functionally equivalent, so use what you're more comfortable with.

string concatenation

Many people will probably be familiar with this. In the first post, cae_jones showed us this.
The difference between string formatting and string concatenation is that string "templates" are reusable. In string formatting, you have a template you can plug your variables in, whereas in string concatenation you just add strings and they're not reusable. Example below:
example 3. string concatenation:

myname = "rambo"
print "hi", + myname+"!"

Essentially, you add (concatenate) strings together to make a new string.

This is not a signature.

2015-10-04 05:39:27

Input and Output

IO (or I/O) (input/output) is the concept of reading data (the "input") from a file or stream and sending the data to a destination (the "output"). IO can be done in many different ways. In this tutorial, we'll cover IO using the print statement, input() function call, and IO using files.

Using print to send output to a file or stream

In Python 3.x, the print statement's syntax looks like this:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

You will notice several strange things about the syntax of this functions. The *objects parameter might look out of place because from what I can tell, it has not been referenced. The * operator in a function parameter list means that the rest of the parameter list is infinite. Basically, print() could take an indefinite number of arguments.
The sep=' ' parameter is the separator between parameters. This means that after each parameter that is not a parameter that is sep, end, file, or flush, a space is placed. This can be changed to anything you like.
The end='\n' parameter is the character (or characters) that is or are placed when the statement ends. By default, a \n (newline) is placed, causing the operating system to push up all the text previously entered and create an empty space below the text at the bottom of the screen for the cursor to be placed. After that's done, the cursor is set back at the beginning of the empty space created on the screen and is ready for more input.
the file=sys.stdout parameter is the stream or file (or location) for the output to be sent. This means that the print function could be technically be used to print data to files, although the file operations (covered later in this post) is recommended, as it is quicker and more efficient.
The flush=false parameter indicates if all data should be placed into a buffer, and then sent to the location specified in the file parameter or immediately sent to the location specified in the file parameter without buffering it. Usually, this parameter is set to false because buffering allows a memory space to be created for the text to be sent to allow formatting and string concatenation to be completed. If set to true, the entire string will be sent, which may or may not cause errors in the string sent.
An example print statement would be as follows:

print ("Hello world!")

An example print statement using separators and end parameter definitions would be as follows:

print ("Hello world!", sep="\0", end="\n")

In this statement, the system sends the null character, \0, as the separator, and sends a newline (\n) as an ending line terminator.
In python 2.x, the print statement is as follows:

print(*objects, sep=' ', end='\n', file=sys.stdout)

As you can see, there is no flush parameter, forcing input to always be buffered.

Reading and writing to files

Reading and writing to files is similar to using standard IO. In this tutorial, I'll use open() to write to files, as it allows one of the cleanest methods of writing to and reading from files.
The syntax for open() is as follows:
open():

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Open() opens file and returns a corresponding file object. If the file cannot be opened, an OSError is raised.
file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation 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). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:
'r'
open for reading (default)
'w'
open for writing, truncating the file first
'x'
open for exclusive creation, failing if the file already exists
'a'
open for writing, appending to the end of the file if it exists
'b'
binary mode
't'
text mode (default)
'+'
open a disk file for updating (reading and writing)
'U'
universal newlines mode (deprecated)
The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.
As mentioned in the Overview in the Python documentation, Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.
Note that Python doesn’t depend on the underlying operating system’s notion of text files; all the processing is done by Python itself, and is therefore platform-independent.
buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

  • Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.

  • “Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.
    encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding and decoding errors are to be handled--this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with codecs.register_error() is also valid. The standard names include:

  • 'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect.

  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.

  • 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data.

  • 'surrogateescape' will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.

  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.

  • 'backslashreplace' replaces malformed data by Python’s backslashed escape sequences.

  • 'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} escape sequences.

newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

  • When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

  • When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be True (the default) otherwise an error will be raised.
A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).
The newly created file is non-inheritable.
The following example uses the dir_fd parameter of the os.open() function to open a file relative to a given directory:

>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd)  # don't leak a file descriptor

The type of file object returned by the open() function depends on the mode. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a subclass of io.TextIOBase (specifically io.TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass of io.BufferedIOBase. The exact class varies: in read binary mode, it returns a io.BufferedReader; in write binary and append binary modes, it returns a io.BufferedWriter, and in read/write mode, it returns a io.BufferedRandom. When buffering is disabled, the raw stream, a subclass of io.RawIOBase, io.FileIO, is returned.

Using asynchronous functions, loops, and context managers

Python 3.5 adds the 'async def', 'async with', and 'async for' syntax, allowing the creation of asynchronous functions, context managers, and for loops. It is unknown if Python will add an 'async while' syntax.
The asynchronous function definition is as follows:

async def <function name> ():
# code

or

async def <function name> (<parameters):

Below is the full text of the python change for this addition:

PEP 492 greatly improves support for asynchronous programming in Python by adding awaitable objects, coroutine functions, asynchronous iteration, and asynchronous context managers.
Coroutine functions are declared using the new asyncdef syntax:
>>> async def coro():
...     return 'spam'
Inside a coroutine function, the new await expression can be used to suspend coroutine execution until the result is available. Any object can be awaited, as long as it implements the awaitable protocol by defining the __await__() method.
PEP 492 also adds the async for statement for convenient iteration over asynchronous iterables.
An example of a simple HTTP client written using the new syntax:

import asyncio

async def http_get(domain):
    reader, writer = await asyncio.open_connection(domain, 80)

    writer.write(b'\r\n'.join([
        b'GET / HTTP/1.1',
        b'Host: %b' % domain.encode('latin-1'),
        b'Connection: close',
        b'', b''
    ]))

    async for line in reader:
        print('>>>', line)

    writer.close()

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(http_get('example.com'))
finally:
    loop.close()

Similarly to asynchronous iteration, there is a new syntax for asynchronous context managers. The following script:

import asyncio

async def coro(name, lock):
    print('coro {}: waiting for lock'.format(name))
    async with lock:
        print('coro {}: holding the lock'.format(name))
        await asyncio.sleep(1)
        print('coro {}: releasing the lock'.format(name))

loop = asyncio.get_event_loop()
lock = asyncio.Lock()
coros = asyncio.gather(coro(1, lock), coro(2, lock))
try:
    loop.run_until_complete(coros)
finally:
    loop.close()

will print:
coro 2: waiting for lock
coro 2: holding the lock
coro 1: waiting for lock
coro 2: releasing the lock
coro 1: holding the lock
coro 1: releasing the lock
Note that both async for and async with can only be used inside a coroutine function declared with async def.
Coroutine functions are intended to be run inside a compatible event loop, such as asyncio.Loop.

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github