Writing a script in Python to output “Hello World” on the screen can be as simple as 1,2,3. When, writing a Python program, it is useful to write it in a text editor and then save it with a .py extension. In python, there are three differents types of files ; the files with .py extension are the Python script files, the files ending .pyc represent the compiled files and the ones with .pyo extension represent the optimized byte code files. Usually, most people produce the .py files and the system handles the rest.
#!/usr/bin/python invocation tells the Operating System that the Python intepreter is needed to execute this file.
It is also important to change the executions rights by using the commands chmod +x hello.py. This command will now make the hello.py an executable file. Afterwards, ./hello.py automatically invokes the python interpreter which reads and interpretes the hello.py file. Unlike other languages, it is possible to write a simple python program with any variables or function definitions just type in the keyword
followed by the expression you want to print and then run your program.
The syntax of a python code is pretty straightforward. Generally, the syntax consists of #!/usr/bin/python invocation followed by a list of statements. These statements can be of different kinds: variables declarations, function declarations, control flow statements, loops, etc.
In Python, whenever a file is read, all the statements are executed contrary to other languages like C or Java where they only compiled. There are no variable declarations because the Python intepreter figures out what datatype the variable is. Function definitions are also a kind of statement in python. The way function are defined in python can be understood as the definition of a variable which name is the name of the function and which can be invoked by opening and closing parenthesis. It is even possible in python to assign to a variable a value which is a function.
In Python, variables do not need to be declared. The first time they are used is when they are declared. Python use dynamics typing, variables can change their type according to last assigned value,
Here you can find differents Based Type in Python
In Python, variables can not be coerced to unrelated types, an explicit conversion is required.
One of Python built-in datatypes are strings.Python strings can be enclosed in either single quotes or double quotes. String supports many operations like + to concanate a value onto a string, * to repeat the string or slicing. You can also do indexing in a string. The first character of a string has index 0.
Mathematical operation return same type as input
Lists are also another built-in datatype in Python. They are similar to arrays in other languages like Perl or Basic. They consist of a set of elements enclosed in brackets. Those elements can be of any datatype, Python keeps track of the datatype internally. You access each element like you would do in an array. The indexing in a list always starts at 0. In the example above, you can get a subset of the list, by slicing it. Slicing a list consists of accessing it by giving out two indices. The first index will be the starting point and it will take all the elements up to the second index.
Many operations can be executed with lists. In fact, you can modify a list by adding elements into it, removing elements from the list, or simply searching through the list. The examples above demonstrate those operations. To add elements into a list, you can either use
only adds one single element to the end of a list. That element can be of any datatype.
extends the list with all the elements of another list which is provided as an argument. To remove an element from a list, you can use
only removes the first occurrence of the value. You can also search a list, by using
to determine the position of the first matching element into the list.
List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used.
A tuple is defined in the same way a list is defined. The only difference is the elements are in parenthesis and a tuple is immutable. Once, you create it, you cannot change it. You can't add or remove elements into it, you can't search through them. However, you can use the operator
to see if an element is in a tuple. This operator will return True if the element is in the tuple, False otherwise.
Because, they are more efficient than lists, tuples are often used to define a constant set values. The fact that tuple are immutable is also used to store persistent sequence values and make sure that some badly written program does not try to modify the sequence.
Another built-in datatype is the dictionary. A dictionary consists of a list of keys associated with some values. In the example above, the dictionary dict has two elements: “user” with its associated value “mame” and “computer” with its associated value “foo”. You can access the values by doing dict[“user”] or dict[“computer”]. However, you can not reference the keys by doing dict[“mame”] or dict[“foo”]. You can assign a new value to a key by doing for example dict[“computer”] = “master”. The old value associated with the key “computer” is erased and the new value is set.
Conditions operators like >,<,<=, >=, in, not, etc. are used to produce boolean expressions which are useful for example for testing in
statements. In the first example, we use those operators to compare two integers. Since the values are compared, so if the expression is True, the answer is always True. Equality is represented by == and is used to test whether two values are the same. In the example above, since the values are the same, the answer is true.
However, there is another testing operator called
which is the identity testing. This operator tests whether two objects are the same, not their values. In analogy, to another language like C, this operator would test if two objects have the same pointers. In the example, [1,2] and [1,2] have the same values, but are not the same objects: they are two different list objects which are created independently. So, the test fails and returns False. However, a=[1,2,3] and b=a is always True because both variables point to the same object which is the list [1,2,3] which was created only once.
In the last example, 1 is 1 is sometimes true because there is no guarantee in Python that two integers or two strings are represented by the same object. In Python, immutable objects like integers or strings are not guaranteed to be unique unlike in some other object languages (ex. some Smalltalk implementations).
There are three types of if statements in Python:
statement which is used to test whether the expression is true, the
statement used to test with another condition and the
statement which is called when the first two conditions fail. The if statements are a type of of group of statements. If the expression is true, the statements in the indented block are executed, otherwise it goes to the other blocks. The expression doesn't need to be in parenthesis. The
blocks can contain multiples lines as long as the indentation is consistent. In this example, the for loop with the
function assign the values 0,1,2,3,4,5 to i. Then, the first
statement tests that for all values of i less than 3 (i.e. 0,1,2), just print them to the screen, else for all values of i greater than 4 (i.e 5), print 3i to the screen and for the other values (i.e. 3, 4), print 2i to the screen.
Indentation is very important in Python. Python groups statements with indentation. It replaces the use of brackets or keywords like
in other languages. All groups of statements like functions, if statements, for loops, while loops, etc..., are defined by their indentation. Indenting starts a group of statements and un-indenting it ends it. It should be consistent throughout the whole code. A group of statements having the same number of spaces belong to the same logical block.
In the example above, the two functions are the same except for the last line where the indentation is different. On the left side, the statement
is executed only if the
condition is True while on the right side since the
statement has the same indentation as the
statement, it will be executed for all the values defined by the loop.
It is important to never use tabs for indentation, always use spaces. In the text editors used to write the Python code, 1 tab can represent 4 spaces, while in others, it can represent 8 spaces. So, using tabs with different text editors can mess up your code. It is recommended to select the feature “replace tabs with spaces” present in most text editors and to use only spaces for indentation. In Python, the standard indentation which is recommended is four spaces. In ERP5, which is written in python, the recommended indentation is two spaces and thus does not follow the pure python recommendations.
loops are used to iterate the items of a sequence in order. In the example, a sequence of numbers of 1 through 9 are generated by a range function and assigned to i. First, the integer 1 is printed. Then, the first
statement tests that if the value of i is equal to 2, just continue by going to the next iteration of the loop and prints 3 and 4. The other if statement tests if the value of i is equal to 5, break out of the loop and the program ends.
Contrary to the syntax of functions in other languages like C++, Python functions don't need separate headers. When you need a function, just start it with the keyword
followed by the function name and the arguments in parenthesis. You can have multiple arguments, but they have to be separated by commas. Some arguments followed by an = assignment are called named parameters.
It is important to notice that functions in Python don't need to specify a return datatype or a datatype for their arguments; python functions can also return multiple values, of different type.
In the example above, the first function getValue1 simply returns the value of function parameter. In the second example, getValue2 has two parameters: i and another named parameter foo which is initialized to 'default'. When that function is called, if there is no second parameter, it will return the initial value 'default'. However, if the second parameter is set to another value, the function will now return the new value for that second parameter. In the third example, getValue3 the function will return the associated value with the key 'bar' and if there is no parameter it will return 'default2'. The last function getValue4 return, the number of parameters when the function is called and the keys of the names parameters stored in the **kw dictionary. The last example shows that it is possible to assign a function to a variable and later use the variable as if it were a function.
File Management allows you to read elements from a file and write them onto a file. To start manipulating a file, it is always important to first open it by using open(filename,mode). filename is a string representing the name of the file while the mode is either 'r' for reading a file or 'w' for writing in file. In the example above, myfile is created . To read the all the lines in the file myfile.readlines() has been used. readlines() reads all the lines of a file and puts them into a list. read(datasize) and readline() are also other methods to read the contents of a file. read(datasize) looks into the file and reads the quantity of lines specified by datasize. If no datasize is specified, it will read the entire file. readline() reads the file line by line.
The same syntax is for writing in a file. First, you need to open the file for writing, then use myfile.write(string). This will write the contents of the string on the output file. However, write() only writes a string, if something other than a string needs to be written, it needs to be converted to a string first. It is important to always close the file using close(), because it frees up the system ressources used by the file opened.
Python is a class based object language. Classes are declared using the class keyword. Classes may contain any number of attributes. Attributes may be of any time, including functions. A function attribute of a class is called a method. There are two kinds of methods in a python class. Those which first argument is named self. And the others, hich do not differ in terms of behaviour from any other python function.s
Methods which first argument is named self are sometimes called instance methods. They require as a first argument an instance of the class. Instantiation in python is obtained by invoking the class with an opening and closing parenthesis such as x = Account(). The result is an instance object. The getCurrentBalance method can then be called on x and returns an integer result.
It is usual in python to use the underscore sign “_” to name a method which is intended for private use only, for example for implementation purpose. However, this is only a naming convention, unlike methods starting with a double underscore “__” which are really private and can only be used within code defined in another method of the same class.
Instance methods accessed either from their class or from an instance. In the first case, they have an unbound method type and require an instance as their first argument (self). In the second case they have a bound method type and do not require to provide the self argument.
During instantiation, it may be useful to set initial properties of the instance. This is possible by using the __init__(self) method. . __init__() is known as a constructor. It is the first method and is called right after the first instance is created. self is the first argument for each method and represents the instance which has been created. In the example above, the argument original given to the class Account at creation time is passed to the __init__() method and stored as a property of the new object referenced by self. That property is later used when the method getCurrentBalance is called.
When you write long programs, it is always better to write them into multiple files for easier maintenance. You may also need a function for several programs without having to copy its definition into each program. Python's way of dealing with this issue is the use of modules. Modules in Python are files containing definitions used in a script. Modules can also contain executable statements. Definitions in a module can be imported into other modules. In the example above, three modules are created. The first module ValueModule.py has two functions definitions setValue() and printValue(), the second module CreateModule.py has one function create(). The third module Application.py( in the next slide) uses both modules for its function calls. For that, this third module needs to import them by doing import ValueModule and import CreateModule(). Then you can do a function call to use the first module by doing ValueModule.setValue() or ValueModule.printValue(10) or CreateValue.create() to use the second module.
This third module Application.py contains functions calls for the previous modules ValueModule.py and CreateModule.py. To be able to do those functions calls, we first need to import both modules. To import modules, we can use either
from module import function
. This latter expression just keeps us from having to write
when we do the function call; we can just write
.ValueModule.setValue() is the function call to the first function on the ValueModule.py. This function call will print out on the screen 2*i for all the values of i between 0 and 9. The next function call printValue(10) prints out a list containing the element 10 ten times. The last function call CreateModule.create() prints on the screen 2*x +3 for all x between 0 and 4.
There are a lot built-in functions(map,filter, lambda, reduce and zip) to handle functional programming in Python. lambda() is used to create a small function. In the example, by defining a lambda function y to compute 3i + 5 for all i. Calling then y(2) will directly produces the result. filter(function, sequence) takes two arguments: a function and a sequence and will return a sequence consisting of the elements for which the function is true. In the example above, the function f takes a parameter x and returns that parameter if x is greater than 3. So, doing filter(f,range(2,6)) will return a list containing only the values 4,5. map(function,sequence) also takes two arguments: a function and a sequence, but will return a list containing all the return values obtained by calling the function for each item in the sequence. In the example, map(f, range(1,4)) returns the list [1,4,9] which is the list of the square of the numbers 1,2,3 in range(1,4). reduce() also takes two arguments : the function and a sequence, and returns a single value which is the result obtained by calling the function on the first two items of the sequence, then on their result with the next item, and so on... reduce(f, range(1,4)) returns the value 2 obtained by doing 3-(2-1). zip() takes as arguments multiple sequences and combines them into one single sequence of tuples. Each tuple will contain the corresponding elements from the sequence arguments. In the example, zip([1,2,3],[0,0,0]) returns the sequence [(1,0),(1,0), (1,0)].
__iter__() and next() are the two methods used to define an iterator. __iter__() function returns an iterator object usually self that uses the method next() to access each element one at a time. In the example above, by using the methods __iter() and __next(), we are telling the intepreter that we want to use the class FactRange as an iterator. By creating the instance f of the class FactRange, f is also an iterator. So, when for i in f, print i is called, the intepreter keeps calling f.next(), it assigns also the factorials returned by that function to i and prints them on the screen. The use of iterators in Python is very elegant and doesn' t take up a lot of memory because the sequence is not computed all at once; each element in the sequence is only computed at the time when it is needed. This is very useful when we loop through an infinite number of iterations. The use of the exception StopIteration is important here because it allows to end the loop when the upper limit range_max is reached or in the case where the lower limit range_min is greater than the upper limit range_max.
Generators are just another way to create iterators. With generators, __iter__() and next() don' t need to be specified, they are created automatically. Generators use the same syntax than regular functions, but instead of return, they have the keyword yield for whenever they want to return data. When the yield is executed, the function remembers all the previous values and where the last statement was executed, so that when the generator function is called, it will start at the line following the yield. The generator function from the example above does the same thing that was done in the previous slide using a class. This generator function computes the factorial of all the numbers between two numbers given as parameters. Another interesting feature with generators is that they automatically raise StopIteration when they terminate.
Exceptions are the errors detected at execution time. Exceptions are syntatically correct, but produce an error message when you try to execute them. There are different types of exceptions. The First shown in the example is the ZeroDivisionError exception obtained because we tried to divide an integer by 0. The second one NameError is obtained because we tried to assign to a variable another variable that has not been defined before. The example on the right shows a way to handle the ZeroDivisionError exception. In the example, try followed by result = 1/x computes the inverse of each parameter of the function as long as there is no ZeroDivisionError exception. The except keyword allows the program to print a N/A on the screen there is a ZeroDivisionError exception.
Python standard library includes many modules useful in your interactions with the interpreter.
provides numerous functions to interact with the operating system while
is another module that gives access to the Python's interpreter internals. With its argv attribute,
can store command line arguments and with its attributes like stdin, stdout, stderr,
is able to emit warnings and error messages.
is used to provide regular expressions for advanced string processing.
gives you access to the standard C library functions for floating point maths.
are two modules for accessing the internet and processing internet protocols.
retrieves data from URLs while
is used to send mails.
is used to manipulate dates and times.
is also another module used for platform independent threads. With this library, we can run tasks on the background while the main program is running. Other modules in the standard library are
for making random selection ,
for performance measurement,
for data compression and archiving, etc.
The python community has created numerous libraries to turn python into a universal development environment.
NumPy and SciPy provide a complete collection of libraries for scientific computing and in particular for high speed matrix operations. PyQt is a great toolkit to create applications for Mac, Windows, Linux and even PDAs.
Twisted is an innovative library to create high performance networking applications which support most Internet protocols.
In the are of gaming and graphics, python includes a wide range of high performance libraries. Games such as slune demonstrate how python can be used for real time interactive applications. Python can even support hundreds of multimedia file formats through the integration of ffmpeg codes in the PyMedia library.
Python is used in bioinformatics (BioPython), system simulation (SimPy).
Integration with other languages can be performed through binding libraries such as SIP for C or C++ code. Java integration is possible through Jython, the Java based implementation of Python.