Python Topics:
1. Python Topics:
1.
Control
Statements or Control Structures
a.
Conditional
Statements or Decision Making Statement or Selection Statements
i) If statements
A.
Simple if
B.
Simple if
else
C.
elif
ladder
D.
Nested if
b.
Looping
statements or Iterative Statement
1.
for loop
2.
while loop
c.
Unconditional
statements or Loop control statement or Transfer statement
1.
break
2.
continue
3.
pass
2. Python Functions
A.
Function
& Types of functions
B.
Default
Arguments
C.
Scope of
variable (Local & Global)
D.
Lambda
function
E.
Recursive
function
F.
Modules (sys,
math, time, dir, help functions)
3. Python features
a. RegEx
b. Simple
Character matching
c. Special
Characters or special Sequences
d. Python
quantifiers or meta characters
e. Character
Classes
f.
Match Objects
g. Substituting (using sub()) & Splitting a string(using split())
h. Compiling regular expression
1.
Control Statements or Control Structures
·
Therefore, using the control flow statements can interrupt a
particular section of a program based on a certain condition.
a. Conditional Statements or Decision Making Statement or Selection
Statements
--------------------------------
·
The
Python if statement is a statement which is used to test(check) specified
condition is true or false
B. if - else statement
C. elif ladder statements
D. nested if statement
A. Simple
if statements
--------------------------
·
The
Python if statement is used to test(check) specified condition is true
·
Present
true part only
Syntax: ---------- if(condition): statements Working: ---------- step1:
check the given condition step2:
if the given condition is true than execute true part statement step3:
otherwise exit from if statements |
Flow chart:
|
#Program 1: To check The given number is Positive Using simple if
n=int ( input ("Enter input :"))
if n>0:
print ("The given number is Positive")
-------------------------
#Program 2: To check The given number is Negative Using simple if
n=int ( input ("Enter input :"))
if n<0:
print ("The given number is Negative")
**************************************************************
B.
if...else statements
-----------------------
·
The
Python if else statement is used to test(check) specified condition is true or
false
·
Present
true part & false only
Syntax: ------- if(condition): statements else: statements Working: ---------- step1:
check the given condition step2:
if the given condition is true than execute true part statement step3: otherwise execute else part statements |
Flow chart: |
n=int (input ("Enter input :"))
if n>0 :
print ("The given number is Positive")
else :
print ("The given number is Negative")
------------------------------------------------------------------------------------------------
#Program
2: Find Biggest in Two numbers
a=int ( input("Enter First input
:"))
b=int ( input("Enter Second input
:"))
if a>b :
print ("a is biggest")
else :
print ("b is biggest")
----------------------------------------------------------
#Program
3: Find Even or Odd number
n=int ( input("Enter input :"))
if (n%2)==0 :
print ("The given number is even")
else :
print ("The given number is odd")
----------------------------------------------------------
#Program
4: Find the given number is divisible by 7 or not
n=int ( input("Enter input :"))
if (n%7)==0 :
print ("The given number is divisible by 7")
else :
print ("The given number is not divisible by 7")
----------------------------------------------------------
******************************************************
C.
elif ladder statements
-----------------------------
·
elif
ladder is used to check more than one condition (choice based execution)
Syntax: ---------- if (condition1): statement1 elif (condition2): statement2 elif (condition3): statements3 .... .... else:
statements Working: ---------- Step 1: To check the given
condition1, if condition1 is True than executes code statements1. Step 2: If condition1 is
not True, the program checks condition2.
If condition2 is True, it executes code statements2. Step 3: suppose all conditions are
false than. It executes else part statements |
Flow chart:
|
a=int(input("Enter First input :"))
b=int(input("Enter Second input
:"))
c=int(input("Enter Third input :"))
if a>b and a>c:
print ("a is biggest")
elif
b>c :
print ("b is biggest")
elif a==b and a==c and b==c:
print ("All are equals")
else:
print ("c is biggest")
---------------------------------
**********************************************
D. Nested if statements
----------------------------
·
if statement
inside another if statement.
Syntax: ---------- if (condition1): if
(condition2): statement1 else: statements2 else:
statement3 Working: ---------- Step 1: if (condition1): Executes when
condition1 is true Step 2: if (condition2): # Executes when
condition2 is true |
Flow chart |
#Program
1: Using Nested If
a=int(input("Enter First input :"))
b=int(input("Enter Second input
:"))
c=int(input("Enter Third input :"))
if a>b:
if
a>c:
print ("a is biggest")
else:
print ("c is biggest")
else:
if
b>c :
print ("b is biggest")
else:
print ("c is biggest")
------------------------------------------
*************************************************************
b.
Python Looping statements or Iterative
Statements
-------------------------------------------
·
In
general, statements are executed sequentially: The first statement in a
function is executed first followed by the second, and so on. There may be a
situation when you need to execute a block of code several number of times.
·
A loop
statement allows us to execute a statement or group of statements multiple
times
There are Two Types looping statements in Python
1. for loop
2. while loop
1) for
loop
-----------
-
for loop
is an entry controlled loop
-
Executes
a sequence of statements multiple times based on condition
Syntax: ---------- for
<variable> in <sequence>: Statement1 #Body of for Statement2 Statement3 Working: ------------ step1:
initialized the given variable step2: check the given condition step3:
if the given condition is true than execute statement otherwise exit from for
loop step4:
next goto increment part step5:
repeat step1, step2 and step3 |
Flow chart
|
#Program
1: using for loop
n = int (input (“Enter the value of n:”))
for i in range (1, n+1, 1):
print(i)
----------------------------------------
#Program
2: Find factorial value using for loop
n = int (input (“Enter the value of
n:”))
f = 1
for i in range (1, n+1, 1):
f
= f * i
print (“Factorial value is:”, f)
----------------------------------------
2)
while loop
---------------
·
while
loop is an Entry controlled loop
·
Repeats a
statement or group of statements while a given condition is TRUE.
Syntax: ---------- while
(condition): Statement1 #Body of for Statement2 Statement3 Working: ------------ step1:
initialized the given variable step2: check the given condition step3:
if the given condition is true than execute statement otherwise exit from for
loop step4:
next goto increment part step5:
repeat step1, step2 and step3 |
Flow chart
|
#Program
1: using while loop
n = int (input (“Enter the value of n:”))
i = 1
while (i <= n):
print(i)
i = i + 1
----------------------------------------
#Program
2: Find factorial value using while loop
n = int (input (“Enter the value of
n:”))
f = 1
while (i<=n):
f
= f * i
i
= i + 1
print (“Factorial value is:”, f)
----------------------------------------
******************************************************
c. Unconditional
Statements or Transfer statements or Loop Control statements
·
Loop control
statements change execution from their normal sequence.
Types of Unconditional statements
1. break
2. continue
3. pass
---------------
·
Exit from
looping statements like for and while loop
Syntax: (using for) -------- for
<variable> in <sequence>: if (condition): break Statements |
Syntax: (using while) --------
while <expression>:
Statements #Body
if (condition):
break |
n = int (input (“Enter the value of
n:”))
for i in range (1, n+1, 1):
if (i==5):
break
print(i)
----------------------------------------
#Program
2: using break
n = int (input (“Enter the value of n:”))
i = 1
while (i <= n):
if (i==5):
break
print(i)
i = i + 1
----------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2. continue statement:
----------------------
·
Ignore or
skip current iteration of the looping statements
Syntax: (using for) -------- for
<variable> in <sequence>: if (condition): continue Statements |
Syntax: (using while) --------
while <expression>:
Statements #Body
if (condition):
continue |
n = int (input (“Enter the value of
n:”))
for i in range (1, n+1, 1):
if (i==5):
continue
print(i)
----------------------------------------
#Program
2: using break
n = int (input (“Enter the value of n:”))
i = 1
while (i <= n):
if (i==5):
continue
print(i)
i = i + 1
----------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3. Pass statement
----------------
·
In
Python, 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. It is same as the name
refers to.
·
It just
makes the control to pass by without executing any code.
·
If we
want to bypass any code pass statement can be used.
Syntax: (using for) -------- for
<variable> in <sequence>: if (condition): pass Statements |
Syntax: (using while) --------
while <expression>:
Statements #Body
if (condition):
pass |
n = int (input (“Enter the value of
n:”))
for i in range (1, n+1, 1):
if (i==5):
print ("Pass when value is",i)
print (i)
*******************************************************
2. Python Function
A. Function:
----------------
·
A
Function is a self-block of code or small piece of code.
·
A
Function is a subprogram that works on data and produces some output.
---------------------------
- Code
Reusability
-
Reduced size of our program
- To
avoid complexity of our program
- Easy
to find error (bugging) and remove error (debugging)
Types
of Functions
--------------------------
1. Pre-Defined
Function
--------------------------
§ Pre-Defined also called as In-build function
or Library function or readymade function
§ Already compiled and executable code (build
into python)
ex: input(), print()
2. User
defined Function
---------------------------
§ user can create own Function (to perform
particular task)
§ a small piece of code or block of code or set
of code written by user
§ Function blocks begin with the keyword def followed by the
function name and parentheses ().
Syntax: (creating a function)
def function_name (parameters):
statements
statements
return [expression]
#function Definition
def msg():
print ("welcome to python")
#function Calling
msg()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program
2: Example program for user defined function
#function Definition
def msg():
a=10
b=20
c=a+b
print ("Result is : ",c)
#function Calling
msg();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program
3: Example program for user defined function
#function Definition
def msg():
a=int(input(“Enter
a :”))
a=int(input(“Enter b :”))
c=a+b
print ("Result is : ",c)
#function Calling
msg();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program
4: Example program for user defined function – Passing Arguments
#function Definition
def msg(a,b):
c=a+b
print ("Result is : ",c)
#function Calling
msg(10,20);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def simple (p,n,r):
si=p*n*r/100
return(si)
p=int(input("Enter value of p :"))
n=int(input("Enter value of n:"))
r=int(input("Enter value of r:"))
si=simple(p,n,r);
print ("result is:",si);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
B. Default
Arguments in Python
--------------------------------------
·
Python allows
function arguments to have default values. If the function is called without
the argument, the argument gets its default value.
Syntax:
--------
def function_name(param1,
param2=default_value2, param3=default_value3):
statements
statements
#function Definition
def msg(a=10, b=20, c=30):
d=a+b+c
print(d)
msg()
msg (1)
msg (1,2)
msg (1,2,3)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C. Scope
of variable:
---------------------
-
Scope of
a variable can be determined by the part in which variable is defined.
-
Each
variable cannot be accessed in each part of a program.
There are two types of variables based on
Scope:
1)
Local Variable.
2)
Global Variable.
1) Local
Variable:
-----------------
- Variables declared inside a function body
is known as Local Variable.
- These have a local access thus these
variables cannot be accessed outside the function body
in
which they are declared.
# Program 1: Example Program for local scope
def msg():
a=10
print ("Value of a is",a)
msg()
#print (a) #it will show error since variable
is local
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2) Global
variable:
------------------
- Variable defined outside the function is
called Global Variable.
- Global variable is accessed all over
program thus global variable have widest accessibility.
# Program 2: Example Program for global scope
b=20
def msg():
a=10
print ("Value of a is",a)
print ("Value of b is",b)
msg()
print (b)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~``
D. Lambda or Anonymous Functions:
----------------------------------------------
·
These
functions are called anonymous (Nameless) 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.
·
Anonymous
Functions are created by using a keyword "lambda".
·
Lambda
takes any number of arguments and returns an evaluated expression.
·
Lambda is
created without using the def keyword.
Syntax:
---------
lambda arg1, args2, args3,….,args_n :
expression
# Program 1: Program for lambda
square=lambda x1: x1*x1
print ("Square of number
is",square(10))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Program 2: Program for lambda (passing two arguments)
x=lambda a,b : a+b # two arguments
print("Result is : ",x(10,20))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Program 3: Program for lambda (passing three arguments)
res=lambda x,y,z :x+y+z # two arguments
print("Result is : ",res(10,20,30))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~``
E. Recursive Function:
-----------------------
-Function can call itself
Syntax:
--------
def
msg(args):
....
msg(args)
.....
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Program
1: Example Program for Recursive
def fact (x, f):
if
x>0:
f = f * x
x = x - 1
fact (x, f)
else:
print ("Factorial is :",f)
n=int (input ("Enter the value of n
:"))
msg (n,1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
F. Python
Modules
-----------------------
-
Modules
refer to a file containing Python statements and definitions.
-
Modules
are used to categorize code in Python into smaller part.
-
A module
is simply a file, where classes, functions and variables are defined.
-
Grouping
similar code into a single file makes it easy to access.
#import
import def1
def1.msg()
#def1.py
def msg():
print("welcome")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python
standard modules
1. sys module
2 math module
3. time module
4. dir function
5. help function
1.
Python
sys module
The python sys module
provides functions and variables which are used to manipulate different parts
of the Python Runtime Environment. It lets us access system-specific parameters
and functions.
1)
import
sys:
First, we have to import the sys module in our program before running any
functions.
2)
sys.modules:
This function provides the name of the existing python modules which have been
imported.
3)
sys.argv:
This function returns a list of command line arguments passed to a Python
script. The name of the script is always the item at index 0, and the rest of
the arguments are stored at subsequent indices.
4)
sys.base_exec_prefix:
This function provides an efficient way to the same value as exec_prefix. If
not running a virtual environment, the value will remain the same.
5)
sys.base_prefix:
It is set up during Python startup, before site.py is run, to the same value as
prefix.
6)
sys.byteorder:
It is an indication of the native byteorder that provides an efficient way to
do something.
7)
sys.maxsize:
This function returns the largest integer of a variable.
8)
sys.path:
This function shows the PYTHONPATH set in the current system. It is an
environment variable that is a search path for all the python modules.
9)
sys.stdin:
It is an object that contains the original values of stdin at the start of the
program and used during finalization. It can restore the files.
10)
sys.getrefcount:
This function returns the reference count of an object.
11)
sys.exit:
This function is used to exit from either the Python console or command prompt,
and also used to exit from the program in case of an exception.
12)
sys
executable: The value of this function is the absolute path to a
Python interpreter. It is useful for knowing where python is installed on
someone else machine.
13)
sys.platform:
This value of this function is used to identify the platform on which we are
working.
2. Python math module
Python has a built-in
math module. It is a standard module, so we don't need to install it
separately. We only have to import it into the program we want to use. We can
import the module, like any other module of Python, using import math to
implement the functions to perform mathematical operations.
Ex1:
(square root)
import math
print(math.sqrt( 9 ))
Ex2:
(pow)
import math
print(math.pow(10,2))
Ex3:
(ceil and floor & pi)
import
math
x
= math.ceil(1.4)
y
= math.floor(1.4)
print(x)
# returns 2
print(y)
# returns 1
print(math.pi)
Ex4:
(sin, cos, tan)
import
math
print(math.sin(90))
print(math.cos(90))
print(math.tan(90))
Ex5:
(log, log10, log2)
import
math
print(math.log(1))
print(math.log10(2))
print(math.log2(2))
Ex6:
(radians)
import
math
print(math.radians(180))
Ex7:
(degrees)
import
math
print(math.degrees(1))
3.
Python
time module
The time module comes with Python’s standard utility module, so there is no need to install it externally. It allows functionality like getting the current time, pausing the Program from executing
Ex1:
(get the current time)
import time
print(time.localtime(time.time()))
Ex2:
(get gmt time)
import
time
print(time.gmtime(0)
Ex3:
Display calendar
import
calendar
cal
= calendar.month(2022, 6)
print(cal)
calendar.prcal(2022)
4. Python dir function
§ This
function will return all the properties and methods, even built-in properties
which are default for all object.
Syntax:
dir(object)
Ex1:
using dir function
lang = ("C","C++","Java",
"Python")
att = dir(lang)
print(att)
Output:
5.
Python
help function
The Python help
function is used to display the documentation of modules, functions,
classes, keywords, etc.
Syntax:
help(object)
Ex1:
using help function
help(print)
Ex2:
using help function
help(input)
************************************************
1.
PYTHON RegEx – Character Matching
a.
RegEx
b.
Simple Character matching
c. Special Characters or special Sequences
d.
Python quantifiers or meta characters
e.
Character Classes
f.
Match Objects
g.
Substituting (using sub()) & Splitting
a string(using split())
h.
Compiling regular expression
RegEx
·
A RegEx, or Regular Expression, is a
sequence of characters that forms a search pattern.
·
RegEx can be used to check if a string
contains the specified search pattern
RegEx
Functions(Simple character matching function)
The re module
offers a set of functions that allows us to search a string for a match:
Function |
Description |
Returns a list containing all matches |
|
Returns a Match
object if there is a match anywhere in the string |
|
Returns a list where the string has been
split at each match |
|
Replaces one or many matches with a
string |
RegEx
Module
Python has a built-in
package called re, which can be used to work with Regular Expressions.
Import
the re module:
import re
Ex1:
(using findall())
import
re
txt
= "Python is used for data analysis"
x
= re.findall("data", txt)
print(x)
Ex2:
(using search())
import
re
txt
= " Python is used for data analysis"
x
= re.search("Python", txt)
print(x)
Ex3:
(using split())
import
re
#Split
the string at every white-space character:
txt
= " Python is used for data analysis"
x
= re.split("\s", txt)
print(x)
Ex4:
(using sub())
import re
txt
= "Python is used for data analysis"
x =
re.sub("\s", "9", txt)
print(x)
Metacharacters or Python
Quantifiers
Metacharacters are characters with a special
meaning:
Character |
Description |
Example |
[] |
A
set of characters |
"[a-m]" |
\ |
Signals
a special sequence (can also be used to escape special characters) |
"\d" |
. |
Any
character (except newline character) |
"he..o" |
^ |
Starts
with |
"^hello" |
$ |
Ends
with |
"planet$" |
* |
Zero
or more occurrences |
"he.*o" |
+ |
One
or more occurrences |
"he.+o" |
? |
Zero
or one occurrences |
"he.?o" |
{} |
Exactly
the specified number of occurrences |
"he.{2}o" |
| |
Either
or |
"falls|stays" |
() |
Capture
and group |
|
Python
special Characters or Special Sequences
The
characters which have some unique functionality, such characters are called
special characters. A
special sequence is a \ followed
by one of the characters in the list below, and has a special meaning:
Character |
Description |
Example |
\A |
Returns a match if the specified characters
are at the beginning of the string |
"\AThe" |
\b |
Returns a match where the specified
characters are at the beginning or at the end of a word (the "r" in
the beginning is making sure that the string is being treated as a "raw
string") |
r"\bain" |
\B |
Returns a match where the specified
characters are present, but NOT at the beginning (or at the end) of a word (the
"r" in the beginning is making sure that the string is being
treated as a "raw string") |
r"\Bain" |
\d |
Returns a match where the string contains
digits (numbers from 0-9) |
"\d" |
\D |
Returns a match where the string DOES NOT
contain digits |
"\D" |
\s |
Returns a match where the string contains a
white space character |
"\s" |
\S |
Returns a match where the string DOES NOT
contain a white space character |
"\S" |
\w |
Returns a match where the string contains
any word characters (characters from a to Z, digits from 0-9, and the
underscore _ character) |
"\w" |
\W |
Returns a match where the string DOES NOT
contain any word characters |
"\W" |
\Z |
Returns a match if the specified characters
are at the end of the string |
"Spain\Z" |
Ex1:
(using special sequences)
import re
txt
= "The Python is used for data analysis"
#Check if the string starts with
"The":
x = re.findall("\Ahe", txt)
print(x)
Ex2:
(using special sequences)
import re
txt
= "The Python is used for data analysis"
#Check if the string contains any digits
(numbers from 0-9):
x = re.findall("\d", txt)
print(x)
Ex3:
(using special sequences)
import re
txt
= "The Python is used for data analysis"
#Return a match at every white-space
character:
x = re.findall("\s", txt)
print(x)
Sets or Character classes
A set is a set of characters inside a pair of
square brackets [] with a special meaning:
Set |
Description |
[arn] |
Returns
a match where one of the specified characters (a, r, or n) is
present |
[a-n] |
Returns
a match for any lower case character, alphabetically
between a and n |
[^arn] |
Returns
a match for any character EXCEPT a, r, and n |
[0123] |
Returns
a match where any of the specified digits (0, 1, 2, or 3) are
present |
[0-9] |
Returns
a match for any digit between 0 and 9 |
[0-5][0-9] |
Returns
a match for any two-digit numbers from 00 and 59 |
[a-zA-Z] |
Returns
a match for any character alphabetically between a and z,
lower case OR upper case |
[+] |
In
sets, +, *, ., |, (), $,{} has no special
meaning, so [+] means: return a match for any + character
in the string |
Ex1:
(using character classes)
import re
txt = "8 times before 11:45 AM"
#Check if the string has any digits:
x = re.findall("[0-9]", txt)
print(x)
Ex2:
(using character classes)
import re
txt = "8 times before 11:45 AM"
#Check if the string has any characters
from a to z lower case, and A to Z upper case:
x = re.findall("[a-zA-Z]", txt)
print(x)
Ex3:
(using character classes)
import re
txt = "The rain in Spain"
#Check if the string has any a, r, or n
characters:
x = re.findall("[arn]", txt)
print(x)
Match Objects
A Match Object is an object containing
information about the search and the result.
1) .span()
returns a tuple containing the start-, and
end positions of the match.
2) .string
returns the string passed into the function
3) .group()
returns the part of the string where there
was a match
Ex1:
(using span())
import
re
#Search
for an upper case "S" character in the beginning of a word, and print
its position:
txt
= "The rain in Spain"
x
= re.search(r"\bS\w+", txt)
print(x.span())
Ex2:
(using string())
import
re
#The
string property returns the search string:
txt
= "The rain in Spain"
x
= re.search(r"\bS\w+", txt)
print(x.string)
Ex3:
(using group())
import
re
#Search
for an upper case "S" character in the beginning of a word, and print
the word:
txt
= "The rain in Spain"
x
= re.search(r"\bS\w+", txt)
print(x.group())
Compiling Regular
Expression
§ combine
a regular expression pattern into pattern objects, which can be used for
pattern matching.
§ It
also helps to search a pattern again without rewriting it.
Syntax:
re.compile(pattern,
repl, string):
Ex1: (using compile())
import
re
pattern=re.compile('data')
result=pattern.findall('The
Python is used for data analysis')
print
(result)
result2=pattern.findall('Pyton
is most popular data analysis tool')
print
(result2)
**************************
No comments:
Post a Comment