0% found this document useful (0 votes)
62 views

Python Module-1

This document provides an introduction and overview of the Python programming language. It describes Python's key features like being dynamically typed, object-oriented, and having a vast library. It also covers Python's history and versions, how to install and check Python, popular IDEs for development, basic syntax like indentation and comments, and core concepts like keywords, identifiers, variables, expressions, statements, and operators.

Uploaded by

Sahana S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Python Module-1

This document provides an introduction and overview of the Python programming language. It describes Python's key features like being dynamically typed, object-oriented, and having a vast library. It also covers Python's history and versions, how to install and check Python, popular IDEs for development, basic syntax like indentation and comments, and core concepts like keywords, identifiers, variables, expressions, statements, and operators.

Uploaded by

Sahana S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Sub.

Name : Data Analytics


MAHARAJA INSTITUTE OF
using Python
TECHNOLOGY MYSORE
DEPARTMENT OF MASTER OF
Course Code : 22MCA31
COMPUTER APPLICATIONS

Module 1

Python Basic Concepts and Programming

Introduction:

Python is a general purpose programming language like C, C++, JAVA created by Guido Vas
Rossum.

Features of Python:

 Support for functional and Object oriented programming


 High-level data structures
 Simple syntax and verbose
 Dynamically typed
 Easily integrated with C, C++, Java
 Auto garbage collection
 Vast library
 Platform independent
 Support for Database, file handling and GUI programming
 Interpreted
 Open source
 Interactive ( can execute commands in prompt)

Application of Python:

 Software development
 Web application development
 Text processing
 System scripting (Shell programming)
 Data analytics
 Many more…

Version history:
 Python 0.9.0- 1991
 Python 1.0- 1994
 Python 2.0- 2000
 Python 3 – 2008
 Python 3.9 – 2020
 Python 3.10 – 2021

Python download:

Python.org

To check the version installed: python –v or python --version

To list all installed packages: pip list

To install a package: pip install package name

Note: these commands has to be executed in command line. In Jupyter notebook use !pip
list, !pip install package name

IDE for development:

 IDLE- default IDE


 Pycharm
 Anaconda (Spider, Jupyter)
 Visual Studio Code

Syntax:

 Whitespace for indentation to define a scope for loop, function, classes ( curly
brackets {} are not used)
 Subsequent lines in the indented regions should be in the same column
 Code block is called as suites
 No semi-colon at the end of statement
 Use backslash character \ to join a statement span over multiple lines
o E.g.,

if a > b and \

a <= c:

print('a is largest')

 File extension - .py


 Case sensitive
 Single line comments are written using #
 Multi-line comments are written using ‘’’ comment ‘’’
 Complex/compound statements consists of header lines and suites

Indentation Rules

 Use the colon : to start a block and press Enter.


E.g.,
if (a>b):
print (‘a is largest’)
else:
print(‘b is largest’)
 All the lines in a block must use the same indentation, either space or a tab.
 Python recommends four spaces as indentation to make the code more
readable. Do not mix space and tab in the same block.
 A block can have inner blocks with next level indentation.

E.g.,

if 10 > 5: # 1st block starts


print(“10 is greater than 5”) # 1st block
print(“Now checking 20 > 10”) # 1st block
if 20 > 10: # 1st block
print(“20 is greater than 10”) # inner block
elif: # 2nd block starts
print(“10 is less than 5”) # 2nd block
print(“This will never print”) # 2nd block

Executing Code:

 python filename.py or py filename.py is the command for execution of the code.

Keywords:

 Reserve words or built-in words with predefined meaning.


 There are 33 keywords in Python 3.0
The following table list all the keywords in Python.

False def if raise


None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
continue global pass
Except for the first three (False, None and True), the other keywords are entirely
in lowercase.
Use help() command to know more about each individual keyword. E.g,
help("def")

Identifiers:

It is name used to identify a variable, function, class, module or other object.

Rules:

The Python identifier is made with


a combination of lowercase or uppercase letters, digits or an underscore.

An identifier cannot start with a digit.

We also cannot use special symbols in the identifiers name.

A keyword cannot be used as an identifier.

Reserved Classes of Python Identifiers

Python built-in classes contains some identifiers that have special


meanings. These special identifiers are recognized by the patterns of
leading and trailing underscore characters:

Single leading underscore (_*)

This identifier is used to store the result of the last evaluation in the interactive
interpreter.

Double leading and trailing underscores (__*__)

It represents system-defined identifiers that matches __*__ pattern, also


known as dunder names. These can be functions or properties such
as __new__(), __init__(), __name__, __main__, etc.

Leading double underscores (__*)

It represents class's private name pattern. These names are to be used


with private member names of the class to avoid name clashes between
private attributes of base and derived classes.
Variables:

Named memory locations. Variables are created when you assign a value
to it.

E.g., a=2, name=’MIT-MCA’, pi=3.14

The type of variable/object can be determined using type() function. E.g.,


type(a) - int

Expressions and statements

An expression is a combination of values, variables, and operators. A statement is a unit of


code that has an effect, like creating a variable or displaying a
value.

E.g.,

a+b : expression , x=a+b : statement

Operators:

Operators are special symbols that perform some operation on


operands and returns the result.

Python includes the following categories of operators:

 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Identity Operators
 Membership Test Operators
 Bitwise Operators

Arithmetic Operators

Arithmetic operators perform the common mathematical operation on the


numeric operands.

The arithmetic operators return the type of result depends on the type of
operands, as below.

1. If either operand is a complex number, the result is converted to


complex;
2. If either operand is a floating point number, the result is converted
to floating point;
3. If both operands are integers, then the result is an integer and no
conversion is needed.

The following table lists all the arithmetic operators in Python:

Operation Operator Function Example in Python Shell


Addition: Sum of two + operator.add(a,b) >>> x = 5; y = 6
operands >>> x + y
11
>>> import operator
>>> operator.add(5,6)
11
Subtraction: Left operand - operator.sub(a,b) >>> x = 10; y = 5
minus right operand >>> x - y
5
>>> import operator
>>> operator.sub(10,
5)
5
Multiplication * operator.mul(a,b) >>> x = 5; y = 6
>>> x * y
30
>>> import operator
>>> operator.mul(5,6)
30
Exponentiation: Left operand ** operator.pow(a,b) >>> x = 2; y = 3
raised to the power of right >>> x ** y
8
>>> import operator
>>> operator.pow(2, 3)
8
Division / operator.truediv(a,b) >>> x = 6; y = 3
>>> x / y
2
>>> import operator
>>>
operator.truediv(6, 3)
2
Floor division: equivilant // operator.floordiv(a,b) >>> x = 6; y = 5
to math.floor(a/b) >>> x // y
1
>>> import operator
>>>
operator.floordiv(6,5)
1
Modulus: Reminder of a/b % operator.mod(a, b) >>> x = 11; y = 3
Operation Operator Function Example in Python Shell
>>> x % y
12
>>> import operator
>>> operator.mod(11,
3)
2

Assignment Operators

The assignment operators are used to assign values to variables. The


following table lists all the arithmetic operators in Python:

Operator Function Example in Python Shell

= >>> x = 5;
>>> x
5
+= operator.iadd(a,b) >>> x = 5
>>> x += 5
10
>>> import operator
>>> x = operator.iadd(5, 5)
10
-= operator.isub(a,b) >>> x = 5
>>> x -= 2
3
>>> import operator
>>> x = operator.isub(5,2)
*= operator.imul(a,b) >>> x = 2
>>> x *= 3
6
>>> import operator
>>> x = operator.imul(2, 3)
/= operator.itruediv(a,b) >>> x = 6
>>> x /= 3
2
>>> import operator
>>> x = operator.itruediv(6, 3)
//= operator.ifloordiv(a,b) >>> x = 6
>>> x //= 5
1
>>> import operator
>>> operator.ifloordiv(6,5)
%= operator.imod(a, b) >>> x = 11
>>> x %= 3
Operator Function Example in Python Shell

2
>>> import operator
>>> operator.imod(11, 3)
2
&= operator.iand(a, b) >>> x = 11
>>> x &= 3
1
>>> import operator
>>> operator.iand(11, 3)
1
|= operator.ior(a, b) >>> x = 3
>>> x |= 4
7
>>> import operator
>>> operator.mod(3, 4)
7
^= operator.ixor(a, b) >>> x = 5
>>> x ^= 2
7
>>> import operator
>>> operator.ixor(5, 2)
7
>>= operator.irshift(a, b) >>> x = 5
>>> x >>= 2
1
>>> import operator
>>> operator.irshift(5, 2)
1
<<= operator.ilshift(a, b) >>> x = 5
>>> x <<= 2
20
>>> import operator
>>> operator.ilshift(5, 2)
20

Comparison Operators

The comparison operators compare two operands and return a boolean


either True or False. The following table lists comparison operators in
Python.

Operator Function Description Example in Python Shell

> operator.gt(a,b) True if the left operand is higher than >>> x = 5; y = 6


the right one >>> x > y
False
Operator Function Description Example in Python Shell

>>> import operator


>>>
operator.gt(5,6)
False
< operator.lt(a,b) True if the left operand is lower than >>> x = 5; y = 6
right one >>> x < y
True
>>> import operator
>>>
operator.add(5,6)
True
== operator.eq(a,b) True if the operands are equal >>> x = 5; y = 6
>>> x == y
False
>>> import operator
>>>
operator.eq(5,6)
False
!= operator.ne(a,b) True if the operands are not equal >>> x = 5; y = 6
>>> x != y
True
>>> import operator
>>>
operator.ne(5,6)
True
>= operator.ge(a,b) True if the left operand is higher than >>> x = 5; y = 6
or equal to the right one >>> x >= y
False
>>> import operator
>>>
operator.ge(5,6)
False
<= operator.le(a,b) True if the left operand is lower than >>> x = 5; y = 6
or equal to the right one >>> x <= y
True
>>> import operator
>>>
operator.le(5,6)
True

Logical Operators

The logical operators are used to combine two boolean expressions. The
logical operations are generally applicable to all objects, and support truth
tests, identity tests, and boolean operations.
Operator Description Example

and True if both are true >>> x = 5; y = 6


>>> x > 1 and y
<10
True
or True if at least one is true >>> x = 5; y = 6
>>> x > 6 or y <10
True
not Returns True if an expression evalutes to false and vice- >>> x = 5
versa >>> not x > 1
False

Identity Operators

The identity operators check whether the two objects have the same id
value e.i. both the objects point to the same memory location.

Operator Function Description Example in Python Shell

is operator.is_(a,b) True if both are true >>> x = 5; y = 6


>>> x is y
False
>>> import operator
>>> operator.is_(x,y)
False
is not operator.is_not(a,b) True if at least one is true >>> x = 5; y = 6
>>> x is not y
True
>>> import operator
>>> operator.is_not(x, y)
True

Membership Test Operators

The membership test operators in and not in test whether the sequence
has a given item or not. For the string and bytes types, x in y is True if
and only if x is a substring of y.

Operator Function Description Example in Python Shell

in operator.contains(a,b) Returns True if the >>> nums = [1,2,3,4,5]


sequence contains the >>> 1 in nums
True
specified item else
>>> 10 in nums
returns False. False
>>> 'str' in 'string'
Operator Function Description Example in Python Shell

True
>>> import operator
>>>
operator.contains(nums,
2)
True
not in not Returns True if the >>> nums = [1,2,3,4,5]
operator.contains(a,b) sequence does not >>> 1 not in nums
False
contains the specified
>>> 10 not in nums
item, else returns False. True
>>> 'str' not in 'string'
False
>>> import operator
>>> not
operator.contains(nums,
2)
False

Bitwise Operators

Bitwise operators perform operations on binary operands.

Operator Function Description Example in Python Shell

& operator.and_(a,b) Sets each bit to 1 if both bits are 1. >>> x=5; y=10
>>> z=x & y
>>> z
0
>>> import operator
>>> operator.and_(x,
y)
0
| operator.or_(a,b) Sets each bit to 1 if one of two bits >>> x=5; y=10
is 1. >>> z=x | y
>>> z
15
>>> import operator
>>> operator.or_(x,
y)
15
^ operator.xor(a,b) Sets each bit to 1 if only one of two >>> x=5; y=10
bits is 1. >>> z=x ^ y
>>> z
15
>>> import operator
Operator Function Description Example in Python Shell

>>> operator.xor(x,
y)
15
~ operator.invert(a) Inverts all the bits. >>> x=5
>>> ~x
-6
>>> import operator
>>>
operator.invert(x)
-6
<< operator.lshift(a,b) Shift left by pushing zeros in from >>> x=5
the right and let the leftmost bits >>> x<<2
20
fall off.
>>> import operator
>>>
operator.lshift(x,2)
20
>> operator.rshift(a,b) Shift right by pushing copies of the >>> x=5
leftmost bit in from the left, and let >>> x>>2
1
the rightmost bits fall off.
>>> import operator
>>>
operator.rshift(x,2)
1

Order of operations (Precedence and Associativity)

When an expression contains more than one operator, the order of evaluation depends
on the order of operations. For mathematical operators, Python follows mathematical
convention. The acronym PEMDAS is a useful way to remember the rules:

• Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first,
2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an
expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the
result.
• Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 *
3**2 is 18, not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction.
So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right (except
exponentiation).
So in the expression degrees / 2 * pi, the division happens first and the
result is multiplied by pi. To divide by 2p, you can use parentheses or write degrees
/ 2 / pi.
Data Types:

Python Data Types

Data types are the classification or categorization of data items. Python


supports the following built-in data types.

Scalar Types

 int: Positive or negative whole numbers (without a fractional part)


e.g. -10, 10, 456, 4654654.
 float: Any real number with a floating-point representation in which
a fractional component is denoted by a decimal symbol or scientific
notation e.g. 1.23, 3.4556789e2.
 complex: A number with a real and imaginary component
represented as x + 2y.
 bool: Data with one of two built-in values True or False. Notice that
'T' and 'F' are capital. true and false are not valid booleans and
Python will throw an error for them.
 None: The None represents the null object in Python. A None is
returned by functions that don't explicitly return a value.

Sequence Type

A sequence is an ordered collection of similar or different data types.


Python has the following built-in sequence data types:

 String: A string value is a collection of one or more characters put in


single, double or triple quotes.
 List: A list object is an ordered collection of one or more data items,
not necessarily of the same type, put in square brackets.
 Tuple: A Tuple object is an ordered collection of one or more data
items, not necessarily of the same type, put in parentheses.

Mapping Type

Dictionary: A dictionary Dict() object is an unordered collection of data


in a key:value pair form. A collection of such pairs is enclosed in curly
brackets. For example: {1:"Steve", 2:"Bill", 3:"Ram", 4: "Farha"}

Set Types

 set: Set is mutable, unordered collection of distinct hashable objects.


The set is a Python implementation of the set in Mathematics. A set
object has suitable methods to perform mathematical set operations
like union, intersection, difference, etc.

Mutable and Immutable Types

Data objects of the above types are stored in a computer's memory for
processing. Some of these values can be modified during processing, but
contents of others can't be altered once they are created in the memory.

Numbers, strings, and Tuples are immutable, which means their contents
can't be altered after creation.

On the other hand, items in a List or Dictionary object can be modified.


It is possible to add, delete, insert, and rearrange items in a list or
dictionary. Hence, they are mutable objects

Type Conversion:

Explicit type conversion can be performed by using the C style syntax.

E.g., str(32) -> ‘32’, int(32.33)-> 32, float(32)-> 32.0

Input and Output functions:

Python provides us with the two inbuilt functions as input() and print().

Input function:

The syntax for input is input(prompt_message); the python will automatically identify
whether the user entered a string, number, or list; if the input entered from the user is not
correct, then python will throw a syntax error.

E.g,

x=input("Enter First number:")

y=input("Enter Second Number:")

i=int(x)

j=int(y)

print("The Sum:", i+j)

Output function:

We use the print() function to output data to the standard output device (screen)
Syntax: The actual syntax of the print() function is:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.

The sep separator is used between the values. It defaults into a space character.

After all values are printed, end is printed. It defaults into a new line.

The file is the object where the values are printed and its default value is sys.stdout
(screen). Here is an example to illustrate this.

E.g.,

print(' Welcome to MIT MCA')

a=5

print('The value of a is', a)

print(1, 2, 3, 4) o/p-> 1 2 3 4

print(1, 2, 3, 4, sep='*') o/p-> 1*2*3*4

print(1, 2, 3, 4, sep='#', end='&') o/p-> 1#2#3#4&

Output formatting

Sometimes we would like to format our output to make it look attractive.


This can be done by using the str.format() method. This method is visible
to any string object.

>>> x = 5; y = 10

>>> print('The value of x is {} and y is {}'.format(x,y))

The value of x is 5 and y is 10

Here, the curly braces {} are used as placeholders. We can specify the
order in which they are printed by using numbers (tuple index).
print('I love {0} and {1}'.format('MIT','MCA'))

print('I love {1} and {0}'.format('MIT','MCA'))

We can also format strings like the old sprintf() style used in C
programming language. We use the % operator to accomplish this.

>>> x = 12.3456789

>>> print('The value of x is %3.2f' %x)

The value of x is 12.35

>>> print('The value of x is %3.4f' %x)

The value of x is 12.3457

Control Flow Statements:

Decision making statements:

Decision making/conditional statements provides the flexibility to execute a part of


the code based on certain condition. Python programming language provides
following types of decision making statements.

Sl.No. Statement & Description

1 if statements

An if statement consists of a boolean expression followed by one or more


statements.
Syntax:
if(condition):
suites
Eg.,
if x > 0:
print('x is positive')
2 if...else statements
An if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE. Used for two way
branching.
Syntax:
if(condition):
suites
else:
suites
E.g.,
if x % 2 == 0:
print('x is even')
else:
print('x is odd')

3 Chained if-else statements


Series of if elseif followed by else block. Used for multiple branching
options.
Syntax:
if(condition):
suites
elif (condition):
suites
….
else:
suites
E.g.,
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
4 Nested if-else statement
An if-else statement nested inside another if-else statement.
Syntax:
if(condition):
if(condition):
suites
else:
suites
else:
suites
E.g.,
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')

Looping/Iterative statements:

Repeated execution of suite/code block until some condition is achieved


by iterative statements.

Python provides with While loop and for loop for executing code
repeatedly.

While loop:

 Entry controlled loop: first, the given condition is verified then the
execution of statements is determined based on the condition result

Syntax:

while condition:
Statement_1
Statement_2
Statement_3
...
E.g.,
x=1

n=5
while (x <=10):
p=x*n

print(n,’*’,x,’=’,p)
x=x+1

Do-While Loop:

For loop:

For loop in Python is used to iterate over items of any sequence, such as a list or a
string.

Syntax:

for val in sequence:


statements
E.g.,
for i in range(1,5):
print(i)
Note:
The range() Function In Python
The range() function is a built-in that is used to iterate over a sequence of numbers.

Syntax Of range() Function

range(start, stop[, step])

Nested For Loops In Python


When one Loop defined within another Loop is called Nested Loops.

Syntax of Nested For Loops


for val in sequence:

for val in sequence:

statements

statements

Example 1 of Nested For Loops (Pattern Programs)


for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')

Run Code

Output :-

1
22
333
4444
55555

Example 2 of Nested For Loops (Pattern Programs)

for i in range(1,6):
for j in range(5,i-1,-1):
print(i, end=" ")
print('')

Output :-

11111
2222
333
44
5

Python break statement

The break is a keyword in python which is used to bring the program control out of
the loop. The break statement breaks the loops one by one, i.e., in the case of nested
loops, it breaks the inner loop first and then proceeds to outer loops. In other words,
we can say that break is used to abort the current execution of the program and the
control goes to the next line after the loop.

The break is commonly used in the cases where we need to break the loop for a given
condition.

The syntax of the break is given below.


#loop statements
break;

Example 1
n=2
while 1:
i=1;
while i<=10:
print("%d X %d = %d\n"%(n,i,n*i));
i = i+1;
choice = int(input("Do you want to continue printing the table, press 0 for no?"))
if choice == 0:
break;
n=n+1
Continue statement:
The continue statement skips the remaining lines of code inside the loop and start with
the next iteration.
#loop statements
continue
#the code to be skipped
E.g.,
i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)
Pass statement:
he pass keyword is used to execute nothing; it means, when we don't want to execute
code, the pass can be used to execute empty. to bypass any code pass statement can be
used.
Usage:
# Empty Function
def function_name(args):
pass
#Empty Class
class Python:
pass
Functions in Python:

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

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

Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access
the items accordingly:

Example

If the number of arguments is unknown, add a * before the parameter


name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Arbitrary Keyword Arguments, **kwargs

If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.

This way the function will receive a dictionary of arguments, and can
access the items accordingly:
Example

If the number of keyword arguments is unknown, add a double ** before


the parameter name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Return Values

A function that returns a value is called as fruitful function. To let a


function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Lambda function:

A lambda function is a small anonymous function. The power of lambda is


better shown when you use them as an anonymous function inside
another function.
A lambda function can take any number of arguments, but can only have
one expression.

Syntax
lambda arguments : expression

The expression is executed and the result is returned:

Example

Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:

Example

Multiply argument a with argument b and return the result:

x = lambda a, b : a * b
print(x(5, 6))

Void function:

A function that do not return any value is called void function.

E.g.,

# Creation of Function
function add_v(a, b);
c = a + b;
print(c);
end

# Function Call
add_v(3, 4)

Variable scope and lifetime:

The part of a program where a variable is accessible is called as scope, and the
duration for which the variable exists its lifetime.

There are two types of scope: 1) Global 2) Local

A variable which is defined in the main body of a file is called a global variable. It will
be visible throughout the file, and also inside any file which imports that file.
A variable which is defined inside a function is local to that function. It is accessible
from the point at which it is defined until the end of the function, and exists for as
long as the function is executing. If we want to access the global value for a variable
inside a function we need to use global keyword.

E.g.,

def myfunc():

global x

print(x)

x = 300

print(x)

x=12

myfunc()

print(x)

Output:

12

300

300

Python Modules

Module is like a code library which is a file containing a set of functions


you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file
extension .py:

Example

Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)
Use a Module

Now we can use the module we just created, by using


the import statement:

Example

Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Chandrajit")

Variables in Module

The module can contain functions, as already described, but also variables
of all types (arrays, dictionaries, objects etc):

Example

Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Re-naming a Module

You can create an alias when you import a module, by using


the as keyword:

Example

Create an alias for mymodule called mx:


import mymodule as mx

a = mx.person1["age"]
print(a)

Import From Module

You can choose to import only parts from a module, by using


the from keyword.

E.g., from mymodule import submodulename

Commonly used modules:

Python Built-in Modules

As we know that the Python interactive shell has a number of built-in functions. As a

shell start, these functions are loaded automatically and are always available, such

as,

 print() and input() for I/O,


 Number conversion functions such as int(), float(), complex(),
 Data type conversions such as list(), tuple(), set(), etc.

In addition to these many built-in functions, there are also a large number of pre-

defined functions available as a part of libraries bundled with Python distributions.

These functions are defined in modules which are known as built-in modules.

These built-in modules are written in C language and integrated with the Python

shell.

To display a list of all of the available modules in Python Programming Language,

we can use the following command in the Python console:

help('modules')

The output to the above code is shown below:


Some of the useful and frequently used built-in modules of Python.

 Math Module
 Random Module
 Datetime Module
 Statistics Module

Working with Math Module of Python

math.ceil() Rounds a number up to the nearest integer


math.cos() Returns the cosine of a number

math.cosh() Returns the hyperbolic cosine of a number

math.dist() Returns the Euclidean distance between two points (p and q), wher
point

math.exp() Returns E raised to the power of x

math.factorial() Returns the factorial of a number

math.floor() Rounds a number down to the nearest integer

math.pow() Returns the value of x to the power of y

math.sin() Returns the sine of a number

math.sinh() Returns the hyperbolic sine of a number

math.sqrt() Returns the square root of a number

math.tan() Returns the tangent of a number

math.tanh() Returns the hyperbolic tangent of a number

math.trunc() Returns the truncated integer parts of a number

Math Constants

Constant Description

math.e Returns Euler's number (2.7182...)

math.pi Returns PI (3.1415...)


Python statistics Module

Statistics Methods

Method Description

statistics.harmonic_mean() Calculates the harmonic mean (central location)

statistics.mean() Calculates the mean (average) of the given data

statistics.median() Calculates the median (middle value) of the give

statistics.median_grouped() Calculates the median of grouped continuous da

statistics.median_high() Calculates the high median of the given data

statistics.median_low() Calculates the low median of the given data

statistics.mode() Calculates the mode (central tendency) of the g

statistics.pstdev() Calculates the standard deviation from an entire

statistics.stdev() Calculates the standard deviation from a sample

statistics.pvariance() Calculates the variance of an entire population

statistics.variance() Calculates the variance from a sample of data

Random Module

Python has a built-in module that you can use to make random numbers.

The random module has a set of methods:


Method Description

seed() Initialize the random number generator

getstate() Returns the current internal state of the random number generator

setstate() Restores the internal state of the random number generator

getrandbits() Returns a number representing the random bits

randrange() Returns a random number between the given range

randint() Returns a random number between the given range

choice() Returns a random element from the given sequence

choices() Returns a list with a random selection from the given sequence

shuffle() Takes a sequence and returns the sequence in a random order

sample() Returns a given sample of a sequence


random() Returns a random float number between 0 and 1

uniform() Returns a random float number between two given parameters

triangular() Returns a random float number between two given parameters, you c
specify the midpoint between the two other parameters

Python datetime module


Python Datetime module supplies classes to work with date and time. These
classes provide a number of functions to deal with dates, times and time
intervals.

Command Line Arguments in Python


The arguments that are given after the name of the program in the command line
shell of the operating system are known as Command Line Arguments. Python
provides various ways of dealing with these types of arguments. The three most
common are:
 Using sys.argv
 Using getopt module
 Using argparse module
Using sys.argv
The sys module provides functions and variables used to manipulate different parts
of the Python runtime environment. This module provides access to some variables
used or maintained by the interpreter and to functions that interact strongly with the
interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:
 It is a list of command line arguments.
 len(sys.argv) provides the number of command line arguments.
 sys.argv[0] is the name of the current Python script.

Example: Let’s suppose there is a Python script for adding two numbers and the
numbers are passed as command-line arguments.

# Python program to demonstrate

# command line arguments


import sys

# total arguments

n = len(sys.argv)

print("Total arguments passed:", n)

# Arguments passed

print("\nName of Python script:", sys.argv[0])

print("\nArguments passed:", end = " ")

for i in range(1, n):

print(sys.argv[i], end = " ")

# Addition of numbers

Sum = 0

# Using argparse module

for i in range(1, n):

Sum += int(sys.argv[i])

print("\n\nResult:", Sum)

Output:

$ python test.py 10 20

Total arguments passed:3

Name of Python script:test.py

10 20

Result: 30

You might also like