Learn Scripting

Coding Knowledge Unveiled: Empower Yourself

Python Control Flow

This tutorial will discuss how the python interpreter shares the processing among the source code. To prioritize the control python used below keywords to direct the control flow.

  • 1. if Statements
  • 2. for Statements
  • 3. The range() Function
  • 4. break and continue Statements, and else Clauses on Loops
  • 5. pass Statements
  • 6. Defining Functions
  • 7. More on Defining Functions
  • 7.1. Default Argument Values
  • 7.2. Keyword Arguments
  • 7.3. Arbitrary Argument Lists
  • 7.4. Unpacking Argument Lists
  • 7.5. Lambda Expressions
  • 7.6. Documentation Strings
  • 7.7. Function Annotations

1. if Statements

Perhaps the most well-known statement type is the if statement. For example:>>>

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More

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):>>>

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:>>>

>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over and over again.

3. The range() Function

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:>>>

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

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

range(-10, -100, -30)
  -10, -40, -70

To iterate over the indices of a sequence, you can combine range() and len() as follows:>>>

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques.

A strange thing happens if you just print a range:>>>

>>> 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 an iterator. The function list() is another; it creates lists from iterables:>>>

>>> list(range(5))
[0, 1, 2, 3, 4]

Later we will see more functions that return iterables and take iterables as argument.

4. break and continue Statements, and else Clauses on Loops

The break statement, like in C, breaks out of the innermost enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (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:>>>

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

(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 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:>>>

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

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:>>>

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...

This is commonly used for creating minimal classes:>>>

>>> class MyEmptyClass:
...     pass
...

Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:>>>

>>> def initlog(*args):
...     pass   # Remember to implement this!
...

6. Defining Functions

We can create a function that writes the Fibonacci series to an arbitrary boundary:>>>

>>> def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

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.

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables and variables of enclosing functions cannot be directly assigned a value within a function (unless, for global variables, named in a global statement, or, for variables of enclosing functions, named in a nonlocal statement), although they may be referenced.

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). 1 When a function calls another function, a new local symbol table is created for that call.

A function definition introduces the function name in the current symbol table. The value of the function name has a type that is recognized by the interpreter as a user-defined function. This value can be assigned to another name which can then also be used as a function. This serves as a general renaming mechanism:>>>

>>> 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:>>>

>>> def fib2(n):  # return Fibonacci series up to n
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    # see below
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)    # call it
>>> f100                # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

This example, as usual, demonstrates some new Python features:

  • 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.

7. More on Defining Functions

It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined.

7.1. Default Argument Values

The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

This function can be called in several ways:

  • giving only the mandatory argument: ask_ok('Do you really want to quit?')
  • giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)
  • or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.

The default values are evaluated at the point of function definition in the defining scope, so that

i = 5

def f(arg=i):
    print(arg)

i = 6
f()

will print 5.

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

This will print

[1]
[1, 2]
[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

7.2. Keyword Arguments

Functions can also be called using keyword arguments of the form kwarg=value. For instance, the following function:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

accepts one required argument (voltage) and three optional arguments (stateaction, and type). This function can be called in any of the following ways:

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

but all the following calls would be invalid:

parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
parrot(110, voltage=220)     # duplicate value for the same argument
parrot(actor='John Cleese')  # unknown keyword argument

In a function call, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for the parrot function), and their order is not important. This also includes non-optional arguments (e.g. parrot(voltage=1000) is valid too). No argument may receive a value more than once. Here’s an example that fails due to this restriction:>>>

>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for keyword argument 'a'

When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before **name.) For example, if we define a function like this:

def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

It could be called like this:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

and of course it would print:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

Note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call.

7.3. Arbitrary Argument Lists

Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.

def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))

Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments.>>>

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'

7.4. Unpacking Argument Lists

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the * operator to unpack the arguments out of a list or tuple:>>>

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

In the same fashion, dictionaries can deliver keyword arguments with the ** operator:>>>

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

7.5. Lambda Expressions

Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:>>>

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument:>>>

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

7.6. Documentation Strings

Here are some conventions about the content and formatting of documentation strings.

The first line should always be a short, concise summary of the object’s purpose. For brevity, it should not explicitly state the object’s name or type, since these are available by other means (except if the name happens to be a verb describing a function’s operation). This line should begin with a capital letter and end with a period.

If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.

The Python parser does not strip indentation from multi-line string literals in Python, so tools that process documentation have to strip indentation if desired. This is done using the following convention. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string. (We can’t use the first line since it is generally adjacent to the string’s opening quotes so its indentation is not apparent in the string literal.) Whitespace “equivalent” to this indentation is then stripped from the start of all lines of the string. Lines that are indented less should not occur, but if they occur all their leading whitespace should be stripped. Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces, normally).

Here is an example of a multi-line docstring:>>>

>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.

    No, really, it doesn't do anything.

7.7. Function Annotations

Function annotations are completely optional metadata information about the types used by user-defined functions (see PEP 3107 and PEP 484 for more information).

Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal ->, followed by an expression, between the parameter list and the colon denoting the end of the def statement. The following example has a positional argument, a keyword argument, and the return value annotated:>>>

>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'

Python Naming Convention Rules

1. General

  • Avoid using names that are too general or too wordy. Strike a good balance between the two.
  • Bad: data_structure, my_list, info_map, dictionary_for_the_purpose_of_storing_data_representing_word_definitions
  • Good: user_profile, menu_options, word_definitions
  • Don’t be a jackass and name things “O”, “l”, or “I”
  • When using CamelCase names, capitalize all letters of an abbreviation (e.g. HTTPServer)

2. Packages

  • Package names should be all lower case
  • When multiple words are needed, an underscore should separate them
  • It is usually preferable to stick to 1 word names

3. Modules

  • Module names should be all lower case
  • When multiple words are needed, an underscore should separate them
  • It is usually preferable to stick to 1 word names

4. Classes

  • Class names should follow the UpperCaseCamelCase convention
  • Python’s built-in classes, however are typically lowercase words
  • Exception classes should end in “Error”

5. Global (module-level) Variables

  • Global variables should be all lowercase
  • Words in a global variable name should be separated by an underscore

6. Instance Variables

  • Instance variable names should be all lower case
  • Words in an instance variable name should be separated by an underscore
  • Non-public instance variables should begin with a single underscore
  • If an instance name needs to be mangled, two underscores may begin its name

7. Methods

  • Method names should be all lower case
  • Words in an method name should be separated by an underscore
  • Non-public method should begin with a single underscore
  • If a method name needs to be mangled, two underscores may begin its name

8. Method Arguments

  • Instance methods should have their first argument named ‘self’.
  • Class methods should have their first argument named ‘cls’

9. Functions

  • Function names should be all lower case
  • Words in a function name should be separated by an underscore

10. Constants

  • Constant names must be fully capitalized
  • Words in a constant name should be separated by an underscore

Learn Numpy

Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data.

Numpy Array

Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array.A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists.

Creating a Numpy Array
Arrays in Numpy can be created by multiple ways, with various number of Ranks, defining the size of the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc. The type of the resultant array is deduced from the type of the elements in the sequences.

Below are some of the basic numpy functions available for the mathematical operation on the data.

1.np.array
2.np.shape
3.np.zeros
4.np.empty
5np.eye

1.np.array(list)-To convert the python list to numpy array.

numpy.array(objectdtype=Nonecopy=Trueorder=’K’subok=Falsendmin=0)

Create an array.

Parameters:object : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtypeorder, etc.). order : {‘K’, ‘A’, ‘C’, ‘F’}, optional Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order (column major). If object is an array the following holds. order no copy copy=True ‘K’ unchanged F & C order preserved, otherwise most similar order ‘A’ unchanged F order if input is F and not C, otherwise C order ‘C’ C order C order ‘F’ F order F order When copy=False and a copy is made for other reasons, the result is the same as if copy=True, with some exceptions for A, see the Notes section. The default order is ‘K’. subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). ndmin : int, optional Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.
Returns:out : ndarray An array object satisfying the specified requirements.

Below Example of creating numpy array from the single list

import numpy as np
ls=[1,2,34,5]
print("Type of ls=",type(ls))
np_arr=np.array(ls)
print("Printing Numpy Array:",np_arr)
print("Type of numpy Array",type(np_arr))
print("Dimension of numpy array",np_arr.ndim)

Output

“C:\Python 37\python.exe” C:/Users/shakdas/PycharmProjects/untitled/NumpyTest/Sample1.py
Type of ls=
Printing Numpy Array: [ 1 2 34 5]
Type of numpy Array
Dimension of numpy array 1

Process finished with exit code 0

Below Example of creating numpy array form the multiple list

import numpy as np
ls=[1,2,34,5]
ls1=[6,7,8,9]
ls2=[ls,ls1]
print("Type of ls=",type(ls2))
np_arr=np.array(ls2)
print("Printing Numpy Array:",np_arr)
print("Type of numpy Array",type(np_arr))
print("Dimension of numpy array",np_arr.ndim)

Output

“C:\Python 37\python.exe” C:/Users/shakdas/PycharmProjects/untitled/NumpyTest/Sample1.py
Type of ls=
Printing Numpy Array: [[ 1 2 34 5]
[ 6 7 8 9]]
Type of numpy Array
Dimension of numpy array 2

Process finished with exit code 0

2. ndarray.shape

Tuple of array dimensions.

The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required.

See alsonumpy.reshape similar function ndarray.reshape similar method

import numpy as np
ls=[1,2,34,5]
ls1=[6,7,8,9]
ls2=[ls,ls1]
np_arr=np.array(ls2)
print("Shape of Numpy Array",np_arr.shape)

Output

“C:\Python 37\python.exe” C:/Users/shakdas/PycharmProjects/untitled/NumpyTest/Sample1.py
Shape of Numpy Array (2, 4)

Process finished with exit code 0

3. numpy.zeros (shapedtype=floatorder=’C’)

Return a new array of given shape and type, filled with zeros.

Parameters:shape : int or tuple of ints Shape of the new array, e.g., (2, 3) or 2dtype : data-type, optional The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64order : {‘C’, ‘F’}, optional, default: ‘C’ Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.
Returns:out : ndarray Array of zeros with the given shape, dtype, and order.
import numpy as np
np_arr=np.zeros(5)
print(np_arr)
print("Type of numpy array:",np_arr.dtype)
print("Shape of Numpy Array",np_arr.shape)

Output

“C:\Python 37\python.exe” C:/Users/shakdas/PycharmProjects/untitled/NumpyTest/Sample1.py
[0. 0. 0. 0. 0.]
Type of numpy array float64
Shape of Numpy Array (5,)

Process finished with exit code 0

4.numpy.empty(shapedtype=floatorder=’C’)

Return a new array of given shape and type, without initializing entries.

Parameters:shape : int or tuple of int Shape of the empty array, e.g., (2, 3) or 2dtype : data-type, optional Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64order : {‘C’, ‘F’}, optional, default: ‘C’ Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.
Returns:out : ndarray Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

5.numpy.eye (NM=Nonek=0dtype=<class ‘float’>order=’C’)

Return a 2-D array with ones on the diagonal and zeros elsewhere.

Parameters:N : int Number of rows in the output. M : int, optional Number of columns in the output. If None, defaults to Nk : int, optional Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype : data-type, optional Data-type of the returned array. order : {‘C’, ‘F’}, optional Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory. New in version 1.14.0.
Returns:I : ndarray of shape (N,M) An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.
import numpy as np
np_arr=np.eye(5)
print(np_arr)
print("Type of numpy array:",np_arr.dtype)
print("Shape of Numpy Array:",np_arr.shape)

Output
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
Type of numpy array: float64
Shape of Numpy Array: (5, 5)

Numpy Mathematical Functions

Adding two numpy array

Adding two numpy array is as simple as adding two matrixes by adding the corresponding positions of the elements.

a=np.array([[2,5,6,4],[4,3,3,4]])
print (a)
print ("---------------------------------")
print (a+a)
[[2 5 6 4]
 [4 3 3 4]]
---------------------------------
[[ 4 10 12  8]
 [ 8  6  6  8]]

Substracting two numpy array

import numpy as np
a=np.array([[2,5,6,4],[4,3,3,4]])
b=np.array([[2,4,5,6],[4,5,6,7]])
print (a)
print ("---------------------------------")
print (b)
print ("---------------------------------")
print (a-b)
[[2 5 6 4]
 [4 3 3 4]]
---------------------------------
[[2 4 5 6]
 [4 5 6 7]]
---------------------------------
[[ 0  1  1 -2]
 [ 0 -2 -3 -3]]

Multiplying two numpy array

import numpy as np
a=np.array([[2,5,6,4],[4,3,3,4]])
b=np.array([[2,4,5,6],[4,5,6,7]])
print (a)
print ("---------------------------------")
print (b)
print ("---------------------------------")
print (a*b)
[[2 5 6 4]
 [4 3 3 4]]
---------------------------------
[[2 4 5 6]
 [4 5 6 7]]
---------------------------------
[[ 4 20 30 24]
 [16 15 18 28]]

Dividing two numpy array

import numpy as np
a=np.array([[2,5,6,4],[4,3,3,4]])
b=np.array([[2,4,5,6],[4,5,6,7]])
print (a)
print ("---------------------------------")
print (b)
print ("---------------------------------")
print (a/b)
[[2 5 6 4]
 [4 3 3 4]]
---------------------------------
[[2 4 5 6]
 [4 5 6 7]]
---------------------------------
[[1.         1.25       1.2        0.66666667]
 [1.         0.6        0.5        0.57142857]]

Powring numpy array

import numpy as np
a=np.array([[2,5,6,4],[4,3,3,4]])
b=np.array([[2,4,5,6],[4,5,6,7]])
print (a)
print ("---------------------------------")
print (a**2)
print ("---------------------------------")
print (a**3)
[[2 5 6 4]
 [4 3 3 4]]
---------------------------------
[[ 4 25 36 16]
 [16  9  9 16]]
---------------------------------
[[  8 125 216  64]
 [ 64  27  27  64]]

numpy.arange

numpy.arange([start, ]stop, [step, ]dtype=None)

Return evenly spaced values within a given interval.

Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments, the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list.

When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases.

Parameters:start : number, optionalStart of interval. The interval includes this value. The default start value is 0.stop : numberEnd of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.step : number, optionalSpacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given.dtype : dtypeThe type of the output array. If dtype is not given, infer the data type from the other input arguments.
Returns:arange : ndarrayArray of evenly spaced values.For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.
import numpy as np
a=np.arange(0,11)
print (a)
a=np.arange(0,11,2)
print (a)
[ 0  1  2  3  4  5  6  7  8  9 10]
[ 0  2  4  6  8 10]

Unix / Linux – Shell Basic Operators

There are various operators supported by each shell. We will discuss in detail about Bourne shell (default shell) in this chapter.According to the operation performed on the operators it has been classified into the below types.

We will now discuss the following operators −

  • Arithmetic Operators
  • Relational Operators
  • Boolean Operators
  • String Operators
  • File Test Operators

Bourne shell didn’t originally have any mechanism to perform simple arithmetic operations but it uses external programs, either awk or expr.

The following example shows how to add two numbers − 

#!/bin/sh

val=`expr 2 + 2`
echo "Total value : $val"

The above script will generate the following result −

Total value : 4

The following points need to be considered while adding −

  • There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2.
  • The complete expression should be enclosed between ‘ ‘, called the backtick.

Arithmetic Operators

The following arithmetic operators are supported by Bourne Shell.

Assume variable a holds 10 and variable b holds 20 then −

OperatorDescriptionExample
+ (Addition)Adds values on either side of the operator`expr $a + $b` will give 30
– (Subtraction)Subtracts right hand operand from left hand operand`expr $a – $b` will give -10
* (Multiplication)Multiplies values on either side of the operator`expr $a \* $b` will give 200
/ (Division)Divides left hand operand by right hand operand`expr $b / $a` will give 2
% (Modulus)Divides left hand operand by right hand operand and returns remainder`expr $b % $a` will give 0
= (Assignment)Assigns right operand in left operanda = $b would assign value of b into a
== (Equality)Compares two numbers, if both are same then returns true.[ $a == $b ] would return false.
!= (Not Equality)Compares two numbers, if both are different then returns true.[ $a != $b ] would return true.

It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect.

All the arithmetical calculations are done using long integers.

Relational Operators

Bourne Shell supports the following relational operators that are specific to numeric values. These operators do not work for string values unless their value is numeric.

For example, following operators will work to check a relation between 10 and 20 as well as in between “10” and “20” but not in between “ten” and “twenty”.

Assume variable a holds 10 and variable b holds 20 then −

OperatorDescriptionExample
-eqChecks if the value of two operands are equal or not; if yes, then the condition becomes true.[ $a -eq $b ] is not true.
-neChecks if the value of two operands are equal or not; if values are not equal, then the condition becomes true.[ $a -ne $b ] is true.
-gtChecks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true.[ $a -gt $b ] is not true.
-ltChecks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true.[ $a -lt $b ] is true.
-geChecks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true.[ $a -ge $b ] is not true.
-leChecks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true.[ $a -le $b ] is true.

It is very important to understand that all the conditional expressions should be placed inside square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is incorrect.

Boolean Operators

The following Boolean operators are supported by the Bourne Shell.

Assume variable a holds 10 and variable b holds 20 then −

OperatorDescriptionExample
!This is logical negation. This inverts a true condition into false and vice versa.[ ! false ] is true.
-oThis is logical OR. If one of the operands is true, then the condition becomes true.[ $a -lt 20 -o $b -gt 100 ] is true.
-aThis is logical AND. If both the operands are true, then the condition becomes true otherwise false.[ $a -lt 20 -a $b -gt 100 ] is false.

String Operators

The following string operators are supported by Bourne Shell.

Assume variable a holds “abc” and variable b holds “efg” then −

OperatorDescriptionExample
=Checks if the value of two operands are equal or not; if yes, then the condition becomes true.[ $a = $b ] is not true.
!=Checks if the value of two operands are equal or not; if values are not equal then the condition becomes true.[ $a != $b ] is true.
-zChecks if the given string operand size is zero; if it is zero length, then it returns true.[ -z $a ] is not true.
-nChecks if the given string operand size is non-zero; if it is nonzero length, then it returns true.[ -n $a ] is not false.
strChecks if str is not the empty string; if it is empty, then it returns false.[ $a ] is not false.

File Test Operators

We have a few operators that can be used to test various properties associated with a Unix file.

Assume a variable file holds an existing file name “test” the size of which is 100 bytes and has readwrite and execute permission on −

OperatorDescriptionExample
-b fileChecks if file is a block special file; if yes, then the condition becomes true.[ -b $file ] is false.
-c fileChecks if file is a character special file; if yes, then the condition becomes true.[ -c $file ] is false.
-d fileChecks if file is a directory; if yes, then the condition becomes true.[ -d $file ] is not true.
-f fileChecks if file is an ordinary file as opposed to a directory or special file; if yes, then the condition becomes true.[ -f $file ] is true.
-g fileChecks if file has its set group ID (SGID) bit set; if yes, then the condition becomes true.[ -g $file ] is false.
-k fileChecks if file has its sticky bit set; if yes, then the condition becomes true.[ -k $file ] is false.
-p fileChecks if file is a named pipe; if yes, then the condition becomes true.[ -p $file ] is false.
-t fileChecks if file descriptor is open and associated with a terminal; if yes, then the condition becomes true.[ -t $file ] is false.
-u fileChecks if file has its Set User ID (SUID) bit set; if yes, then the condition becomes true.[ -u $file ] is false.
-r fileChecks if file is readable; if yes, then the condition becomes true.[ -r $file ] is true.
-w fileChecks if file is writable; if yes, then the condition becomes true.[ -w $file ] is true.
-x fileChecks if file is executable; if yes, then the condition becomes true.[ -x $file ] is true.
-s fileChecks if file has size greater than 0; if yes, then condition becomes true.[ -s $file ] is true.
-e fileChecks if file exists; is true even if file is a directory but exists.[ -e $file ] is true.

Python Operator – Types of Operators in Python

Being a high level language where it can fit into most of the system it has the capability to handle the all data types.To handle this data the operators are categorized into below 7 categories .

  • Python Arithmetic Operator
  • Python Relational Operator
  • Python Assignment Operator
  • Python Logical Operator
  • Python Membership Operator
  • Python Identity Operator
  • Python Bitwise Operator

Python Arithmetic Operator

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.

OperatorMeaningExample
+Add two operands or unary plusx + y
+2
Subtract right operand from the left or unary minusx – y
-2
*Multiply two operandsx * y
/Divide left operand by the right one (always results into float)x / y
%Modulus – remainder of the division of left operand by the rightx % y (remainder of x/y)
//Floor division – division that results into whole number adjusted to the left in the number linex // y
**Exponent – left operand raised to the power of rightx**y (x to the power y)

Python Relational Operator

Relational operators are used to compare values. It either returns True or False according to the condition.

OperatorMeaningExample
>Greater that – True if left operand is greater than the rightx > y
<Less that – True if left operand is less than the rightx < y
==Equal to – True if both operands are equalx == y
!=Not equal to – True if operands are not equalx != y
>=Greater than or equal to – True if left operand is greater than or equal to the rightx >= y
<=Less than or equal to – True if left operand is less than or equal to the rightx <= y

Python Assignment Operator

Assignment operators are used in Python to assign values to variables.

a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.

There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.

OperatorExampleEquivatent to
=x = 5x = 5
+=x += 5x = x + 5
-=x -= 5x = x – 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5
//=x //= 5x = x // 5
**=x **= 5x = x ** 5
&=x &= 5x = x & 5
|=x |= 5x = x | 5
^=x ^= 5x = x ^ 5
>>=x >>= 5x = x >> 5
<<=x <<= 5x = x << 5

Python Logical Operator

Logical operators are the andornot operators.

OperatorMeaningExample
andTrue if both the operands are truex and y
orTrue if either of the operands is truex or y
notTrue if operand is false (complements the operand)not x

Python Membership Operator

in and not in are the membership operators in Python. They are used to test whether a value or variable is found in a sequence (stringlisttupleset and dictionary).

In a dictionary we can only test for presence of key, not the value.

OperatorMeaningExample
inTrue if value/variable is found in the sequence5 in x
not inTrue if value/variable is not found in the sequence5 not in x

Python Identity Operator

is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical.

OperatorMeaningExample
isTrue if the operands are identical (refer to the same object)x is True
is notTrue if the operands are not identical (do not refer to the same object)x is not True

Python Bitwise Operator

Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

OperatorMeaningExample
&Bitwise ANDx& y = 0 (0000 0000)
|Bitwise ORx | y = 14 (0000 1110)
~Bitwise NOT~x = -11 (1111 0101)
^Bitwise XORx ^ y = 14 (0000 1110)
>>Bitwise right shiftx>> 2 = 2 (0000 0010)
<<Bitwise left shiftx<< 2 = 40 (0010 1000)

Creating Virtual Environment in Python using Command Line Arguments

Installing packages using pip In virtualenv

This guide discusses how to install packages using pip and virtualenv. These are the lowest-level tools for managing Python packages and are recommended if higher-level tools do not suit your needs.

Note

This doc uses the term package to refer to a Distribution Package which is different from a Import Package that which is used to import modules in your Python source code.

Installing pip

pip is the reference Python package manager. It’s used to install and update packages. You’ll need to make sure you have the latest version of pip installed.

Windows

The Python installers for Windows include pip. You should be able to access pip using:

py -m pip --version
pip 9.0.1 from c:\python36\lib\site-packages (Python 3.6.1)

You can make sure that pip is up-to-date by running:

py -m pip install --upgrade pip

Linux and macOS

Debian and most other distributions include a python-pip package, if you want to use the Linux distribution-provided versions of pip see Installing pip/setuptools/wheel with Linux Package Managers.

You can also install pip yourself to ensure you have the latest version. It’s recommended to use the system pip to bootstrap a user installation of pip:

python3 -m pip install --user --upgrade pip

Afterwards, you should have the newest pip installed in your user site:

python3 -m pip --version
pip 9.0.1 from $HOME/.local/lib/python3.6/site-packages (python 3.6)

Installing virtualenv

virtualenv is used to manage Python packages for different projects. Using virtualenv allows you to avoid installing Python packages globally which could break system tools or other projects. You can install virtualenv using pip.

On macOS and Linux:

python3 -m pip install --user virtualenv

On Windows:

py -m pip install --user virtualenv

Note

If you are using Python 3.3 or newer the venv module is included in the Python standard library. This can also create and manage virtual environments, however, it only supports Python 3.

Creating a virtualenv

virtualenv allows you to manage separate package installations for different projects. It essentially allows you to create a “virtual” isolated Python installation and install packages into that virtual installation. When you switch projects, you can simply create a new virtual environment and not have to worry about breaking the packages installed in the other environments. It is always recommended to use a virtualenv while developing Python applications.

To create a virtual environment, go to your project’s directory and run virtualenv.

On macOS and Linux:

python3 -m virtualenv env

On Windows:

py -m virtualenv env

The second argument is the location to create the virtualenv. Generally, you can just create this in your project and call it env.

virtualenv will create a virtual Python installation in the env folder.

Note

You should exclude your virtualenv directory from your version control system using .gitignore or similar.

Activating a virtualenv

Before you can start installing or using packages in your virtualenv you’ll need to activate it. Activating a virtualenv will put the virtualenv-specific python and pip executables into your shell’s PATH.

On macOS and Linux:

source env/bin/activate

On Windows:

.\env\Scripts\activate

You can confirm you’re in the virtualenv by checking the location of your Python interpreter, it should point to the env directory.

On macOS and Linux:

which python
.../env/bin/python

On Windows:

where python
.../env/bin/python.exe

As long as your virtualenv is activated pip will install packages into that specific environment and you’ll be able to import and use packages in your Python application.

Leaving the virtualenv

If you want to switch projects or otherwise leave your virtualenv, simply run:

deactivate

If you want to re-enter the virtualenv just follow the same instructions above about activating a virtualenv. There’s no need to re-create the virtualenv.

Installing packages

Now that you’re in your virtualenv you can install packages. Let’s install the excellent Requests library from the Python Package Index (PyPI):

pip install requests

pip should download requests and all of its dependencies and install them:

Collecting requests
  Using cached requests-2.18.4-py2.py3-none-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Using cached chardet-3.0.4-py2.py3-none-any.whl
Collecting urllib3<1.23,>=1.21.1 (from requests)
  Using cached urllib3-1.22-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests)
  Using cached certifi-2017.7.27.1-py2.py3-none-any.whl
Collecting idna<2.7,>=2.5 (from requests)
  Using cached idna-2.6-py2.py3-none-any.whl
Installing collected packages: chardet, urllib3, certifi, idna, requests
Successfully installed certifi-2017.7.27.1 chardet-3.0.4 idna-2.6 requests-2.18.4 urllib3-1.22

Installing specific versions

pip allows you to specify which version of a package to install using version specifiers. For example, to install a specific version of requests:

pip install requests==2.18.4

To install the latest 2.x release of requests:

pip install requests>=2.0.0,<3.0.0

To install pre-release versions of packages, use the --pre flag:

pip install --pre requests

Installing extras

Some packages have optional extras. You can tell pip to install these by specifying the extra in brackets:

pip install requests[security]

Installing from source

pip can install a package directly from source, for example:

cd google-auth
pip install .

Additionally, pip can install packages from source in development mode, meaning that changes to the source directory will immediately affect the installed package without needing to re-install:

pip install --editable .

Installing from version control systems

pip can install packages directly from their version control system. For example, you can install directly from a git repository:

git+https://github.com/GoogleCloudPlatform/google-auth-library-python.git#egg=google-auth

For more information on supported version control systems and syntax, see pip’s documentation on VCS Support.

Installing from local archives

If you have a local copy of a Distribution Package’s archive (a zip, wheel, or tar file) you can install it directly with pip:

pip install requests-2.18.4.tar.gz

If you have a directory containing archives of multiple packages, you can tell pip to look for packages there and not to use the Python Package Index (PyPI) at all:

pip install --no-index --find-links=/local/dir/ requests

This is useful if you are installing packages on a system with limited connectivity or if you want to strictly control the origin of distribution packages.

Using other package indexes

If you want to download packages from a different index than the Python Package Index (PyPI), you can use the --index-url flag:

pip install --index-url http://index.example.com/simple/ SomeProject

If you want to allow packages from both the Python Package Index (PyPI) and a separate index, you can use the --extra-index-url flag instead:

pip install --extra-index-url http://index.example.com/simple/ SomeProject

Upgrading packages

pip can upgrade packages in-place using the --upgrade flag. For example, to install the latest version of requests and all of its dependencies:

pip install --upgrade requests

Using requirements files

Instead of installing packages individually, pip allows you to declare all dependencies in a Requirements File. For example you could create a requirements.txt file containing:

requests==2.18.4
google-auth==1.1.0

And tell pip to install all of the packages in this file using the -r flag:

pip install -r requirements.txt

Freezing dependencies

Pip can export a list of all installed packages and their versions using the freeze command:

pip freeze

Which will output a list of package specifiers such as:

cachetools==2.0.1
certifi==2017.7.27.1
chardet==3.0.4
google-auth==1.1.1
idna==2.6
pyasn1==0.3.6
pyasn1-modules==0.1.4
requests==2.18.4
rsa==3.4.2
six==1.11.0
urllib3==1.22

This is useful for creating Requirements Files that can re-create the exact versions of all packages installed in an environment.

What is Lambda, Filter, Reduce,Map & List Comprehension,Set Comprehension in Python

Although we all know that in python def(): is used to create a function,We can use a def() as er our requirement and modify accordingly.Sometimes its necessary to create a one line function known as Lambda.Which can be created by just in demand situation where it can  behave like an normal definition. We can see the result: lambda, map() and filter() are still part of core Python. Only reduce() had to go it is moved into the module functools.

  • There is an equally powerful alternative to lambda, filter, map and reduce, i.e. list comprehension
  • List comprehension is more evident and easier to understand
  • Having both list comprehension and “Filter, map, reduce and lambda” is transgressing the Python motto “There should be one obvious way to solve a problem”

Lambda

Some like it, others feels complicated lambda operator. The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce(). The lambda feature was added to Python due to the demand from Lisp programmers.

The general syntax of a lambda function is quite simple:

lambda argument_list: expression

The argument list consists of a comma separated list of arguments and the expression is an arithmetic expression using these arguments. You can assign the function to a variable to give it a name.

The following example of a lambda function returns the average of its two arguments:

xx=lambda y:y*5
print(xx(55))

The above example might look like a plaything for a mathematician. A formalism which turns an easy to comprehend issue into an abstract harder to grasp formalism. Above all, we could have had the same effect by just using the following conventional function definition:

def xx(y):
    return y*5
print(xx(55))

We can assure you that the advantages of this approach will be apparent, when you will have learnt to use the map() function.

Lambda with if condition

The map() Function

The lambda operator can be seen when it is used in combination with the map() function.The map() is a function which takes two arguments the first one is the function and second one on which it needs to map the function.

r = map(func, seq)

The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. Before Python3, map() used to return a list, where each element of the result list was the result of the function func applied on the corresponding element of the list or tuple “seq”. With Python 3, map() returns an iterator.

In the below example we are calculating the total travel cost.Our distance=[30,50,80,12,90,40,60,20] list contain the number of distances.We are calculating the distance by car and bike and storing inside the respective list.We are using the lambda for creating inline function.And by using map we are mapping the function over the list of n elements.

distance=[30,50,80,12,90,40,60,20]
costByCar=[]
costByBike=[]
car=lambda x:x*4
costByCar=map(car,distance)
print(list(costByCar))
bike=lambda x:x*2
costByBike=map(bike,distance)
print(list(costByBike))

The below lines of code are the generic way of python definition to create a function and do same thing

def calcostByCar():
for i in distance:
#Per kilomeater i am considering 4$ as traveliing cost
costByCar.append(i*4)
calcostByCar()
print("Cost by car :",costByCar)
def calcostByBike():
for i in distance:
#Per kilomeater i am considering 2$ as traveliing cost
costByBike.append(i*2)
calcostByBike()
print("Cost by bike :",costByBike)

Output of the above program is as below.
[120, 200, 320, 48, 360, 160, 240, 80]
[60, 100, 160, 24, 180, 80, 120, 40]

Filtering

The function

filter(function, sequence)

offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function function returns True. i.e. an item will be produced by the iterator result of filter(function, sequence) if item is included in the sequence “sequence” and if function(item) returns True.

In other words: The function filter(f,l) needs a function f as its first argument. f has to return a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True will the element be produced by the iterator, which is the return value of filter(function, sequence).

In the following example, we filter out first the odd and then the even elements of the sequence of the first 11 Fibonacci numbers:

>>> fibonacci = [0,1,1,2,3,5,8,13,21,34,55]
>>> odd_numbers = list(filter(lambda x: x % 2, fibonacci))
>>> print(odd_numbers)
[1, 1, 3, 5, 13, 21, 55]
>>> even_numbers = list(filter(lambda x: x % 2 == 0, fibonacci))
>>> print(even_numbers)
[0, 2, 8, 34]
>>> 
>>> 
>>> # or alternatively:
... 
>>> even_numbers = list(filter(lambda x: x % 2 -1, fibonacci))
>>> print(even_numbers)
[0, 2, 8, 34]
>>> 

Reducing a List

As we mentioned in the introduction of this chapter of our tutorial. reduce() had been dropped from the core of Python when migrating to Python 3. Guido van Rossum hates reduce(), as we can learn from his statement in a posting, March 10, 2005, in artima.com:

“So now reduce(). This is actually the one I’ve always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what’s actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it’s better to write out the accumulation loop explicitly.”

The function

reduce(func, seq)

continually applies the function func() to the sequence seq. It returns a single value.

If seq = [ s1, s2, s3, … , sn ], calling reduce(func, seq) works like this:

  • At first the first two elements of seq will be applied to func, i.e. func(s1,s2) The list on which reduce() works looks now like this: [ func(s1, s2), s3, … , sn ]
  • In the next step func will be applied on the previous result and the third element of the list, i.e. func(func(s1, s2),s3)
    The list looks like this now: [ func(func(s1, s2),s3), … , sn ]
  • Continue like this until just one element is left and return this element as the result of reduce()

If n is equal to 4 the previous explanation can be illustrated like this: Reduce

We want to illustrate this way of working of reduce() with a simple example. We have to import functools to be capable of using reduce:

>>> import functools
>>> functools.reduce(lambda x,y: x+y, [47,11,42,13])
113
>>> 

The following diagram shows the intermediate steps of the calculation:

Reduce: Method of operating

Examples of reduce()

Determining the maximum of a list of numerical values by using reduce:

>>> from functools import reduce
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102
>>> 

Calculating the sum of the numbers from 1 to 100:

>>> from functools import reduce
>>> reduce(lambda x, y: x+y, range(1,101))
5050

It’s very simple to change the previous example to calculate the product (the factorial) from 1 to a number, but do not choose 100. We just have to turn the “+” operator into “*”:

>>> reduce(lambda x, y: x*y, range(1,49))
12413915592536072670862289047373375038521486354677760000000000

If you are into lottery, here are the chances to win a 6 out of 49 drawing:

>>> reduce(lambda x, y: x*y, range(44,50))/reduce(lambda x, y: x*y, range(1,7))
13983816.0
>>> 

List Comprehension

Introduction

alternative to map, filter, reduce and lambda We learned  “Lambda Operator, Filter, Reduce and Map” that Guido van Rossum prefers list comprehensions to constructs using map, filter, reduce and lambda. In this chapter we will cover the essentials about list comprehensions. List comprehensions were added with Python 2.0. Essentially, it is Python’s way of implementing a well-known notation for sets as used by mathematicians.
In mathematics the square numbers of the natural numbers are, for example, created by { x2 | x ∈ ℕ } or the set of complex integers { (x,y) | x ∈ ℤ ∧ y ∈ ℤ }.

List comprehension is an elegant way to define and create list in Python. These lists have often the qualities of sets, but are not in all cases sets.

List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce(). For most people the syntax of list comprehension is easier to be grasped.

Examples

In the chapter on lambda and map() we had designed a map() function to convert Celsius values into Fahrenheit and vice versa. It looks like this with list comprehension:

>>> Celsius = [39.2, 36.5, 37.3, 37.8]
>>> Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ]
>>> print Fahrenheit
[102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999]
>>> 

The following list comprehension creates the Pythagorean triples:

>>> [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]
>>> 

Cross product of two sets:

>>> colours = [ "red", "green", "yellow", "blue" ]
>>> things = [ "house", "car", "tree" ]
>>> coloured_things = [ (x,y) for x in colours for y in things ]
>>> print coloured_things
[('red', 'house'), ('red', 'car'), ('red', 'tree'), ('green', 'house'), ('green', 'car'), ('green', 'tree'), ('yellow', 'house'), ('yellow', 'car'), ('yellow', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue', 'tree')]
>>> 

Generator Comprehension

Generator comprehensions were introduced with Python 2.6. They are simply a generator expression with a parenthesis – round brackets – around it. Otherwise, the syntax and the way of working is like list comprehension, but a generator comprehension returns a generator instead of a list.

>>> x = (x **2 for x in range(20))
>>> print(x)
 at 0xb7307aa4>
>>> x = list(x)
>>> print(x)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]

A more Demanding Example

Calculation of the prime numbers between 1 and 100 using the sieve of Eratosthenes:

>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 100, i)]
>>> primes = [x for x in range(2, 100) if x not in noprimes]
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> 

We want to bring the previous example into more general form, so that we can calculate the list of prime numbers up to an arbitrary number n:

>>> from math import sqrt
>>> n = 100
>>> sqrt_n = int(sqrt(n))
>>> no_primes = [j for i in range(2,sqrt_n) for j in range(i*2, n, i)]

If we have a look at the content of no_primes, we can see that we have a problem. There are lots of double entries contained in this list:

>>> no_primes
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99]
>>>

The solution to this intolerable problem comes with the set comprehension, which we will cover in the next section.

Set Comprehension

A set comprehension is similar to a list comprehension, but returns a set and not a list. Syntactically, we use curly brackets instead of square brackets to create a set. Set comprehension is the right functionality to solve our problem from the previous subsection. We are able to create the set of non primes without doublets:

>>> from math import sqrt
>>> n = 100
>>> sqrt_n = int(sqrt(n))
>>> no_primes = {j for i in range(2,sqrt_n) for j in range(i*2, n, i)}
>>> no_primes
{4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99}
>>> primes = {i for i in range(n) if i not in no_primes}
>>> print(primes)
{0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
>>> 

Recursive Function to Calculate the Primes

The following Python script uses a recursive function to calculate the prime numbers. It incorporates the fact that it is enough to examine the multiples of the prime numbers up to the square root of n:

from math import sqrt
def primes(n):
    if n == 0:
        return []
    elif n == 1:
        return []
    else:
        p = primes(int(sqrt(n)))
        no_p = {j for i in p for j in xrange(i*2, n+1, i)}
        p = {x for x in xrange(2, n + 1) if x not in no_p}
    return p

for i in range(1,50):
    print i, primes(i) 

Installation of Python Version(2.7/3.*) in Windows

[lwptoc min=”2″ depth=”6″ hierarchical=”1″ numeration=”decimalnested” numerationSuffix=”none” title=”Contents” toggle=”1″ labelShow=”show” labelHide=”hide” hideItems=”0″ smoothScroll=”1″ width=”auto”]

Installation of Python Version(2.7/3.*) is very easy because of it GUI Installer. Which made life simple for the programmer. For the installation of Python, we need to follow the below steps.

If you are a beginner in python before choosing the version you can go through the post The Difference Between Pyhton 2.x and Python 3.x

Step 1:Download Python According to System Processor 

Depending on your system processor you have chosen the appropriate exe file from the download page Link.

Step 2:Run the Package Installer & Setup the Python Executable Path

After downloading the python you need to install it in your system by double clicking it.During installation you need to setup few things without which you can face difficulties in future.

#Need to provide the installation path at the time of setup otherwise it will take the system default path.You have to create a folder named as PythonXX with post fix your version code. In my case i have created a folder Python37 for the python 3.7 version installation.As shown in the below image.

#Select Customize Installation.

#Add Pyhton 3.7 to PATH

#Check the options

Pip

tcl/tk

Python Test Suite

#Give the Python37 Folder Location which you have created at first step.

Step 3:Open Command and Check the Installation

Open you command prompt and Type python -v in your command prompt .Now you can able to see the pyhton version installed in your system.If you don’t find the  pyton version installed in your system you might have skip some step from above please reinstall pyhton with above prerequisite or you can setup your python path manually as provided in the step #4.

Step 4:Setting Up Python Path in the environment variable.

Go to your my computer->Properties->Advance System Setting ->Go to advance Tab->Click on Environmental Variable .

You will find two section where you need to give your python installation location as shown in the image.

If you still find difficulties please comment below with your error code.And please do not forget to give your comment.

Difference Between Pyhton 2.X Vs 3.X

The key differences between Python 2.7.x and Python 3.x with examples

Many beginning Python users are wondering with which version of Python they should start their career. Our answer to this question is usually something along the lines “just go with the version your favorite tutorial was written in, and check out the differences later on.”But what if you are starting a new project and have the choice to pick? I would say there is currently no “right” or “wrong” as long as both Python 2.7.x and Python 3.x support the libraries that you are planning to use. However, it is worthwhile to have a look at the major differences between those two most popular versions of Python to avoid common pitfalls when writing the code for either one of them, or if you are planning to port your project.

The Key Differences are as below

  1. The __future__ module in python 2
  2. The print function
    1. Python 2
    2. Python 3
  3. Integer division
    1. Python 2
    2. Python 3
  4. Unicode
    1. Python 2
    2. Python 3
  5. xrange
    1. Python 2
    2. Python 3
    3. The __contains__ method for range objects in Python 3
      1. Note about the speed differences in Python 2 and 3
  6. Raising exceptions
    1. Python 2
    2. Python 3
  7. Handling exceptions
    1. Python 2
    2. Python 3
  8. The next() function and .next() method
    1. Python 2
    2. Python 3
  9. For-loop variables and the global namespace leak
    1. Python 2
    2. Python 3
  10. Comparing unorderable types
    1. Python 2
    2. Python 3
  11. Parsing user inputs via input()
    1. Python 2
    2. Python 3
  12. Returning iterable objects instead of lists
    1. Python 2
    2. Python 3
  13. Banker’s Rounding
    1. Python 2
    2. Python 3
  14. More articles about Python 2 and Python 3

1.The __future__ module

Python 3.x introduced some Python 2-incompatible keywords and features that can be imported via the in-built __future__ module in Python 2. It is recommended to use __future__ imports it if you are planning Python 3.x support for your code. For example, if we want Python 3.x’s integer division behavior in Python 2, we can import it via the folowing syntax.

from __future__ import division

More features that can be imported from the __future__ module are listed in the table below:

feature optional in mandatory in effect
nested_scopes 2.1.0b1 2.2 PEP 227: Statically Nested Scopes
generators 2.2.0a1 2.3 PEP 255: Simple Generators
division 2.2.0a2 3.0 PEP 238: Changing the Division Operator
absolute_import 2.5.0a1 3.0 PEP 328: Imports: Multi-Line and Absolute/Relative
with_statement 2.5.0a1 2.6 PEP 343: The “with” Statement
print_function 2.6.0a2 3.0 PEP 3105: Make print a function
unicode_literals 2.6.0a2 3.0 PEP 3112: Bytes literals in Python 3000

(Source: [https://docs.python.org/2/library/__future__.html](https://docs.python.org/2/library/__future__.html#module-__future__))

from platform import python_version

2.The print function

This is an important change in the Pyhton from the 2 to 3, and the change in the print-syntax is probably the most widely known change, but still it is worth mentioning: Python 2’s print statement has been replaced by the print() function, meaning that we have to wrap the object that we want to print in parenthesis.

Python 2 doesn’t have a problem with additional parenthesis, but in contrast, Python 3 would raise a SyntaxError if we called the print function the Python 2-way without the parentheses.

Python 2

print 'Python', python_version()
print 'Hello, World!'
print('Hello, World!')
print "text", ; print 'print more text on the same line'
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

print('Python', python_version())
print('Hello, World!')

print("some text,", end="")
print(' print more text on the same line')
Python 3.4.1
Hello, World!
some text, print more text on the same line
print 'Hello, World!'
  File "<ipython-input-3-139a7c5835bd>", line 1
    print 'Hello, World!'
                        ^
SyntaxError: invalid syntax

Note:

Printing “Hello, World” above via Python 2 looked quite “normal”. However, if we have multiple objects inside the parantheses, we will create a tuple, since print is a “statement” in Python 2, not a function call.

print 'Python', python_version()
print('a', 'b')
print 'a', 'b'
Python 2.7.7
('a', 'b')
a b

3.Integer division

This change is particularly dangerous if you are porting code, or if you are executing Python 3 code in Python 2, since the change in integer-division behavior can often go unnoticed (it doesn’t raise a SyntaxError).
So, I still tend to use a float(3)/2 or 3/2.0 instead of a 3/2 in my Python 3 scripts to save the Python 2 guys some trouble (and vice versa, I recommend a from __future__ import division in your Python 2 scripts).

Python 2

print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Python 3

print('Python', python_version())
print('3 / 2 =', 3 / 2)
print('3 // 2 =', 3 // 2)
print('3 / 2.0 =', 3 / 2.0)
print('3 // 2.0 =', 3 // 2.0)
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

4.Unicode

Python 2 has ASCII str() types, separate unicode(), but no byte type.

Now, in Python 3, we finally have Unicode (utf-8) strings, and 2 byte classes: byte and bytearrays.

Python 2

print 'Python', python_version()
Python 2.7.6
print type(unicode('this is like a python3 str type'))
<type 'unicode'>
print type(b'byte type does not exist')
<type 'str'>
print 'they are really' + b' the same'
they are really the same
print type(bytearray(b'bytearray oddly does exist though'))
<type 'bytearray'>

Python 3

print('Python', python_version())
print('strings are now utf-8 \u03BCnico\u0394é!')
Python 3.4.1
strings are now utf-8 μnicoΔé!
print('Python', python_version(), end="")
print(' has', type(b' bytes for storing data'))
Python 3.4.1 has <class 'bytes'>
print('and Python', python_version(), end="")
print(' also has', type(bytearray(b'bytearrays')))
and Python 3.4.1 also has <class 'bytearray'>
'note that we cannot add a string' + b'bytes for data'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

<ipython-input-13-d3e8942ccf81> in <module>()
----> 1 'note that we cannot add a string' + b'bytes for data'


TypeError: Can't convert 'bytes' object to str implicitly

5.xrange

The usage of xrange() is very popular in Python 2.x for creating an iterable object, e.g., in a for-loop or list/set-dictionary-comprehension.
The behavior was quite similar to a generator (i.e., “lazy evaluation”), but here the xrange-iterable is not exhaustible – meaning, you could iterate over it infinitely.

Thanks to its “lazy-evaluation”, the advantage of the regular range() is that xrange() is generally faster if you have to iterate over it only once (e.g., in a for-loop). However, in contrast to 1-time iterations, it is not recommended if you repeat the iteration multiple times, since the generation happens every time from scratch!

In Python 3, the range() was implemented like the xrange() function so that a dedicated xrange() function does not exist anymore (xrange() raises a NameError in Python 3).

import timeit

n = 10000
def test_range(n):
    return for i in range(n):
        pass

def test_xrange(n):
    for i in xrange(n):
        pass    

Python 2

print 'Python', python_version()

print '\ntiming range()'
%timeit test_range(n)

print '\n\ntiming xrange()'
%timeit test_xrange(n)
Python 2.7.6

timing range()
1000 loops, best of 3: 433 µs per loop


timing xrange()
1000 loops, best of 3: 350 µs per loop

Python 3

print('Python', python_version())

print('\ntiming range()')
%timeit test_range(n)
Python 3.4.1

timing range()
1000 loops, best of 3: 520 µs per loop
print(xrange(10))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

<ipython-input-5-5d8f9b79ea70> in <module>()
----> 1 print(xrange(10))


NameError: name 'xrange' is not defined

6.The __contains__ method for range objects in Python 3

Another thing worth mentioning is that range got a “new” __contains__ method in Python 3.x (thanks to Yuchen Ying, who pointed this out). The __contains__ method can speedup “look-ups” in Python 3.x range significantly for integer and Boolean types.

x = 10000000
def val_in_range(x, val):
    return val in range(x)
def val_in_xrange(x, val):
    return val in xrange(x)
print('Python', python_version())
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_range(x, x/2)
%timeit val_in_range(x, x//2)
Python 3.4.1
1 loops, best of 3: 742 ms per loop
1000000 loops, best of 3: 1.19 µs per loop

Based on the timeit results above, you see that the execution for the “look up” was about 60,000 faster when it was of an integer type rather than a float. However, since Python 2.x’s range or xrange doesn’t have a __contains__ method, the “look-up speed” wouldn’t be that much different for integers or floats:

print 'Python', python_version()
assert(val_in_xrange(x, x/2.0) == True)
assert(val_in_xrange(x, x/2) == True)
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_xrange(x, x/2.0)
%timeit val_in_xrange(x, x/2)
%timeit val_in_range(x, x/2.0)
%timeit val_in_range(x, x/2)
Python 2.7.7
1 loops, best of 3: 285 ms per loop
1 loops, best of 3: 179 ms per loop
1 loops, best of 3: 658 ms per loop
1 loops, best of 3: 556 ms per loop

Below the “proofs” that the __contain__ method wasn’t added to Python 2.x yet:

print('Python', python_version())
range.__contains__
Python 3.4.1





<slot wrapper '__contains__' of 'range' objects>
print 'Python', python_version()
range.__contains__
Python 2.7.7



---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

<ipython-input-7-05327350dafb> in <module>()
      1 print 'Python', python_version()
----> 2 range.__contains__


AttributeError: 'builtin_function_or_method' object has no attribute '__contains__'
print 'Python', python_version()
xrange.__contains__
Python 2.7.7



---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

<ipython-input-8-7d1a71bfee8e> in <module>()
      1 print 'Python', python_version()
----> 2 xrange.__contains__


AttributeError: type object 'xrange' has no attribute '__contains__'

Note about the speed differences in Python 2 and 3

Some people pointed out the speed difference between Python 3’s range() and Python2’s xrange(). Since they are implemented the same way one would expect the same speed. However the difference here just comes from the fact that Python 3 generally tends to run slower than Python 2.

def test_while():
    i = 0
    while i < 20000:
        i += 1
    return
print('Python', python_version())
%timeit test_while()
Python 3.4.1
100 loops, best of 3: 2.68 ms per loop
print 'Python', python_version()
%timeit test_while()
Python 2.7.6
1000 loops, best of 3: 1.72 ms per loop

7.Raising exceptions

Where Python 2 accepts both notations, the ‘old’ and the ‘new’ syntax, Python 3 chokes (and raises a SyntaxError in turn) if we don’t enclose the exception argument in parentheses:

Python 2

print 'Python', python_version()
Python 2.7.6
raise IOError, "file error"
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)

<ipython-input-8-25f049caebb0> in <module>()
----> 1 raise IOError, "file error"


IOError: file error
raise IOError("file error")
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)

<ipython-input-9-6f1c43f525b2> in <module>()
----> 1 raise IOError("file error")


IOError: file error

Python 3

print('Python', python_version())
Python 3.4.1
raise IOError, "file error"
  File "<ipython-input-10-25f049caebb0>", line 1
    raise IOError, "file error"
                 ^
SyntaxError: invalid syntax

The proper way to raise an exception in Python 3:

print('Python', python_version())
raise IOError("file error")
Python 3.4.1



---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)

<ipython-input-11-c350544d15da> in <module>()
      1 print('Python', python_version())
----> 2 raise IOError("file error")


OSError: file error

8.Handling exceptions

Also the handling of exceptions has slightly changed in Python 3. In Python 3 we have to use the “as” keyword now

Python 2

print 'Python', python_version()
try:
    let_us_cause_a_NameError
except NameError, err:
    print err, '--> our error message'
Python 2.7.6
name 'let_us_cause_a_NameError' is not defined --> our error message

Python 3

print('Python', python_version())
try:
    let_us_cause_a_NameError
except NameError as err:
    print(err, '--> our error message')
Python 3.4.1
name 'let_us_cause_a_NameError' is not defined --> our error message

9.The next() function and .next() method

Since next() (.next()) is such a commonly used function (method), this is another syntax change (or rather change in implementation) that is worth mentioning: where you can use both the function and method syntax in Python 2.7.5, the next() function is all that remains in Python 3 (calling the .next() method raises an AttributeError).

Python 2

print 'Python', python_version()

my_generator = (letter for letter in 'abcdefg')

next(my_generator)
my_generator.next()
Python 2.7.6





'b'

Python 3

print('Python', python_version())

my_generator = (letter for letter in 'abcdefg')

next(my_generator)
Python 3.4.1





'a'
my_generator.next()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

<ipython-input-14-125f388bb61b> in <module>()
----> 1 my_generator.next()


AttributeError: 'generator' object has no attribute 'next'

10.For-loop variables and the global namespace leak

Good news is: In Python 3.x for-loop variables don’t leak into the global namespace anymore!

This goes back to a change that was made in Python 3.x and is described in What’s New In Python 3.0 as follows:

“List comprehensions no longer support the syntactic form [... for var in item1, item2, ...]. Use [... for var in (item1, item2, ...)] instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a list() constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.”

Python 2

print 'Python', python_version()

i = 1
print 'before: i =', i

print 'comprehension: ', [i for i in range(5)]

print 'after: i =', i
Python 2.7.6
before: i = 1
comprehension:  [0, 1, 2, 3, 4]
after: i = 4

Python 3

print('Python', python_version())

i = 1
print('before: i =', i)

print('comprehension:', [i for i in range(5)])

print('after: i =', i)
Python 3.4.1
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 1

11.Comparing unorderable types

Another nice change in Python 3 is that a TypeError is raised as warning if we try to compare unorderable types.

Python 2

print 'Python', python_version()
print "[1, 2] > 'foo' = ", [1, 2] > 'foo'
print "(1, 2) > 'foo' = ", (1, 2) > 'foo'
print "[1, 2] > (1, 2) = ", [1, 2] > (1, 2)
Python 2.7.6
[1, 2] > 'foo' =  False
(1, 2) > 'foo' =  True
[1, 2] > (1, 2) =  False

Python 3

print('Python', python_version())
print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))
Python 3.4.1



---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

<ipython-input-16-a9031729f4a0> in <module>()
      1 print('Python', python_version())
----> 2 print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
      3 print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
      4 print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))


TypeError: unorderable types: list() > str()

12.Parsing user inputs via input()

Fortunately, the input() function was fixed in Python 3 so that it always stores the user inputs as str objects. In order to avoid the dangerous behavior in Python 2 to read in other types than strings, we have to use raw_input() instead.

Python 2

Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input('enter a number: ')

enter a number: 123

>>> type(my_input)
<type 'int'>

>>> my_input = raw_input('enter a number: ')

enter a number: 123

>>> type(my_input)
<type 'str'>

Python 3

Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input('enter a number: ')

enter a number: 123

>>> type(my_input)
<class 'str'>

13.Returning iterable objects instead of lists

As we have already seen in the xrange section, some functions and methods return iterable objects in Python 3 now – instead of lists in Python 2.

Since we usually iterate over those only once anyway, I think this change makes a lot of sense to save memory. However, it is also possible – in contrast to generators – to iterate over those multiple times if needed, it is only not so efficient.

And for those cases where we really need the list-objects, we can simply convert the iterable object into a list via the list() function.

Python 2

print 'Python', python_version()

print range(3)
print type(range(3))
Python 2.7.6
[0, 1, 2]
<type 'list'>

Python 3

print('Python', python_version())

print(range(3))
print(type(range(3)))
print(list(range(3)))
Python 3.4.1
range(0, 3)
<class 'range'>
[0, 1, 2]

Some more commonly used functions and methods that don’t return lists anymore in Python 3:

  • zip()
  • map()
  • filter()
  • dictionary’s .keys() method
  • dictionary’s .values() method
  • dictionary’s .items() method

14.Banker’s Rounding

Python 3 adopted the now standard way of rounding decimals when it results in a tie (.5) at the last significant digits. Now, in Python 3, decimals are rounded to the nearest even number. Although it’s an inconvenience for code portability, it’s supposedly a better way of rounding compared to rounding up as it avoids the bias towards large numbers. For more information, see the excellent Wikipedia articles and paragraphs:

  • https://en.wikipedia.org/wiki/Rounding#Round_half_to_even
  • https://en.wikipedia.org/wiki/IEEE_floating_point#Roundings_to_nearest

Python 2

print 'Python', python_version()
Python 2.7.12
round(15.5)
16.0
round(16.5)
17.0

Python 3

print('Python', python_version())
Python 3.5.1
round(15.5)
16
round(16.5)
16