PYTHON by (@mr.udayjatav)

 

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

It is used for:

  • web development (server-side),
  • software development,
  • mathematics,
  • system scripting.

What can Python do?

  • Python can be used on a server to create web applications.
  • Python can be used alongside software to create workflows.
  • Python can connect to database systems. It can also read and modify files.
  • Python can be used to handle big data and perform complex mathematics.
  • Python can be used for rapid prototyping, or for production-ready software development.

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.

Good to know

  • The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
  • In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.

Python Syntax compared to other programming languages

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


Interpreted Python

Unlike C/C++ etc, Python is an interpreted object-oriented programming language. By interpreted it is meant that each time a program is run the interpreter checks through the code for errors and then interprets the instructions into machine-readable bytecode.

An interpreter is a translator in computer's language which translates the given code line-by-line in machine readable bytecodes. And if any error is encounterd it stops the translation until the error is fixed. Unlike C language, which is a compiled programming language. The compiler translates the whole code in one-go rather than line-by-line. This is the reason why in C language, all the errors are listed during compilation only.

# Demonstrating interpreted python

print "\n\n----This line is correct----\n\n"   #line1
print Hello     #this is wrong                 #line2

example to demonstrate interpreted nature of Python

In the above illustration, you can see that line 1 was syntactically correct and hence got successfully executed. Whereas, in line 2 we had a syntax error. Hence the interpreter stopped executing the above script at line 2. This is not valid in the case of a compiled programming language.

The illustration below is a C++ program, see that although line 1 and line 2 were correct than also the program reports an error, due to an error on line 3. This is the basic difference between interpreted language and compiled language.

// Demonstrating Compiled language

#include<iostream>
using namespace std;
int main()
{
        cout<<"---This is correct line---";       // line 1
        cout<<"---This line is also correct---";  // line 2
        cout "this is Incorrect Line"             // line 3
        return 0;
}

Interactive Python


Interactive Python

Python is interactive. When a Python statement is entered, and is followed by the Return key, if appropriate, the result will be printed on the screen, immediately, in the next line. This is particularly advantageous in the debugging process. In interactive mode of operation, Python is used in a similar way as the Unix command line or the terminal.

The interactive Python shell looks like:

Interactive mode of Python

Interactive Python is very much helpful for the debugging purpose. It simply returns the >>> prompt or the corresponding output of the statement if appropriate and returns error for incorrect statements. In this way if you have any doubts like: whether a syntax is correct, whether the module you are importing exists or anything like that, you can be sure within seconds using Python interactive mode.

An illustration for interactive python is shown below:

using the Interactive mode of Python





Python Data Types

Variables can hold values, and every value has a data-type. Python is a dynamically typed language; hence we do not need to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type.

  1. a = 5  

The variable a holds integer value five and we did not define its type. Python interpreter will automatically interpret variables a as an integer type.

Python enables us to check the type of the variable used in the program. Python provides us the type() function, which returns the type of the variable passed.

Consider the following example to define the values of different data types and checking its type.

501
HTML Tutorial

  1. a=10  
  2. b="Hi Python"  
  3. c = 10.5  
  4. print(type(a))  
  5. print(type(b))  
  6. print(type(c))  

Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types

A variable can hold different types of values. For example, a person's name must be stored as a string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each of them. The data types defined in Python are given below.

  1. Numbers
  2. Sequence Type
  3. Boolean
  4. Set
  5. Dictionary
Python Data Types

In this section of the tutorial, we will give a brief introduction of the above data-types. We will discuss each one of them in detail later in this tutorial.

Numbers

Number stores numeric values. The integer, float, and complex values belong to a Python Numbers data-type. Python provides the type() function to know the data-type of the variable. Similarly, the isinstance() function is used to check an object belongs to a particular class.

Python creates Number objects when a number is assigned to a variable. For example;

  1. a = 5  
  2. print("The type of a", type(a))  
  3.   
  4. b = 40.5  
  5. print("The type of b", type(b))  
  6.   
  7. c = 1+3j  
  8. print("The type of c", type(c))  
  9. print(" c is a complex number", isinstance(1+3j,complex))  

Output:

The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three types of numeric data.

  1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has no restriction on the length of an integer. Its value belongs to int
  2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate upto 15 decimal points.
  3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.

Sequence Type

String

The string can be defined as the sequence of characters represented in the quotation marks. In Python, we can use single, double, or triple quotes to define a string.

String handling in Python is a straightforward task since Python provides built-in functions and operators to perform operations in the string.

In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python Python'.

The following example illustrates the string in Python.

Example - 1

  1. str = "string using double quotes"  
  2. print(str)  
  3. s = '''''A multiline 
  4. string'''  
  5. print(s)  

Output:

string using double quotes
A multiline
string

Consider the following example of string handling.

Example - 2

  1. str1 = 'hello javatpoint' #string str1    
  2. str2 = ' how are you' #string str2    
  3. print (str1[0:2]) #printing first two character using slice operator    
  4. print (str1[4]) #printing 4th character of the string    
  5. print (str1*2#printing the string twice    
  6. print (str1 + str2) #printing the concatenation of str1 and str2    

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List

Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator (*) works with the list in the same way as they were working with the strings.

Consider the following example.

  1. list1  = [1"hi""Python"2]    
  2. #Checking type of given list  
  3. print(type(list1))  
  4.   
  5. #Printing the list1  
  6. print (list1)  
  7.   
  8. # List slicing  
  9. print (list1[3:])  
  10.   
  11. # List slicing  
  12. print (list1[0:2])   
  13.   
  14. # List Concatenation using + operator  
  15. print (list1 + list1)  
  16.   
  17. # List repetation using * operator  
  18. print (list1 * 3)  

Output:

[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Let's see a simple example of the tuple.

  1. tup  = ("hi""Python"2)    
  2. # Checking type of tup  
  3. print (type(tup))    
  4.   
  5. #Printing the tuple  
  6. print (tup)  
  7.   
  8. # Tuple slicing  
  9. print (tup[1:])    
  10. print (tup[0:1])    
  11.   
  12. # Tuple concatenation using + operator  
  13. print (tup + tup)    
  14.   
  15. # Tuple repatation using * operator  
  16. print (tup * 3)     
  17.   
  18. # Adding value to tup. It will throw an error.  
  19. t[2] = "hi"  

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary

Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where each key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

Consider the following example.

  1. d = {1:'Jimmy'2:'Alex'3:'john'4:'mike'}     
  2.   
  3. # Printing dictionary  
  4. print (d)  
  5.   
  6. # Accesing value using keys  
  7. print("1st name is "+d[1])   
  8. print("2nd name is "+ d[4])    
  9.   
  10. print (d.keys())    
  11. print (d.values())    

Output:

1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

Boolean type provides two built-in values, True and False. These values are used to determine the given statement true or false. It denotes by the class bool. True can be represented by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following example.

  1. # Python program to check the boolean type  
  2. print(type(True))  
  3. print(type(False))  
  4. print(false)  

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set

Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after creation), and has unique elements. In set, the order of the elements is undefined; it may return the changed sequence of the element. The set is created by using a built-in function set(), or a sequence of elements is passed in the curly braces and separated by the comma. It can contain various types of values. Consider the following example.

  1. # Creating Empty set  
  2. set1 = set()  
  3.   
  4. set2 = {'James'23,'Python'}  
  5.   
  6. #Printing Set value  
  7. print(set2)  
  8.   
  9. # Adding element to the set  
  10.   
  11. set2.add(10)  
  12. print(set2)  
  13.   
  14. #Removing element from the set  
  15. set2.remove(2)  
  16. print(set2)  

Output:

{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}






Variables

Variables are containers for storing data values.


Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Example

x = 5
y = "John"
print(x)
print(y)
Try it Yourself »

Variables do not need to be declared with any particular type, and can even change type after they have been set.

Example

x = 4       # x is of type int
x = "Sally" # x is now of type str
print(x)
Try it Yourself »

Casting

If you want to specify the data type of a variable, this can be done with casting.

Example

x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0
Try it Yourself »

Get the Type

You can get the data type of a variable with the type() function.

Example

x = 5
y = "John"
print(type(x))
print(type(y))
Try it Yourself »

Single or Double Quotes?

String variables can be declared either by using single or double quotes:

Example

x = "John"
# is the same as
x = 'John'
Try it Yourself »

Case-Sensitive

Variable names are case-sensitive.

Example

This will create two variables:

a = 4
A = "Sally"
#A will not overwrite a



Expressions in Python

An expression is a combination of operators and operands that is interpreted to produce some other value. In any programming language, an expression is evaluated as per the precedence of its operators. So that if there is more than one operator in an expression, their precedence decides which operation will be performed first. We have many different types of expressions in Python. Let’s discuss all types along with some exemplar codes :

1. Constant Expressions: These are the expressions that have constant values only.

Example:

# Constant Expressions
x = 15 + 1.3
  
print(x)
Output
16.3

2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic operators in Python:

OperatorsSyntaxFunctioning
+x + yAddition
x – ySubtraction
*x * yMultiplication
/x / yDivision
//x // yQuotient
%x % yRemainder
**x ** yExponentiation

Example:

Let’s see an exemplar code of arithmetic expressions in Python :

# Arithmetic Expressions
x = 40
y = 12
  
add = x + y
sub = x - y
pro = x * y
div = x / y
  
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335

3. Integral Expressions: These are the kind of expressions that produce only integer results after all computations and type conversions.

Example:

# Integral Expressions
a = 13
b = 12.0
  
c = a + int(b)
print(c)
Output
25

4. Floating Expressions: These are the kind of expressions which produce floating point numbers as result after all computations and type conversions.

Example:

# Floating Expressions
a = 13
b = 5
  
c = a / b
print(c)
Output
2.6

5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per relational operator and produce a boolean output in the end. These expressions are also called Boolean expressions.

Example:

# Relational Expressions
a = 21
b = 13
c = 40
d = 37
  
p = (a + b) >= (c - d)
print(p)
Output
True

6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return False. Studying logical expressions, we also come across some logical operators which can be seen in logical expressions most often. Here are some logical operators in Python:

OperatorSyntaxFunctioning
andP and QIt returns true if both P and Q are true otherwise returns false
orP or QIt returns true if at least one of P and Q is true
notnot PIt returns true if condition P is false

Example:

Let’s have a look at an exemplar code :

P = (10 == 9)
Q = (7 > 5)
  
# Logical Expressions
R = P and Q
S = P or Q
T = not P
  
print(R)
print(S)
print(T)
Output
False
True
True

7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit level.

Example:

# Bitwise Expressions
a = 12
  
x = a >> 2
y = a << 1
  
print(x, y)
Output
3 24

8. Combinational Expressions: We can also use different types of expressions in a single expression, and that will be termed as combinational expressions.

Example:

# Combinational Expressions
a = 16
b = 12
  
c = a + (b >> 1)
print(c)
Output
22

But when we combine different types of expressions or use multiple operators in a single expression, operator precedence comes into play.

Multiple operators in expression (Operator Precedence)

It’s a quite simple process to get the result of an expression if there is only one operator in an expression. But if there is more than one operator in an expression, it may give different results on basis of the order of operators executed. To sort out these confusions, the operator precedence is defined. Operator Precedence simply defines the priority of operators that which operator is to be executed first. Here we see the operator precedence in Python, where the operator higher in the list has more precedence or priority:

PrecedenceNameOperator
1Parenthesis   ( ) [ ] { }
2Exponentiation **
3Unary plus or minus, complement -a , +a , ~a
4Multiply, Divide, Modulo  /  *  //  %
5Addition & Subtraction +  –
6Shift Operators>>  <<
7Bitwise AND&
8Bitwise XOR^
9Bitwise OR|
10Comparison Operators>=  <=  >  <
11Equality Operators==  !=
12Assignment Operators =  +=  -=  /=  *=
13Identity and membership operatorsis, is not, in, not in
14Logical Operators   and, or, not

So, if we have more than one operator in an expression, it is evaluated as per operator precedence. For example, if we have the expression “10 + 3 * 4”. Going without precedence it could have given two different outputs 22 or 52. But now looking at operator precedence, it must yield 22. Let’s discuss this with the help of a Python program:

# Multi-operator expression
  
a = 10 + 3 * 4
print(a)
  
b = (10 + 3) * 4
print(b)
  
c = 10 + (3 * 4)
print(c)
Output
22
52
22

Hence, operator precedence plays an important role in the evaluation of a Python expression.


Tuple Assignment

Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an assignment to be assigned values from a tuple on the right of the assignment.

(name, surname, birth_year, movie, movie_year, profession, birth_place) = julia

This does the equivalent of seven assignment statements, all on one easy line. One requirement is that the number of variables on the left must match the number of elements in the tuple.

Once in a while, it is useful to swap the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b:

temp = a
a = b
b = temp

Tuple assignment solves this problem neatly:

(a, b) = (b, a)

The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. This feature makes tuple assignment quite versatile.

Naturally, the number of variables on the left and the number of values on the right have to be the same.

>>> (a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack

The following table lists all operators from highest precedence to lowest.

OperatorDescription
**Exponentiation (raise to the power)
~ + -Complement, unary plus and minus (method names for the last two are +@ and -@)
* / % //Multiply, divide, modulo and floor division
+ -Addition and subtraction
>> <<Right and left bitwise shift
&Bitwise 'AND'td>
^ |Bitwise exclusive `OR' and regular `OR'
<= < > >=Comparison operators
<> == !=Equality operators
= %= /= //= -= += *= **=Assignment operators
is is notIdentity operators
in not inMembership operators
not or andLogical operators

Operator precedence affects how an expression is evaluated.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.

Example

#!/usr/bin/python

a = 20
b = 10
c = 15
d = 5
e = 0

e = (a + b) * c / d       #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ",  e

e = ((a + b) * c) / d     # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ",  e

e = (a + b) * (c / d);    # (30) * (15/5)
print "Value of (a + b) * (c / d) is ",  e

e = a + (b * c) / d;      #  20 + (150/5)
print "Value of a + (b * c) / d is ",  e

When you execute the above program, it produces the following result −

Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50

MODULES

A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.

Example

The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py

def print_func( par ):
   print "Hello : ", par
   return

The import Statement

You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax −

import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script −

#!/usr/bin/python

# Import module support
import support

# Now you can call defined function that module as follows
support.print_func("Zara")

When the above code is executed, it produces the following result −

Hello : Zara

A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.

The from...import Statement

Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax −

from modname import name1[, name2[, ... nameN]]

For example, to import the function fibonacci from the module fib, use the following statement −

from fib import fibonacci

This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.

The from...import * Statement

It is also possible to import all names from a module into the current namespace by using the following import statement −

from modname import *

This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.

Locating Modules

When you import a module, the Python interpreter searches for the module in the following sequences −

  • The current directory.

  • If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.

  • If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.

The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.

The PYTHONPATH Variable

The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.

Here is a typical PYTHONPATH from a Windows system −

set PYTHONPATH = c:\python20\lib;

And here is a typical PYTHONPATH from a UNIX system −

set PYTHONPATH = /usr/local/lib/python

Namespaces and Scoping

Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).

A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.

Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.

Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.

Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.

The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.

For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.

#!/usr/bin/python

Money = 2000
def AddMoney():
   # Uncomment the following line to fix the code:
   # global Money
   Money = Money + 1

print Money
AddMoney()
print Money

The dir( ) Function

The dir() built-in function returns a sorted list of strings containing the names defined by a module.

The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −

#!/usr/bin/python

# Import built-in module math
import math

content = dir(math)
print content

When the above code is executed, it produces the following result −

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 
'sqrt', 'tan', 'tanh']

Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.

The globals() and locals() Functions

The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.

If locals() is called from within a function, it will return all the names that can be accessed locally from that function.

If globals() is called from within a function, it will return all the names that can be accessed globally from that function.

The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.

The reload() Function

When the module is imported into a script, the code in the top-level portion of a module is executed only once.

Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −

reload(module_name)

Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following −

reload(hello)

Packages in Python

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.

Consider a file Pots.py available in Phone directory. This file has following line of source code −

#!/usr/bin/python

def Pots():
   print "I'm Pots Phone"

Similar way, we have another two files having different functions with the same name as above −

  • Phone/Isdn.py file having function Isdn()

  • Phone/G3.py file having function G3()

Now, create one more file __init__.py in Phone directory −

  • Phone/__init__.py

To make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows −

from Pots import Pots
from Isdn import Isdn
from G3 import G3

After you add these lines to __init__.py, you have all of these classes available when you import the Phone package.

#!/usr/bin/python

# Now import your Phone Package.
import Phone

Phone.Pots()
Phone.Isdn()
Phone.G3()

When the above code is executed, it produces the following result −

I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone

In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.


FUNCTION

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

Defining a Function

You can define functions to provide the required functionality. Here are simple rules to define a function in Python.

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

  • The first statement of a function can be an optional statement - the documentation string of the function or docstring.

  • The code block within every function starts with a colon (:) and is indented.

  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Syntax

def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

Example

The following function takes a string as input parameter and prints it on standard screen.

def printme( str ):
   "This prints a passed string into this function"
   print str
   return

Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function −

#!/usr/bin/python

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str
   return;

# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result −

I'm first call to user defined function!
Again second call to the same function

Pass by reference vs value

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −

#!/usr/bin/python

# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist.append([1,2,3,4]);
   print "Values inside the function: ", mylist
   return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −

Values inside the function:  [10, 20, 30, [1, 2, 3, 4]]
Values outside the function:  [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.

#!/usr/bin/python

# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist = [1,2,3,4]; # This would assig new reference in mylist
   print "Values inside the function: ", mylist
   return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −

Values inside the function:  [1, 2, 3, 4]
Values outside the function:  [10, 20, 30]

Function Arguments

You can call a function by using the following types of formal arguments −

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

Required arguments

Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows −

#!/usr/bin/python

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str
   return;

# Now you can call printme function
printme()

When the above code is executed, it produces the following result −

Traceback (most recent call last):
   File "test.py", line 11, in <module>
      printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −

#!/usr/bin/python

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str
   return;

# Now you can call printme function
printme( str = "My string")

When the above code is executed, it produces the following result −

My string

The following example gives more clear picture. Note that the order of parameters does not matter.

#!/usr/bin/python

# Function definition is here
def printinfo( name, age ):
   "This prints a passed info into this function"
   print "Name: ", name
   print "Age ", age
   return;

# Now you can call printinfo function
printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −

Name:  miki
Age  50

Default arguments

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −

#!/usr/bin/python

# Function definition is here
def printinfo( name, age = 35 ):
   "This prints a passed info into this function"
   print "Name: ", name
   print "Age ", age
   return;

# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −

Name:  miki
Age  50
Name:  miki
Age  35

Variable-length arguments

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):
   "function_docstring"
   function_suite
   return [expression]

An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −

#!/usr/bin/python

# Function definition is here
def printinfo( arg1, *vartuple ):
   "This prints a variable passed arguments"
   print "Output is: "
   print arg1
   for var in vartuple:
      print var
   return;

# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −

Output is:
10
Output is:
70
60
50

The Anonymous Functions

These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

  • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

  • An anonymous function cannot be a direct call to print because lambda requires an expression

  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

  • Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.

Syntax

The syntax of lambda functions contains only a single statement, which is as follows −

lambda [arg1 [,arg2,.....argn]]:expression

Following is the example to show how lambda form of function works −

#!/usr/bin/python

# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

When the above code is executed, it produces the following result −

Value of total :  30
Value of total :  40

The return Statement

The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

All the above examples are not returning any value. You can return a value from a function as follows −

#!/usr/bin/python

# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2
   print "Inside the function : ", total
   return total;

# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total 

When the above code is executed, it produces the following result −

Inside the function :  30
Outside the function :  30

Scope of Variables

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −

  • Global variables
  • Local variables

Global vs. Local variables

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example −

#!/usr/bin/python

total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print "Inside the function local total : ", total
   return total;

# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total 

When the above code is executed, it produces the following result −

Inside the function local total :  30
Outside the function global total :  0


Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

Example

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Try it Yourself »

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?

The terms parameter and argument can be used for the same thing: information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that are sent to the function when it is called.


Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

Example

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil""Refsnes")
Try it Yourself »

If you try to call the function with 1 or 3 arguments, you will get an error:

Example

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil")
What is the difference between operators and operands?
An operator is the ‘function’ that performs the operation, whereas the operand is the input to that function. In the expression 3 + 4 = 7, the operator is ‘+’ - since it’s telling us how to perform the operation - and the operands are 3 and 4 - the inputs upon which the operation is acting.

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example

If statement:

a = 33
b = 200
if b > a:
  print("b is greater than a")
Try it Yourself »

In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a".

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.

Example

If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a"# you will get an error
Try it Yourself »

Elif

The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".

Example

a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
Try it Yourself »

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal".


Else

The else keyword catches anything which isn't caught by the preceding conditions.

Example

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")
Try it Yourself »

In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b".

You can also have an else without the elif:

Example

a = 200
b = 33
if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")


Comments