Python Notes
Python Notes
It is used for:
History:
Python was conceived in the late 1980s by Guido Van Rossum began doing its
application-based work in December of 1989 by at Centrum Wickenden &
Informatica (CWI) which is situated in Netherland. It was started firstly as a hobby
project because he was looking for an interesting project to keep him occupied
during Christmas. The programming language which Python is said to have
succeeded is ABC Programming Language, which had the interfacing with the
Amoeba Operating System and had the feature of exception handling. He had
already helped to create ABC earlier in his career and he had seen some issues with
ABC but liked most of the features. After that what he did as really very clever. He
had taken the syntax of ABC, and some of its good features. It came with a lot of
complaints too, so he fixed those issues completely and had created a good scripting
language which had removed all the flaws. The inspiration for the name came from
BBC’s TV Show – ‘Monty Python’s Flying Circus’, as he was a big fan of the TV
show and also, he wanted a short, unique and slightly mysterious name for his
invention and hence he named it Python! He was the “Benevolent dictator for life”
(BDFL) until he stepped down from the position as the leader on 12th July 2018. For
quite some time he used to work for Google, but currently, he is working at Dropbox.
The language was finally released in 1991. When it was released, it used a lot fewer
codes to express the concepts, when we compare it with Java, C++ & C. Its design
philosophy was quite good too. Its main objective is to provide code readability and
advanced developer productivity. When it was released, it had more than enough
capability to provide classes with inheritance, several core data type exception
handling and functions.
Why Python?
● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
● Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a
functional way.
Python Syntax
● Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
● Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
● Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose. Example:
print("Hello, World!")
For example, in Windows, there will likely be a program group in the Start menu
labelled Python 3.x, and under it a menu item labelled Python 3.x (32-bit), or
something similar depending on the particular installation you chose.
Alternatively, you can open a terminal window and run the interpreter from the
command line. How you go about opening a terminal window varies depending on
which operating system you’re using:
Perhaps the most well-known statement type is the if statement. For example:
There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’
is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif …
sequence is a substitute for the switch or case statements found in other languages.
2.for Statements
The for statement in Python differs a bit from what you may be used to in C or
Pascal. Rather than always iterating over an arithmetic progression of numbers (like
in Pascal), or giving the user the ability to define both the iteration step and halting
condition (as C), Python’s for statement iterates over the items of any sequence (a
list or a string), in the order that they appear in the sequence. For example (no pun
intended):
Code that modifies a collection while iterating over that same collection can be tricky
to get right. Instead, it is usually more straight-forward to loop over a copy of the
collection or to create a new collection:
The given end point is never part of the generated sequence; range(10) generates
10 values, the legal indices for items of a sequence of length 10. It is possible to let
the range start at another number, or to specify a different increment (even negative;
sometimes this is called the ‘step’):
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
To iterate over the indices of a sequence, you can combine range() and len() as
follows:
>>> print(range(10))
range(0, 10)
In many ways the object returned by range() behaves as if it is a list, but in fact it
isn’t. It is an object which returns the successive items of the desired sequence when
you iterate over it, but it doesn’t really make the list, thus saving space.
We say such an object is iterable, that is, suitable as a target for functions and
constructs that expect something from which they can obtain successive items until
the supply is exhausted. We have seen that the for statement is such a construct,
while an example of a function that takes an iterable is sum():
>>> sum(range(4)) # 0 + 1 + 2 + 3
6
Later we will see more functions that return iterables and take iterables as
arguments. Lastly, maybe you are curious about how to get a list from a range. Here
is the solution:
>>> list(range(4))
[0, 1, 2, 3]
Loop statements may have an else clause; it is executed when the loop terminates
through exhaustion of the iterable (with for) or when the condition becomes false
(with while), but not when the loop is terminated by a break statement. This is
exemplified by the following loop, which searches for prime numbers:
(Yes, this is the correct code. Look closely: the else clause belongs to
the for loop, not the if statement.)
When used with a loop, the else clause has more in common with the else clause of
a try statement than it does with that of if statements: a try statement’s else clause
runs when no exception occurs, and a loop’s else clause runs when no break occurs.
For more on the try statement and exceptions, see Handling Exceptions.
The continue statement, also borrowed from C, continues with the next iteration of
the loop:
5.pass Statements
The pass statement does nothing. It can be used when a statement is required
syntactically but the program requires no action. For example:
6.Defining Functions
We can create a function that writes the Fibonacci series to an arbitrary boundary:
The keyword def introduces a function definition. It must be followed by the function
name and the parenthesized list of formal parameters. The statements that form the
body of the function start at the next line, and must be indented.
The first statement of the function body can optionally be a string literal; this string
literal is the function’s documentation string, or docstring. (More about docstrings can
be found in the section Documentation Strings.) There are tools which use
docstrings to automatically produce online or printed documentation, or to let the
user interactively browse through code; it’s good practice to include docstrings in
code that you write, so make a habit of it.
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
Coming from other languages, you might object that fib is not a function but a
procedure since it doesn’t return a value. In fact, even functions without
a return statement do return a value, albeit a rather boring one. This value is
called None (it’s a built-in name). Writing the value None is normally suppressed by
the interpreter if it would be the only value written. You can see it if you really want to
using print():
>>> fib(0)
>>> print(fib(0))
None
It is simple to write a function that returns a list of the numbers of the Fibonacci
series, instead of printing it:
● The return statement returns with a value from a function. return without an
expression argument returns None. Falling off the end of a function also
returns None.
● The statement result.append(a) calls a method of the list object result. A
method is a function that ‘belongs’ to an object and is
named obj.methodname, where obj is some object (this may be an
expression), and methodname is the name of a method that is defined by the
object’s type. Different types define different methods. Methods of different
types may have the same name without causing ambiguity. (It is possible to
define your own object types and methods, using classes, see Classes) The
method append () shown in the example is defined for list objects; it adds a
new element at the end of the list. In this example it is equivalent
to result = result + [a], but more efficient.
Data Structures
Data structures are the fundamental constructs around which you build your
programs. Each data structure provides a particular way of organizing data so it can
be accessed efficiently, depending on your use case. Python ships with an extensive
set of data structures in its standard library.
1.List:
● The list data type has some more methods. Here are all of the methods of list
objects:
● list.append(x)
● Add an item to the end of the list. Equivalent to a[len(a):] = [x].
● list.extend(iterable)
● Extend the list by appending all the items from the iterable. Equivalent
to a[len(a):] = iterable.
● list.insert(i, x)
● Insert an item at a given position. The first argument is the index of the
element before which to insert, so a.insert(0, x) inserts at the front of the list,
and a.insert(len(a), x) is equivalent to a.append(x).
● list.remove(x)
● Remove the first item from the list whose value is equal to x. It raises
a ValueError if there is no such item.
● list.pop([i])
● Remove the item at the given position in the list, and return it. If no index is
specified, a.pop() removes and returns the last item in the list. (The square
brackets around the i in the method signature denote that the parameter is
optional, not that you should type square brackets at that position. You will
see this notation frequently in the Python Library Reference.)
● list.clear()
● Remove all items from the list. Equivalent to del a[:].
● list.index(x[, start[, end]])
● Return zero-based index in the list of the first item whose value is equal to x.
Raises a ValueError if there is no such item.
● The optional arguments start and end are interpreted as in the slice notation
and are used to limit the search to a particular subsequence of the list. The
returned index is computed relative to the beginning of the full sequence
rather than the start argument.
● list.count(x)
● Return the number of times x appears in the list.
● list.sort(*, key=None, reverse=False)
● Sort the items of the list in place (the arguments can be used for sort
customization, see sorted() for their explanation).
● list.reverse()
● Reverse the elements of the list in place.
● list.copy()
● Return a shallow copy of the list. Equivalent to a[:].
● An example that uses most of the list methods:
There is a way to remove an item from a list given its index instead of its value:
the del statement. This differs from the pop() method which returns a value.
The del statement can also be used to remove slices from a list or clear the entire list
(which we did earlier by assignment of an empty list to the slice). For example:
>>>
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
>>>
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
As you see, on output tuples are always enclosed in parentheses, so that nested
tuples are interpreted correctly; they may be input with or without surrounding
parentheses, although often parentheses are necessary anyway (if the tuple is part
of a larger expression). It is not possible to assign to the individual items of a tuple,
however it is possible to create tuples which contain mutable objects, such as lists.
4. Sets
Python also includes a data type for sets. A set is an unordered collection with no
duplicate elements. Basic uses include membership testing and eliminating duplicate
entries. Set objects also support mathematical operations like union, intersection,
difference, and symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an
empty set you have to use set(), not {}; the latter creates an empty dictionary, a data
structure that we discuss in the next section.
>>>
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
5. Dictionaries
Another useful data type built into Python is the dictionary (see Mapping Types —
dict). Dictionaries are sometimes found in other languages as “associative
memories” or “associative arrays”. Unlike sequences, which are indexed by a range
of numbers, dictionaries are indexed by keys, which can be any immutable type;
strings and numbers can always be keys. Tuples can be used as keys if they contain
only strings, numbers, or tuples; if a tuple contains any mutable object either directly
or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be
modified in place using index assignments, slice assignments, or methods
like append() and extend().
It is best to think of a dictionary as a set of key: value pairs, with the requirement that
the keys are unique (within one dictionary). A pair of braces creates an empty
dictionary: {}. Placing a comma-separated list of key:value pairs within the braces
adds initial key:value pairs to the dictionary; this is also the way dictionaries are
written on output.
The main operations on a dictionary are storing a value with some key and extracting
the value given the key. It is also possible to delete a key:value pair with del. If you
store using a key that is already in use, the old value associated with that key is
forgotten. It is an error to extract a value using a non-existent key.
Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in
insertion order (if you want it sorted, just use sorted(d) instead). To check whether a
single key is in the dictionary, use the in keyword.
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
When the keys are simple strings, it is sometimes easier to specify pairs using
keyword arguments:
6. Looping Techniques
When looping through dictionaries, the key and corresponding value can be retrieved
at the same time using the items() method.
When looping through a sequence, the position index and corresponding value can
be retrieved at the same time using the enumerate() function.
To loop over two or more sequences at the same time, the entries can be paired with
the zip() function.
To loop over a sequence in reverse, first specify the sequence in a forward direction
and then call the reversed() function.
To loop over a sequence in sorted order, use the sorted() function which returns a
new sorted list while leaving the source unaltered.
It is sometimes tempting to change a list while you are looping over it; however, it is
often simpler and safer to create a new list instead.
Modules
If you quit from the Python interpreter and enter it again, the definitions you have
made (functions and variables) are lost. Therefore, if you want to write a somewhat
longer program, you are better off using a text editor to prepare the input for the
interpreter and running it with that file as input instead. This is known as creating
a script. As your program gets longer, you may want to split it into several files for
easier maintenance. You may also want to use a handy function that you’ve written
in several programs without copying its definition into each program.
To support this, Python has a way to put definitions in a file and use them in a script
or in an interactive instance of the interpreter. Such a file is called a module;
definitions from a module can be imported into other modules or into
the main module (the collection of variables that you have access to in a script
executed at the top level and in calculator mode).
A module is a file containing Python definitions and statements. The file name is the
module name with the suffix .py appended. Within a module, the module’s name (as
a string) is available as the value of the global variable __name__. For instance, use
your favorite text editor to create a file called fibo.py in the current directory with the
following contents:
Now enter the Python interpreter and import this module with the following
command:
This does not enter the names of the functions defined in fibo directly in the current
symbol table; it only enters the module name fibo there. Using the module name you
can access the functions:
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
If you intend to use a function often you can assign it to a local name:
There is a variant of the import statement that imports names from a module directly
into the importing module’s symbol table. For example:
>>>
>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in the
local symbol table (so in the example, fibo is not defined).
the code in the module will be executed, just as if you imported it, but with
the __name__ set to "__main__". That means that by adding this code at the end of
your module:
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
you can make the file usable as a script as well as an importable module, because
the code that parses the command line only runs if the module is executed as the
“main” file:
$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34
This is often used either to provide a convenient user interface to a module, or for
testing purposes (running the module as a script executes a test suite).
When a module named spam is imported, the interpreter first searches for a built-in
module with that name. If not found, it then searches for a file named spam.py in a
list of directories given by the variable sys.path. sys.path is initialized from these
locations:
● The directory containing the input script (or the current directory when no file
is specified).
● PYTHONPATH (a list of directory names, with the same syntax as the shell
variable PATH).
● The installation-dependent default.
Standard Modules
These two variables are only defined if the interpreter is in interactive mode.
The variable sys.path is a list of strings that determines the interpreter’s search path
for modules. It is initialized to a default path taken from the environment
variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You
can modify it using standard list operations:
The built-in function dir() is used to find out which names a module defines. It returns
a sorted list of strings:
>>>
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',
'__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
'__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',
'_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',
'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',
'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',
'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',
'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',
'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',
'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',
'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix',
'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr',
'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info',
'warnoptions']
Without arguments, dir() lists the names you have defined currently:
>>>
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
Note that it lists all types of names: variables, modules, functions, etc.
dir() does not list the names of built-in functions and variables.
Packages
Users of the package can import individual modules from the package, for example:
import sound.effects.echo
This loads the submodule sound.effects.echo. It must be referenced with its full
name.
This also loads the submodule echo, and makes it available without its package
prefix, so it can be used as follows:
Sometimes a developer might want to take input from the user at some point in the
program. To do this Python provides an input() function.
Syntax:
input('prompt')
where, prompt is a string that is displayed on the string at the time of taking input.