Python Tutorial

Python is a widely-used programming language. It is:

  • High*level: Python automates low-level operations such as memory management. It leaves the programmer with a bit less control but has many benefits including code readability and minimal code expressions.
  • General*purpose: Python is built to be used in all contexts and environments. An example of a non-general-purpose language is PHP: it is designed specifically as a server-side web-development scripting language. In contrast, Python can be used for server-side web development, but also for building desktop applications.
  • Dynamically typed: Every variable in Python can reference any type of data. A single expression may evaluate to data of different types at different times. Due to that, the following code is possible:

Python logo

if something:
    x = 1
else:
    x = 'this is a string'
print(x)
  • Strongly typed: During program execution, you are not allowed to do anything that's incompatible with the type of data you're working with. For example, there are no hidden conversions from strings to numbers; a string made out of digits will never be treated as a number unless you convert it explicitly:
1 + '1'  # raises an error
1 + int('1')  # results with 2
  • Beginner-friendly :): Python's syntax and structure are very intuitive. It is high level and provides constructs intended to enable writing clear programs on both a small and large scale. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It has a large, comprehensive standard library and many easy-to-install 3rd party libraries.

Its design principles are outlined in The Zen of Python.

Currently, there are two major release branches of Python which have some significant differences. Python 2.x is the legacy version though it still sees widespread use. Python 3.x makes a set of backwards-incompatible changes which aim to reduce feature duplication. For help deciding which version is best for you, see this article.

The official Python documentation is also a comprehensive and useful resource, containing documentation for all versions of Python as well as tutorials to help get you started.

There is one official implementation of the language supplied by Python.org, generally referred to as CPython, and several alternative implementations of the language on other runtime platforms. These include IronPython (running Python on the .NET platform), Jython (on the Java runtime) and PyPy (implementing Python in a subset of itself).

VersionsEdit

Python 3.xEdit

Version Release Date
[3.7] 2017-05-08
3.6 2016-12-23
3.5 2015-09-13
3.4 2014-03-17
3.3 2012-09-29
3.2 2011-02-20
3.1 2009-06-26
3.0 2008-12-03

Python 2.xEdit

Version Release Date
2.7 2010-07-03
2.6 2008-10-02
2.5 2006-09-19
2.4 2004-11-30
2.3 2003-07-29
2.2 2001-12-21
2.1 2001-04-15
2.0 2000-10-16

String function - str() and repr()Edit

There are two functions that can be used to obtain a readable representation of an object.

repr(x) calls x.__repr__(): a representation of x. eval will usually convert the result of this function back to the original object.

str(x) calls x.__str__(): a human-readable string that describes the object. This may elide some technical detail.


repr()Edit

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(). Otherwise, the representation is a string enclosed in angle brackets that contains the name of the type of the object along with additional information. This often includes the name and address of the object.

str()Edit

For strings, this returns the string itself. The difference between this and repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(). Rather, its goal is to return a printable or 'human readable' string. If no argument is given, this returns the empty string, .


Example 1:

s = """w'o"w"""
repr(s) # Output: '\'w\\\'o"w\''  
str(s)  # Output: 'w\'o"w'
eval(str(s)) == s  # Gives a SyntaxError 
eval(repr(s)) == s # Output: True

Example 2:

import datetime
today = datetime.datetime.now()
str(today)  # Output: '2016-09-15 06:58:46.915000'
repr(today) # Output: 'datetime.datetime(2016, 9, 15, 6, 58, 46, 915000)'

When writing a class, you can override these methods to do whatever you want:

class Represent(object):

    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "Represent(x={},y=\"{}\")".format(self.x, self.y)

    def __str__(self):
        return "Representing x as {} and y as {}".format(self.x, self.y)

Using the above class we can see the results:

r = Represent(1, "Hopper")
print(r)  # prints __str__
print(r.__repr__)  # prints __repr__: '<bound method Represent.__repr__ of Represent(x=1,y="Hopper")>'
rep = r.__repr__()  # sets the execution of __repr__ to a new variable
print(rep)  # prints 'Represent(x=1,y="Hopper")'
r2 = eval(rep) # evaluates rep
print(r2)  # prints __str__ from new object
print(r2 == r)  # prints 'False' because they are different objects

Credit:Stack_Overflow_Documentation