Python Tutorial for Beginners

Python Tutorial for Beginners, Python Programming Environment Setup, Python Language Fundamentals, and Python Object-Oriented Programming.

Python Programming Syllabus

Python Language Tutorial

Introduction to Python Language

Download & Install Python

Python Language Syntax

Variables and Data Types in Python

Python Operators

Python Control Flow – Decision Making

Python Control Flow – Looping

Python Control Flow – Branching

Python Numbers

Python Strings

Python Lists

Python Tuples

Python Sets

Python Dictionaries

Python Arrays

Python user-defined Functions

Python Built-in Functions

Python – Modules

Python User Input

Python File Handling

Python Exceptions Handling

Python Classes and Objects

Python Methods

Python Constructors

Python Inheritance

Python Polymorphism

Python Abstraction

Python Encapsulation

Regular Expressions

Database Access

Python Multithreading

Python Networking Programming

Python CGI (Common Gateway Interface. Programming

Python GUI Programming


1.Introduction to Python Language

What is Python?

Python is a general-purpose, high-level, interpreted, interactive, object-oriented, open-source programming language.

Python was created by Guido Van Rossum in 1989, but publicly released in 1991, It is further developed by the Python Software Foundation, and Python official website is (python.org).

Key features of Python Language

Free and Open Source

Object-Oriented Language

Easy to Learn and Use

Cross-platform Language:

Integrated

Implementation of Python

CPython: The default implementation of the Python programming language is CPython.

IronPython: Python running on .NET

Jython: Python running on the Java Virtual Machine

PyPy: A fast Python implementation with a JIT compiler

Stackless Python: Branch of CPython supporting micro-threads

MicroPython: Python running on microcontrollers

Anaconda Python: Anaconda is a free and open-source distribution of the Python and R programming languages for scientific computing.

Applications of Python Language

Python is used to develop:

Desktop GUI (Graphical User Interface)

Web and Internet Development (IoT – Internet of Things)

Games and 3D Graphics

Scientific and Numeric Applications

Machine Learning and Artificial Intelligence

Data Science and Data Visualization

Enterprise Applications (Such as e-commerce, ERP, and many more.)

Network Programming

Embedded Applications

Audio and Video Applications

Education

CAD (Computer-Aided Designing) Applications

Software Testing / Writing automated tests

Python for DevOps / System administration / Writing automation scripts.

Drawbacks of Python Language

1. Python has a slow speed of execution.

2. Python language is seen as less suitable for mobile development and game development.

3. Python has high memory consumption and is not used in web browsers because it is not secure.

4. Python’s database access layer is primitive and underdeveloped.

5. Python is a dynamically typed language so the data type of a variable can change anytime.


2. Download & Install Python

Python Programming Environment is required to write and execute/run Python programs,

• First, we need to download and install the Python interpreter from Python’s website python.org.

• Download Python Software (You operating system compatible Python software) from Python’s website python.org,

• Install Python…

• After Python installation, launch Python IDLE (Integrated Development and Learning Environment) from the start menu, and write Python statements & execute/run.

First Python Program:

x=123
y=234

print (x+y) # It will print 357

Modes of Programming in Python:

1. Iterative Mode
2. Script Mode

Note:

Python IDLE (Integrated Development and Learning Environment) is best for learning Python language, and PyCharm IDE is best for working (real-time)

You can get Python IDLE after the installation of Python, but you need to download & install PyCharm IDE.


3. Python Language Syntax

Moded of Python Programming:

Python has two modes of programming,

a. Interactive Mode: Interactive mode provides us with a quick way of running blocks or a single line of Python code.

b. Script/File Mode: In script mode, You write your code in a text file then save it with a .py extension which stands for “Python”.

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_)

Reserved Words / Keywords

Reserved words (also called keywords) are defined with predefined meaning and syntax in the language. These keywords have to be used to develop programming instructions. Reserved words can’t be used as identifiers for other programming elements like the name of variable, function, etc.

Lines and Indentation

a. Lines
A Python program is divided into a number of logical lines and every logical line is terminated by the token NEWLINE.

Split a Logical line into multiple physical lines using Semicolon (;) and Join multiple physical lines into one logical line using (\)

b. Indentation
Where in other programming languages the indentation in code is for readability only, in Python the indentation is very important.

Python uses indentation to indicate a block of code.

Correct Syntax:
if 5 > 2:
print(“Five is greater than two!”)

Incorrect Syntax:
if 5 > 2:
print(“Five is greater than two!”)

Comments in Python

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

Note: You can type a comment on the same line after a statement.

Quotation in Python:

Python accepts single (‘), double (“) and triple (”’ or “””) quotes to denote string literals, as long as the same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines.


4. Variables and Data Types in Python

No Explicit declaration of Data Types and Variables in Python Programming.

What is a Variable?

A named memory location to store the temporary data within a program, the variable value may vary throughout the program, and Variables store in primary memory RAM.

Implicit declaration of Data types in Python means no data type specification before declaring the variable.

Ex:
a=10

Suppose in Java explicit declaration of data types…

Ex:
int a=10
or
int a

Implicit declaration of Data Types in Python means we no need to declare variables with a Data Type, we can use them directly.

Ex:
num=100

What is Data Type?

A data type in programming is a classification that specifies which type of value a variable has and what type of mathematical, relational, or logical operations can be applied to it without causing an error.

Example:
Alfa bytes, Numbers, Boolean values, etc.

Assign values to variables…

counter=10 # An Integer Assignment
distance=20.45 # A Floating Point
name= “Ramu” # A String

print (counter)
print (distance)
print (name)

Verify Data Types:

Using type(); command we can check the type of data that a variable hold.

a=1
type(a)
It returns int…

b=2.23
type(b)
It returns float…

c=”abcd”
It returns str…

Multiple Assignment

Python allows us to assign a single value to several variables simultaneously.

Ex:
a=b=c=1
print (a, b, c)

We can also assign multiple values to multiple variables.

a, b, c=1, 2.2, “John”
print (a)
print (b)
print (c)

Delete a Variable

We can also delete a variable using the del command…

a=123
print (a)

del(a)
print(a) # It will show an error

Standard Data Types in Python:

Python has five standard data types –

Number
String
List
Tuple
Dictionary


5. Operators in Python Language

Operators are used to performing Arithmetic, Comparison, and Logical Operations…

Important categories of operators in Python:

a. Arithmetic Operators
b. Comparison (Relational) Operators
c. Assignment Operators
d. Logical Operators
e. Identity Operators
f. Bitwise Operators

a. Python Arithmetic Operators

i. + Addition (Example: 10 + 20) = 30
ii. – Subtraction (Example: 10 – 20) = -10
iii. * Multiplication (Example: 10 * 20) = 200
iv. / Division (Example: 20/10) = 2
v. % Modulus (Example: 20 % 10) = 0
vi. ** Exponent (Example: 10 ** 20) =

Examples:

a=10
b=20
c=3

print (a+b)
print (a-b)
print (a*b)
print (a/c)
print (b%a)
print (a**c)
print (a//c)

Output:
30
-10
200
3.3333333333333335
0
1000
3

b. Python Comparison (Relational) Operators

i. ==
ii. !=
iii. >
iv. <
v. >=
vi. <=

Example:

a=10
b=20

print (a == b)
print (a != b)
print (a > b)
print (a < b)
print (a >= b)
print (a <= b)

Output:
False
True
False
True
False
True

c. Python Assignment Operators

i. = Equal to
ii. += Add And
iii. -= Subtract And
iv. *= Multiply And
v. /= Divide And
vi. %= Modula And
vii. **= Exponent And
viii. //= Floor Division And

Examples:

a=10
b=3
print (a)
print (b)

a += b
print (a)

a -=b
print (a)

a *=b
print (a)

a /=b
print (a)

a **=b
print (a)

a //=b
print (a)

Output:
10
3
13
10
30
10.0
1000.0
333.0

d. Python Logical Operators

i. and (Logical And)
ii. or (Logical Or)
iii. Not (Logical Not)

Examples:
x=’true’
y=’false’

print (x and y) # false

print (x or y) # true

print (not x) # false

e. Python Identity Operators

i. is
ii. is not

Examples:

x1 = 5
y1 = 5

print (x1 is not y1) # false

print (x1 is y1) # true


6. Python Control Flow – Decision Making

Decision Making or Conditional Statements are part of control flow statements in computer programming,

Computer programming control flow statements
a. Conditional Statements
b. Loop Statements
c. Branching Statements

In Python language also these three types of statements are there, but we have only one conditional statement in Python.

If Statement

Note: No Switch statement in Python Language, ‘if’ statement only.

Usage of Conditional Statements / Decision-Making Statements

1. Execute a block of Statements when a condition is true.

Syntax:

if (Condition/Expression):
Statement/s

Example:

a, b = 100, 50
if (a>b):
print (“A is a Big Number”)

a, b = 100, 50
if (a>b):
print (“A is a Big Number”)
print (“Hello Python”)

2. Execute a block of Statements when a compound condition is true

Syntax:
if ((condition1/Expression1) and (Condition2/Expression2)) :
Statement/s

Example:
a, b, c = 100, 50, 700
if ((a>b) or (a>c)):
print (“A is a Big Number”)

3. Execute a block of Statements when the condition is true otherwise execute another block of Statements

Syntax:
if (Condition):
Statement/s
else:
Statement/s

Example:

a, b = 100, 200
if (a>b):
print (“A is a Big Number”)
else :
print (“B is a Big Number”)

4. Decide among several alternates(elif)

Syntax:

if (condition):
Statement/s
elif (condition):
Statement/s
elif (condition):
Statement/s
else:
Statement/s

Example:
Initialize an Integer Variable and verify the range

If the number is in between 1 and 100 then display “Number is a Small Number”
If the number is in between 101 and 1000 then display “Number is a Medium Number”
If the number is in between 1001 and 10000 then display “Number is a Big Number”
If the number is more than 10000 then display “Number is a High Number”
Otherwise, display “Number is either Zero or Negative Number”

Python Program:

a=0
if ((a>=1) and (a<=100)):
print (“A is a Small Number”)
elif ((a>100) and (a<=1000)):
print (“A is a Medium Number”)
elif ((a>1000) and (a<=10000)):
print (“A is a Big Number”)
elif (a>10000):
print (“A is a High Number”)
else:
print (“A is either Zero or Negative Number”)

5. Execute a block of Statements when more than one condition is true (Nested if)

Syntax:
if (condition):
if (condition):
if (condition):
Statements
————–
————–

Example:
Initialize a, b, c, and d variables (Integer variables), check if the variable
is bigger than the other three variables or not?

a, b, c, d = 100, 90, 70, 500

if (a>b):
if (a>c):
if (a>d):
print (“A is a Big Number”)
else :
print (“A is Not a Big Number”)
————————-
a, b, c, d = 100, 909, 70, 50

if (a>b):
if (a>c):
if (a>d):
print (“A is a Big Number”)
else :
print (“A is Not a Big Number “+ “3rd Condition is not true”)
else :
print (“A is Not a Big Number “+ “2nd Condition is not true”)
else :
print (“A is Not a Big Number “+ “1st Condition is not true”)

Using Compound Condition

a, b, c, d = 100, 90, 70, 50

if ((a>b) and (a>c) and (a>d)):
print (“A is a Big Number”)
else:
print (“A is Not a Big Number”)

Nested if Condition vs. Compound Condition

In Nested if condition we can write multiple else parts, whereas in Compound
The condition we can write a single else part only.

Problem: Find the biggest variable (Integer variables) among four variables

Use Compound Condition and else if…

a, b, c, d = 100, 90, 70, 50

if ((a>b) and (a>c) and (a>d)):
print (“A is a Big Number”)
elif ((b>a) and (b>c) and (b>d)):
print (“B is a Big Number”)
elif ((c>a) and (c>b) and (c>d)):
print (“C is a Big Number”)
else:
print (“D is a Big Number”)


7. Python Control Flow – Looping

In general, statements are executed sequentially in Computer programming,

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times.

Python programming language provides two loop structures,

1. while loop
2. for loop

1. while loop

It repeatedly executes statements while the condition is true…

Syntax:

while (condition/expression):
statement/s

Example 1: Print 1 to 10 Numbers.

a=1
while (a<=10):
print(a)
a=a+1

Output:
1
2
3
4
5
6
7
8
9
10

Example 2: Read a Number, and calculate sum, and Zero to quit from the loop

a=1
sum=0

print (“Enter a Number to add to the sum: “)
print (“Enter 0 to quit.”)

while a != 0:
print (“Current Sum: “, sum)
a= float(input(“Enter Number: “))
a=float(a)
sum += a
print(“Total Sum is: “, sum)

Example 3: Print 1 to 5 Numbers in reverse order…

val=5
while (val >= 1):
print(val)
val = val-1

Output:
5
4
3
2
1

2. for loop

for loop iterates over the items of any sequence, such as a list or a string.

Syntax:

for iterating_var in sequence:
statement/s

Example 1:

a= [2, 4, 6, 8, 10, 12, 14]

for num in a:
print(num)

Output:
2
4
6
8
10
12
14

Example 2:

for num in range(5):
print(num);

output:
0
1
2
3
4

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

Note: we can use conditional statements only in our script, or loop statements only, or we can insert loops in Conditional statements and vice versa.


String Handling in Python

What is String?

The string is a sequence of characters written in single quotes or in double-quotes or three double-quotes.

Examples:
string1= ‘This is a single-quoted string’
string2= “This is double-quoted string”
string3= “””This is triple quoted-string”””
print (string1)
print (string2)
print (string3)

The string may have Alphabets, Numbers, and Special Characters

Examples:
a=”India”
b= “100”
c =”India123″
d =”*&%$”
e = “123*&%$”
f =”India123*&%$”
g=”Selenium With Java”

print (a)
print (b)
print (c)
print (d)
print (e)
print (f)
print (g)

How to use quotation marks in Strings?

Examples:
string1 =’Hello Python Don’t’
string2 =”Python” Strings”
print (string1)
print (string2)

use Forward Slash (/) to avoid Syntax errors…

string1 =’]Hello Python Don\’t’
string2 =”Python\” Strings”
print (string1)
print (string2)

Important Operations on Strings…

1. Finding String length

string1 =”Hello Python”;
print (len(string1));

2. Concatenating Strings

string1 =”Hello ”
string2=”Python”
print (string1 + string2)

string1 =”Hello ”
num=100
print (string1 + str(num))

3. Print a String multiple times

string1 =”Hello ”
print (string1 *10)

4. Check whether the String having all numeric characters?

string1 =”Hello”
print (string1.isnumeric()) # False

string2 =”Hello123″
print (string2.isnumeric()) # False

string3 =”12345″
print (string3.isnumeric()) # True

5. Check whether the String having all alphabetic characters?

string1 =”Hello”
print (string1.isalpha()) # True

string2 =”Hello123″
print (string2.isalpha()) # False

string3 =”12345″
print (string3.isalpha()) # False


Read User Input using Python

Python user input from the keyboard can be read using the input() built-in function. The input from the user is read as a string and can be assigned to a variable. After entering the value from the keyboard, we have to press the “Enter” button. Then the input() function reads the value entered by the user.

Syntax of input() Function:

input(prompt)

Example:

value = input(“Please enter a string:\n”)

print(f’You entered {value}’)

Read input – Python

Output: You entered Python


Python Lists

The sequence is the most basic data structure in Python, Each element of a sequence is assigned a number – its position or index. The first index is zero, the second index is one, and so forth.

Python has six built-in types of sequences, but the most common ones are Lists and Tuples.

The list is the most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. The important thing about a list is that items in a list need not be of the same type.

Examples:

list1 = [‘Java’, ‘Visual Basic’, 1997, 2000]
list2 = [10, 20, 30, 40, 50]
list3 = [“a”, “b”, “c”, “d”]

1. Accessing Values in Lists

To access values in lists, use the square brackets for slicing along with the index.

Examples:

abc = [“Selenium”, “UFT”, “SilkTest”, 100, 200, 300]
print (abc)
print (abc[1])

2. Updating Lists

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a ‘list’ with the append() method.

Examples:

list = [‘physics’, ‘chemistry’, 1997, 2000]

print (list)
print (list[2])
list[2] = 9999
print (list)
print (list[2])

3. Delete List Elements

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know.

Example:

list1 = [‘physics’, ‘chemistry’, 1997, 2000]

print (list1)
del (list1[2])
print (list1)

4. Built-in List Functions & Methods / Operations on Python Lists

i. len()
Gives the total length of the list.

Example:
list = [10, 20, 30, 40, 50]

print (len(list))

ii. max()
Returns item from the list with max value.

Example:

list = [10, 20, 30, 40, 50]

print (max(list))

iii. min()

Returns item from the list with min value.

Example:

list = [10, 20, 30, 40, 50]

print (min(list))

Methods with Description

i) append() method
.
Appends object obj to list

Example:
list = [10, 20, 30, 40, 50]

print(list)
list.append(70)
print(list)

ii. remove() method
Removes element from list by element value.

Example:

list = [10, 20, 30, 40, 50]

print(list)
list.remove(50)
print(list)

iii. reverse() method

Reverses elements of list in place

Example:

list = [10, 20, 30, 40, 50]

print(list)
list.reverse()
print(list)


Python Tuples

What is Tuple?
A tuple is a collection that is ordered and unchangeable. In Python, tuples are written with round brackets.

A Data Structure of Python or a Compound data type of Python language

Example

Create a Tuple:

fruits = (“apple”, “banana”, “cherry”)
print (fruits)

Operations on Tuples:

1. Access Tuple Items
2. Range of Indexes
3. Change Tuple Values
4. Loop Through a Tuple
5. Check if Item Exists
6. Find Tuple Length
7. Add Items
8. Remove Items
9. Join Two Tuples

1. Access Tuple Items

We can access tuple items by referring to the index number, inside square brackets:

Example

Print the second item in the tuple:

fruits = (“apple”, “banana”, “cherry”, “orange”, “kiwi”, “melon”, “mango”)
print(fruits [1])

Negative Indexing

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.

Example
Print the last item of the tuple:

fruits = (“apple”, “banana”, “cherry”, “orange”, “kiwi”, “melon”, “mango”)
print(fruits[-1])

2. Range of Indexes

We can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new tuple with the specified items.

fruits = (“apple”, “banana”, “cherry”, “orange”, “kiwi”, “melon”, “mango”)
print(fruits [2:5])

It will print: (‘cherry’, ‘orange’, ‘kiwi’)

Note: the item in position 5 is Not included

Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the tuple:

Example

fruits = (“apple”, “banana”, “cherry”, “orange”, “kiwi”, “melon”, “mango”)
print(fruits [-4:-1])

It will print: (‘orange’, ‘kiwi’, ‘melon’)
This example returns the items from index -4 (included) to index -1 (excluded)

3. Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable, but we can convert the tuple into a list, change the list, and convert the list back into a tuple.

Example

x = (“apple”, “banana”, “cherry”)
y = list(x)
y[1] = “kiwi”
x = tuple(y)

print(x)

4. Loop Through a Tuple

We can loop through the tuple items by using a for loop.

Example
Iterate through the items and print the values:

fruits= (“apple”, “banana”, “cherry”)
for x in fruits:
print(x)

5. Check if Item Exists

To determine if a specified item is present in a tuple,

Example

Check if “apple” is present in the tuple:

fruits = (“apple”, “banana”, “cherry”)

if “apple” in fruits:
print(“Yes, ‘apple’ is in the fruits tuple”)

6. Find Tuple Length

To determine how many items a tuple has, use the len() keyword

Example

fruits = (“apple”, “banana”, “cherry”)
print(len(fruits))

7. Add Items

Once a tuple is created, we cannot add items to it. Tuples are unchangeable.

fruits = (“apple”, “banana”, “cherry”)
fruits[3] = “orange” # This will raise an error
print(fruits)

8. Remove Items

Note: We cannot remove items in a tuple.

Tuples are unchangeable, so we cannot remove items from it, but we can delete the tuple completely:

Example

The del keyword can delete the tuple completely:

fruits = (“apple”, “banana”, “cherry”)
del fruits
print(fruits ) #this will raise an error because the tuple no longer exists

9. Join Two Tuples

To join two or more tuples you can use the + operator:

Example
Join two tuples:

tuple1 = (“a”, “b” , “c”)
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2
print(tuple3)


File Handling in Python

Python File Operations

Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files and Python treats files differently as text or binary.

open() function

We use open () function in Python to open a file in read or write mode. open () will return a file object, to return a file object we use open() function along with two arguments, that accept file name and the mode, whether to read or write.

In Python, a file operation takes place in the following order.

Open a file
Read or write (perform the operation)
Close the file

Syntax: open(filename, mode).

There are three kinds of mode, that Python provides and how files can be opened,

“r “, for reading.
“w”, for writing.
“a”, for appending.

“r+”, for both reading and writing

The mode argument is not mandatory. If not passed, then Python will assume it to be “r” by default.

File Handling Examples:

1. Read a File

The open() function returns a file object, which has a read() method for reading the content of the file:

Example

f = open(“sample.txt”, “r”)
print(f.read())

2. Read Only Parts of the File

Example
Return the 5 first characters of the file:

f = open(“sample.txt”, “r”)
print(f.read(5))

3. Read Lines

You can return one line by using the readline() method:

Example
Read one line of the file:

f = open(“sample.txt”, “r”)
print(f.readline())

4. Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

“a” – Append – will append to the end of the file

“w” – Write – will overwrite any existing content

Example

Open the file “sample.txt” and append content to the file:

f = open(“sample.txt”, “a”)
f.write(“Now the file has more content!”)
f.close()

#open and read the file after the appending:
f = open(“sample.txt”, “r”)
print(f.read())

5. Overwrite the content

Open the file “sample3.txt” and overwrite the content:

f = open(“sample3.txt”, “w”)
f.write(“Woops! I have deleted the content!”)
f.close()

#open and read the file after the appending:
f = open(“demofile3.txt”, “r”)
print(f.read())

6. Create a New File

To create a new file in Python, use the open() method, with one of the following parameters

“x” – Create – will create a file, returns an error if the file exist

Example

f = open(“myfile.txt”, “x”)

7. Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Example
#Remove the file “demofile.txt”:

import os
os.remove(“sample.txt”)


Python Modules

1. What is Python Module?
2. Purpose of Modules
3. Types of Modules
4. How to use Modules
5. User-defined Modules in Python

1. What is Python Module?

• A module is a file consisting of Python code. It can define functions, classes, and variables, and can also include runnable code. Any Python file can be referenced as a module.

• A file containing Python code, for example, test.py, is called a module, and its name would be tested..

Module vs. Function

Function: it’s a block of code that you can use/reuse by calling it with a keyword. Eg. print() is a function.

Module: it’s a .py file that contains a list of functions (it can also contain variables and classes). Eg. in statistics.mean(a), mean is a function that is found in the statistics module.

2. Purpose of Modules

• As our program grows more in the size we may want to split it into several files for easier maintenance as well as reusability of the code. The solution to this is Modules.

• We can define your most-used functions in a module and import it, instead of copying their definitions into different programs. A module can be imported by another program to make use of its functionality. This is how you can use the Python standard library as well.

3. Types of Modules

• Python provides us with some built-in modules, which can be imported by using the “import” keyword.

• Python also allows us to create our own modules and use them in our programs.

4. How to use Modules

Built-in modules are written in C and integrated with the Python interpreter.

Each built-in module contains resources for certain system-specific functionalities such as OS management, disk IO, etc.

>>> help(‘modules’)

There is a Python Standard Library with dozens of built-in modules. From those, five important modules,

random, statistics, math, datetime, csv

Python math module,

This contains factorial, power, and logarithmic functions, but also some trigonometry and constants.

i. import math

And then:

math.factorial(5)
math.pi
math.sqrt(5)
math.log(256, 2)

ii. import math as m

And then:

m.factorial(5)
m.pi
m.sqrt(5)
m.log(256, 2)

iii. from math import factorial

Here, we first call the from a keyword, then math for the module. Next, we use the import keyword and call the specific function we would like to use.

print (factorial(5))

iv. from math import *

print(factorial(5))
print(pi)
print(sqrt(5)
print(log(256, 2))

5. User-defined Modules in Python

i. Create a module

# A simple module, calc.py

price=1000

def add(x, y):
return (x+y)

def sub(x, y):
return (x-y)

def mul(x, y):
return (x*y)

ii. Use Module

# importing module calc.py

import calc

print calc.add(10, 2)

# from calc import mul

print(add(10, 2))


 

Python Videos

Python Fundametals Quiz

Python Interview Questions for Beginners

Follow me on social media: