SlideShare a Scribd company logo
INTRODUCTION
TO
PYTHON
PROGRAMMING
-By
Ziyauddin Shaik
Btech (CSE)
(PART - 1)
Contents
• What is Python?
• Uses, features & flavours of Python
• Running Python
• Identifiers
• key words
• values & types
• Type casting
• Operators
• Functions
• Types of arguments
What is Python?
Python is a simple, general purpose, high level, Dynamic, Interpreted and object-
oriented programming language.
Python was developed by Guido Van Rossam in 1989 while working at National
Research Institute at Netherlands.
But officially python was made available to public in 1991. The official Date of
Birth for python is: Feb 20th 1991.
Guido developed python program language by taking almost all programming
features from different languages:
1. Functional Programming Features from C.
2. Object Oriented Programming Features from C++.
Uses of Python:
We can use everywhere .The most common important Application
areas are:
1. For developing Desktop Applications.
2. For developing Web Applications.
3. For developing Database Applications.
4. For developing Network programming Applications.
5. For developing Games.
6. For Data Analysis Applications.
7. For Machine Learning.
8. For developing Artificial Intelligence Applications.
9. For IoT etc.
Features of Python:
1. Simple and easy to learn
2. Freeware and Open Source
3. High Level Programming Language
4. Platform Independent
5. Portability
6. Dynamically Typed
7. Both procedure Oriented and Object Oriented
8. Interpreted
9. Extensible
10. Embedded
11. Extensive Library
Versions of Python :
 Python 1.0 in Jan 1994.
Python 2.0 in Oct 2000.
Python 3.0 in Dec 2008.
Flavors of Python:
NO Flavor description
1 Cpython It is the standard flavor of Python. It can be used to work with C language
Applications.
2 Jython (or) Jpython It is for Java Applications. It can run on JVM.
3 IronPython It is for C#.Net Platform.
4 PyPy The main advantage of PyPy is performance will be improved because JIT
compiler is Available inside PVM.
5 RubyPython For Ruby Platforms
6 AnacondaPython It is specially designed for handling large volume of data processing.
We Run Python Script in the following
ways:
1.Interactive Mode
2.Command Line
3.IDE Mode
1. Interactive Mode:
To enter in an interactive mode,
you will have to open Command
Prompt on your windows machine and
type ‘python’ and press Enter.
Running Python :
2. Script Mode:
Using Script Mode, we can write our Python code in a separate file of any
editor in our Operating System.
Save it by .py extension.
Now open Command prompt and execute it by : python filename.py
Ex: python hello.py
You can write your own file name in place of ‘hello.py’.
3.Using IDE (Integrated Development Environment):
We can execute our Python code using a Graphical User Interface (GUI).
All you need to do is:
Click on Start button -> All Programs -> Python -> IDLE(Python GUI)
 Python Shell will be opened. Now click on File -> New Window.
A new Editor will be opened. Write our Python code here.
Identifiers :
A Name in python program is called Identifier
It can be variable Name (OR) Class Name (OR) Function Name
EX: a=10
Rules to Define Identifier in Python:
1. The only allowed characters in python are:
Alphabet symbols(Either lower or Upper case)
Digits(0 to 9)
Underscore Symbol(_)
2. Identifier should not start with Digit.
3.Identifers are Case Sensitive.
Reserved words ( or ) Key words :
Python Keywords are special reserved words that convey a special meaning
to the compiler/interpreter.
 Each keyword has a special meaning and a specific operation.
 These keywords can't be used as a variable.
 Following is the List of Python Keywords.
True False None and as
asset def class continue break
else finally elif del except
global for if from import
raise try or return pass
nonlocal in not is lambda
Value and Types:
Value:
A value is one of the basic thing in a
program ,like a letter or a number.
Some values we have seen so far are
2, 42.0, and 'Hello, World!’.
These values belong to different
types:
Ex: 2 is an integer, 42.0 is a floating-
point number, and 'Hello, World!' is a
string
Types:
Data Type Represents the type of value
present inside a Variable.
In python we are not required to
specify the type explicitly. Based on Value
assigned the type will be assigned
automatically. Hence python is dynamic
typed language.
Python Contains the following inbuilt
Data Types:
1.Int
2.Float
3.Complex
4.Bool
5.Str
1.int:
int data type is used to represent whole numbers(integral values)
Ex: a=10
type(a) #int
We can represent int values in the following ways:
1.Decimal form
2.Binary form
3.Octal form
4.Hexa Decimal form
1.Decimal Form (Base-10):
It is the default number system.
The allowed digits are: 0 to 9
Ex: a=10
2. Binary Form (Base-2):
The allowed digits are: 0 & 1
Value should be prefixed with 0b or
0B.
Ex: a=0B1111
3.Octal Form (Base-8):
The allowed digits are: 0 to 7
Value should be prefixed with 0o or
0O
Ex: 0o123
4. Hexa Decimal Form ( Base -16):
The allowed digits are:0 to 9, a-f
(both lower and upper cases).
Values should be prefixed with 0x or 0X.
EX: a=0x10
2.float :
float data type is used to represent floating point values(decimal values)
Ex: f=1.234
type(f) #float
3. complex :
A complex number is of the form a+bj
Complex numbers are specified as <real part>+<imaginary part>j.
Note: ‘a’ and ‘b’ contain integers (or) floating point values.
EX: 3+5j
10+5.5j
0.5 + 0.1j
4.bool :
We can use this data type to represent Boolean values.
The only allowed values for this data type are: True and False
Internally python represents True as 1 and False as 0.
EX: b=True
type(b) -> bool
5.str :
A String is a sequence of characters enclosed within single /double quotes.
EX: s1=‘Hello’
s2=“Welcome”
By using single or double quotes we can’t represent multi line string.
Type Casting :
Conversion of one type value to another is called typecasting.
The following are various inbuilt functions for type casting:
function input output
1.int() int(123.987) 123
2.float() float(10) 10.0
3.complex() complex(10) 10+0j
4.bool() bool(1) True
5.str() str(10) ‘10’
Assignment Statements:
An assignment statement creates a new variable and gives it a value
Ex: message = 'And now for something completely different’
n = 17
pi = 3.1415926535897932
This example makes three assignments. The first assigns a string to a new
variable named message.
 the second gives the integer 17 to n.
 the third assigns the (approximate) value of π to pi.
Operators:
Operator is a Symbol that perform certain operations.
Python provide the following Operators:
1.Arithmatic Operators
2.Relational Operators (or) Comparison Operators.
3.Logical Operators.
4.Bitwise Operators.
5. Assignment Operators.
6.Special Operators.
1. Arithmetic operators:
Python provides operators, which are special symbols that represent certain
operations like addition and multiplication etc.
One of the operator is Arithmetic operators.
Arithmetic Operators are:
1) + -> Addition
2) - -> Subtraction
3) * -> Multiplication
4) / -> Division
5) % -> Modulation
6) // -> Floor Division
7) ** -> Exponent (OR) Power Operator
Example :
a=10
b=2
print(“a+b=“ , a+b)
print(“a-b=“ , a-b)
print(“a*b=“ , a*b)
print(“a/b=“ , a/b)
print(“a//b=“, a//b)
print(“a%b=“ , a%b)
print(“a**b=“ , a**b)
Output :
a+b=12
a-b=8
a*b=20
a/b=5.0
a//b=5
a%b=0
a**b=100
2.Relatonal (OR) Comparison Operators:
Comparison operators are used to comparing the value of the two operands and
returns Boolean true or false.
They return true if the condition is satisfied otherwise the return false.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the
condition becomes true.
>= If the first operand is greater than or equal to the second operand, then the
condition becomes true.
<> If the value of two operands is not equal, then the condition becomes true.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition
becomes true.
Example :
a = 13
b = 33
print(a > b)
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
True
We can also apply relational
operators for str types also.
Example :
a=“hello”
b=“hello”
print(“a>b is”, a>b)
print(“a>b is”, a>=b)
print(“a>b is”, a<b)
print(“a>b is”, a<=b)
Output :
a>b is False
a>=b is True
a<b is False
a<=b True
3.Logical Operators:(and,or,not)
The logical operators are used primarily in the expression evaluation to make
a decision.
1.For Boolean Types:
Operator Description
and If both the expression are true, then the condition will be true. If a and b are the two
expressions, a → true, b → true => a and b → true.
Or If one of the expressions is true, then the condition will be true. If a and b are the two
expressions, a → true, b → false => a or b → true.
Not If an expression a is true then not (a) will be false and vice versa.
Example :
a=10
b=20
c=5
if a>b and a>c:
print(“ a is biggest”)
elif b>c:
print(“b Is biggest”)
else:
print(“c is biggest”)
Output :
b is biggest
2.For non Boolean types:
X and Y:
If x is evaluates to false return X otherwise return Y.
Ex: 10 and 20 -> 20
0 and 20 -> 0
X or Y:
If x is evaluates to True return X otherwise return Y.
Ex: 10 and 20 ->10
0 or 20 ->20
not X :
0 means ->False
Non-zero means -> True
Empty string means -> False
If x is evaluates to False Then result is True otherwise False.
Ex : not 10 ->False
not 0 ->True
4.Bitwse Operators:
The bitwise operators perform bit by bit operation on the values of the two
operands.
Operator Description
& (binary and) If both the bits at the same place in two operands are 1, then 1 is copied
to the result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the resulting
bit will be 1.
^ (binary xor) The resulting bit will be 1 if both the bits are different otherwise the
resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the
resulting bit will be 1 and vice versa.
<< (left shift) The left operand value is moved left by the number of bits present in the
right operand.
>> (right shift) The left operand is moved right by the number of bits present in the right
operand.
Program:
a = 10
b = 4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
Output:
0
14
-11
14
2
40
5.Assignment Operators:
The assignment operators are used to assign the value of the right expression
to the left operand.
perator Description Example
= Assigns values from right side operands to left side operand c = a + b assigns value of
a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left
operand
c += a is equivalent to c =
c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result to left
operand
c -= a is equivalent to c =
c - a
*= Multiply AND It multiplies right operand with the left operand and assign the result to left
operand
c *= a is equivalent to c =
c * a
/= Divide AND It divides left operand with the right operand and assign the result to left
operand
c /= a is equivalent to c =
c / ac /= a is equivalent
to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c =
c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign value to
the left operand
c **= a is equivalent to c
= c ** a
//= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c
= c // a
Program :
a = 21
b = 10
c = 0
c = a + b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c = 2
c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
print "Line 7 - Value of c is ", c
6.Special Operators:
1.Identity Operators:
We can use identity operators for
address comparison.
 the identity operators both are used
to check if two values are refer the
same part of the memory. It return
True (or) False
2.Membership Operators:
We can use Membership operators to
check whether the given object
present in the given collection.(It may
be string ,list,Tuple or Dict)
Operator Description
is It is evaluated to be true if the
reference present at both sides
point to the same object.
is not It is evaluated to be true if the
reference present at both sides do
not point to the same object.
Operator Description
in It is evaluated to be True if value is
found in the sequence (list, tuple,
or dictionary).
not in It is evaluated to be True if value is
not found in the sequence (list,
tuple, or dictionary).
Ex:
X=“hello learning python is very easy”
print(‘h’ in X) ->True
print(‘d’ in X) -> False
print(‘d’ not in X) -> True
Print(‘python’ in X) ->True
Ex:
list1=[“sunny”,”bunny”,”chinny”,”pinny”]
print(“sunny” in list1) -> True
print(“tunny” in list1) -> False
print(“tunny” not in list1) -> True
String Operations: ( + , * )
The + operator performs string
concatenation, which means it joins
the strings by linking them end-to-
end.
Example:
first = 'throat'
second = 'warbler’
Print( first + second)
Output :
throatwarbler
The * operator also works on
strings; it performs repetition.
Example:
Print( 'Spam'*3)
Output :
'SpamSpamSpam'
Functions :
What is Function: Function is a Block of code to perform specific Operation, it
only runs when it is called.
we can pass data to functions Known as parameters.
A Functions can return data as result.
Why Functions:
 Easy to Understand
Easy to Read
Easy to Debug
Code Reusability
Functions can make a program smaller by eliminating repetitive code. Later, if
you make a change, you only have to make it in one place.
Types Of Functions:
Python supports 2 types of functions:
1.Built in Functions
2.User Defined Functions
1.Built in Functions:
The functions which are coming along with python software automatically, are
called built in functions (or) predefined functions.
Ex :
id()
type()
input()
print()
eval()
2.User Defined Functions:
The functions which are developed by programmer explicitly according to
business requirements are called user defined functions.
Syntax to create user defined functions:
def function_name(parameters):
function Block
return value
In python a functions is defined using “def” Keyword
A function accepts the parameter (argument), and they can be optional.
The function block is started with the colon (:), and block statements must
be at the same indentation.
The return statement is used to return the value. A function can have only
one return
Program :
def hello_world():
print(“hello world”)
hello_world()
function call
Math Functions:
Python has a math module that provides most of the familiar mathematical
functions.
 A module is a file that contains a collection of related functions.
Before we can use the functions in a module, we have to import it with an
import statement:
import modulename
EX: import math
This statement creates a module object named math.
we can access members by using module name.
modulename.variable
modulename.function()
Ex: import math
s=math.sqrt(4)
print(s)
Output : 2
Module Aliasing:
Syntax: import modulename as aliasname
Ex: import math as m
original module name alias name.
Ex: import math as m
s=m.sqrt(4)
print(s)
Output : 2
Member Aliasing:
Syntax:
from modulename import module1 as
aliasname,moule2 as aliasname,….
Ex:
from math import sqrt as st, pow as pw
Ex :
s=st(4)
p=pw(2,2)
print(s)
print(p)
Coposition :
So far, we have looked at the elements of a program—variables, expressions, and
statements.
One of the most useful features of programming languages is their ability to take
small building blocks and compose them.
 For example, the argument of a function can be any kind of expression, including
arithmetic operators:
 x = math.sin(degrees / 360.0 * 2 * math.pi)
And even function calls:
 x = math.exp(math.log(x+1))
 Almost anywhere you can put a value, you can put an arbitrary expression, with
one exception: the left side of an assignment statement has to be a variable
name.
 Any other expression on the left side is a syntax error (we will see exceptions to
this rule later).
 minutes = hours * 60 # right
FLOW OF EXECUTION:
To ensure that a function is defined before its first use, you have to know the
order statements run in, which is called the flow of execution.
 Execution always begins at the first statement of the program. Statements are
run one at a time, in order from top to bottom.
 Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function don’t run until the function is
called.
Parameters and Arguments:
Parameters are inputs to the function. if a function contains
parameters, then at the time of calling, compulsory we should provide
values otherwise, otherwise we will get error.
Ex: Write a function to take name of the student as input and print
message by name.
def wish(name):
print(“ Hi”,name,”you look Gorgeous !”)
wish(“ Selena”)
wish(“ Lisa”)
Output :
Hi Selena you look Gorgeous !
Hi Lisa you look Gorgeous !
Types of arguments:
def f1(a,b):
satement1
statement2
:
:
statement
f1(10,20)
There are 4 types of actual arguments in python:
1.positional Arguments
2.Keyword Arguments
3.Default Arguments
4.Variable Length Arguments
Formal arguments
Actual arguments
1.Positional Arguments:
These are the arguments passed to function in correct positional order.
EX: def add(a,b):
print(a+b)
add(10,20)
add(100,200)
OUTPUT: 30
300
The number of arguments and position of arguments must be matched. if we
change the order then result may be changed.
If we change the number of arguments then we will get error.
2.Keyword Arguments:
We can pass argument values by keyword i.e by parameter name.
EX: def wish(name,msg):
print(“Hello”name,msg)
wish(name=“Selena ”,msg=“Good Morning”)
wish(msg=“Good Morning”,name=“ Selena ”)
OUTPUT:
Hello Selena Good Morning
Hello Selena Good Morning
Here the order of arguments is not important but the number of arguments
must be matched.
3.Default Arguments:
Some times we can provide default values for our positional
arguments.
EX:
def wish(name=“Guest ”):
print(“hello”,name,”good morning”)
wish(“Selena”)
wish()
OUTPUT:
Hello Selena good morning
Hello Guest good morning
If we are not passing any name then only default value will be
considered.
4.Vaiable Length Arguments:
Some times we can pass variable number of arguments to our function, such
type of arguments are called variable length arguments.
We can declare a variable length arguments with * symbol as follows.
EX: def f1(*N):
EX: def sum(*n):
total=0
for i in n:
total=total+n
print(“the sum =”,total)
sum()
sum(10)
sum(10,20)
sum(10,20,30,40)
OUTPUT:
the sum=0
the sum=10
the sum=30
the sum=100
Variables and Parameters are local:
1.Local Variables:
The variables which are declared inside a
function are called local variables.
Local variables are available only for the
function in which we declared it. i.e from out
side of function we cannot access.
EX:
def f1():
a=10 ->Local variable
print(a) -> valid
def f2():
print(a) ->Invalid
f1()
f2()
NameError: name ‘a’ is not defined
2. Global Variables :
The variables which are declared
out side of function are called global
variables.
These variables can be accessed in
all functions of that module.
EX:
a=10 -> global variable
def f1():
print(a) -> valid
def f2():
print(a) ->valid
f1()
f2()
Fruitful Functions : Void Functions:
Which are the functions return
values are called fruitful functions.
The function return values by
executing “return” statement.
EX: def f1(a,b):
c=a+b
return c
sum=f1(10,20)
print(sum)
OUTPUT:
30
Which are the functions are not
return values are called void functions
.
EX:
def f1(a,b):
c=a+b
print( c )
f1(10,20)
OUTPUT:
30
# THANK YOU

More Related Content

Similar to Introduction to python programming ( part-1) (20)

1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdf
MaheshGour5
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)
MdFurquan7
 
Sessisgytcfgggggggggggggggggggggggggggggggg
SessisgytcfggggggggggggggggggggggggggggggggSessisgytcfgggggggggggggggggggggggggggggggg
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
unit1 python.pptx
unit1 python.pptxunit1 python.pptx
unit1 python.pptx
TKSanthoshRao
 
Python by Rj
Python by RjPython by Rj
Python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
python programming ppt-230111072927-1c7002a5.pptx
python programming ppt-230111072927-1c7002a5.pptxpython programming ppt-230111072927-1c7002a5.pptx
python programming ppt-230111072927-1c7002a5.pptx
pprince22982
 
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptxpython notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
yuvarajkumar334
 
Lecture 1 .
Lecture 1                                     .Lecture 1                                     .
Lecture 1 .
SwatiHans10
 
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptxPYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptx
swarna627082
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning
ParrotAI
 
Introduction of Python
Introduction of PythonIntroduction of Python
Introduction of Python
ZENUS INFOTECH INDIA PVT. LTD.
 
Chapter1 python introduction syntax general
Chapter1 python introduction syntax generalChapter1 python introduction syntax general
Chapter1 python introduction syntax general
ssuser77162c
 
Review old Pygame made using python programming.pptx
Review old Pygame made using python programming.pptxReview old Pygame made using python programming.pptx
Review old Pygame made using python programming.pptx
ithepacer
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
introduction to python programming concepts
introduction to python programming conceptsintroduction to python programming concepts
introduction to python programming concepts
GautamDharamrajChouh
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
ParveenShaik21
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
ParveenShaik21
 
Revision-of-thehki-basics-of-python.pptx
Revision-of-thehki-basics-of-python.pptxRevision-of-thehki-basics-of-python.pptx
Revision-of-thehki-basics-of-python.pptx
PraveenaFppt
 
1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdf
MaheshGour5
 
funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)
MdFurquan7
 
Sessisgytcfgggggggggggggggggggggggggggggggg
SessisgytcfggggggggggggggggggggggggggggggggSessisgytcfgggggggggggggggggggggggggggggggg
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
python programming ppt-230111072927-1c7002a5.pptx
python programming ppt-230111072927-1c7002a5.pptxpython programming ppt-230111072927-1c7002a5.pptx
python programming ppt-230111072927-1c7002a5.pptx
pprince22982
 
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptxpython notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
yuvarajkumar334
 
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptxPYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptx
swarna627082
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning
ParrotAI
 
Chapter1 python introduction syntax general
Chapter1 python introduction syntax generalChapter1 python introduction syntax general
Chapter1 python introduction syntax general
ssuser77162c
 
Review old Pygame made using python programming.pptx
Review old Pygame made using python programming.pptxReview old Pygame made using python programming.pptx
Review old Pygame made using python programming.pptx
ithepacer
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
introduction to python programming concepts
introduction to python programming conceptsintroduction to python programming concepts
introduction to python programming concepts
GautamDharamrajChouh
 
Revision-of-thehki-basics-of-python.pptx
Revision-of-thehki-basics-of-python.pptxRevision-of-thehki-basics-of-python.pptx
Revision-of-thehki-basics-of-python.pptx
PraveenaFppt
 

More from Ziyauddin Shaik (7)

Operating Systems
Operating Systems Operating Systems
Operating Systems
Ziyauddin Shaik
 
Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems
Ziyauddin Shaik
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
Product Design
Product Design Product Design
Product Design
Ziyauddin Shaik
 
Capsule Endoscopy
Capsule Endoscopy Capsule Endoscopy
Capsule Endoscopy
Ziyauddin Shaik
 
Amazon Go : The future of shopping
Amazon Go : The future of shopping Amazon Go : The future of shopping
Amazon Go : The future of shopping
Ziyauddin Shaik
 
Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems
Ziyauddin Shaik
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
Amazon Go : The future of shopping
Amazon Go : The future of shopping Amazon Go : The future of shopping
Amazon Go : The future of shopping
Ziyauddin Shaik
 
Ad

Recently uploaded (20)

dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Migrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right WayMigrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right Way
Alexander (Alex) Komyagin
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Ad

Introduction to python programming ( part-1)

  • 2. Contents • What is Python? • Uses, features & flavours of Python • Running Python • Identifiers • key words • values & types • Type casting • Operators • Functions • Types of arguments
  • 3. What is Python? Python is a simple, general purpose, high level, Dynamic, Interpreted and object- oriented programming language. Python was developed by Guido Van Rossam in 1989 while working at National Research Institute at Netherlands. But officially python was made available to public in 1991. The official Date of Birth for python is: Feb 20th 1991. Guido developed python program language by taking almost all programming features from different languages: 1. Functional Programming Features from C. 2. Object Oriented Programming Features from C++.
  • 4. Uses of Python: We can use everywhere .The most common important Application areas are: 1. For developing Desktop Applications. 2. For developing Web Applications. 3. For developing Database Applications. 4. For developing Network programming Applications. 5. For developing Games. 6. For Data Analysis Applications. 7. For Machine Learning. 8. For developing Artificial Intelligence Applications. 9. For IoT etc.
  • 5. Features of Python: 1. Simple and easy to learn 2. Freeware and Open Source 3. High Level Programming Language 4. Platform Independent 5. Portability 6. Dynamically Typed 7. Both procedure Oriented and Object Oriented 8. Interpreted 9. Extensible 10. Embedded 11. Extensive Library Versions of Python :  Python 1.0 in Jan 1994. Python 2.0 in Oct 2000. Python 3.0 in Dec 2008.
  • 6. Flavors of Python: NO Flavor description 1 Cpython It is the standard flavor of Python. It can be used to work with C language Applications. 2 Jython (or) Jpython It is for Java Applications. It can run on JVM. 3 IronPython It is for C#.Net Platform. 4 PyPy The main advantage of PyPy is performance will be improved because JIT compiler is Available inside PVM. 5 RubyPython For Ruby Platforms 6 AnacondaPython It is specially designed for handling large volume of data processing.
  • 7. We Run Python Script in the following ways: 1.Interactive Mode 2.Command Line 3.IDE Mode 1. Interactive Mode: To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘python’ and press Enter. Running Python :
  • 8. 2. Script Mode: Using Script Mode, we can write our Python code in a separate file of any editor in our Operating System. Save it by .py extension. Now open Command prompt and execute it by : python filename.py Ex: python hello.py You can write your own file name in place of ‘hello.py’.
  • 9. 3.Using IDE (Integrated Development Environment): We can execute our Python code using a Graphical User Interface (GUI). All you need to do is: Click on Start button -> All Programs -> Python -> IDLE(Python GUI)  Python Shell will be opened. Now click on File -> New Window. A new Editor will be opened. Write our Python code here.
  • 10. Identifiers : A Name in python program is called Identifier It can be variable Name (OR) Class Name (OR) Function Name EX: a=10 Rules to Define Identifier in Python: 1. The only allowed characters in python are: Alphabet symbols(Either lower or Upper case) Digits(0 to 9) Underscore Symbol(_) 2. Identifier should not start with Digit. 3.Identifers are Case Sensitive.
  • 11. Reserved words ( or ) Key words : Python Keywords are special reserved words that convey a special meaning to the compiler/interpreter.  Each keyword has a special meaning and a specific operation.  These keywords can't be used as a variable.  Following is the List of Python Keywords. True False None and as asset def class continue break else finally elif del except global for if from import raise try or return pass nonlocal in not is lambda
  • 12. Value and Types: Value: A value is one of the basic thing in a program ,like a letter or a number. Some values we have seen so far are 2, 42.0, and 'Hello, World!’. These values belong to different types: Ex: 2 is an integer, 42.0 is a floating- point number, and 'Hello, World!' is a string Types: Data Type Represents the type of value present inside a Variable. In python we are not required to specify the type explicitly. Based on Value assigned the type will be assigned automatically. Hence python is dynamic typed language. Python Contains the following inbuilt Data Types: 1.Int 2.Float 3.Complex 4.Bool 5.Str
  • 13. 1.int: int data type is used to represent whole numbers(integral values) Ex: a=10 type(a) #int We can represent int values in the following ways: 1.Decimal form 2.Binary form 3.Octal form 4.Hexa Decimal form
  • 14. 1.Decimal Form (Base-10): It is the default number system. The allowed digits are: 0 to 9 Ex: a=10 2. Binary Form (Base-2): The allowed digits are: 0 & 1 Value should be prefixed with 0b or 0B. Ex: a=0B1111 3.Octal Form (Base-8): The allowed digits are: 0 to 7 Value should be prefixed with 0o or 0O Ex: 0o123 4. Hexa Decimal Form ( Base -16): The allowed digits are:0 to 9, a-f (both lower and upper cases). Values should be prefixed with 0x or 0X. EX: a=0x10
  • 15. 2.float : float data type is used to represent floating point values(decimal values) Ex: f=1.234 type(f) #float 3. complex : A complex number is of the form a+bj Complex numbers are specified as <real part>+<imaginary part>j. Note: ‘a’ and ‘b’ contain integers (or) floating point values. EX: 3+5j 10+5.5j 0.5 + 0.1j
  • 16. 4.bool : We can use this data type to represent Boolean values. The only allowed values for this data type are: True and False Internally python represents True as 1 and False as 0. EX: b=True type(b) -> bool 5.str : A String is a sequence of characters enclosed within single /double quotes. EX: s1=‘Hello’ s2=“Welcome” By using single or double quotes we can’t represent multi line string.
  • 17. Type Casting : Conversion of one type value to another is called typecasting. The following are various inbuilt functions for type casting: function input output 1.int() int(123.987) 123 2.float() float(10) 10.0 3.complex() complex(10) 10+0j 4.bool() bool(1) True 5.str() str(10) ‘10’
  • 18. Assignment Statements: An assignment statement creates a new variable and gives it a value Ex: message = 'And now for something completely different’ n = 17 pi = 3.1415926535897932 This example makes three assignments. The first assigns a string to a new variable named message.  the second gives the integer 17 to n.  the third assigns the (approximate) value of π to pi.
  • 19. Operators: Operator is a Symbol that perform certain operations. Python provide the following Operators: 1.Arithmatic Operators 2.Relational Operators (or) Comparison Operators. 3.Logical Operators. 4.Bitwise Operators. 5. Assignment Operators. 6.Special Operators.
  • 20. 1. Arithmetic operators: Python provides operators, which are special symbols that represent certain operations like addition and multiplication etc. One of the operator is Arithmetic operators. Arithmetic Operators are: 1) + -> Addition 2) - -> Subtraction 3) * -> Multiplication 4) / -> Division 5) % -> Modulation 6) // -> Floor Division 7) ** -> Exponent (OR) Power Operator
  • 21. Example : a=10 b=2 print(“a+b=“ , a+b) print(“a-b=“ , a-b) print(“a*b=“ , a*b) print(“a/b=“ , a/b) print(“a//b=“, a//b) print(“a%b=“ , a%b) print(“a**b=“ , a**b) Output : a+b=12 a-b=8 a*b=20 a/b=5.0 a//b=5 a%b=0 a**b=100
  • 22. 2.Relatonal (OR) Comparison Operators: Comparison operators are used to comparing the value of the two operands and returns Boolean true or false. They return true if the condition is satisfied otherwise the return false. Operator Description == If the value of two operands is equal, then the condition becomes true. != If the value of two operands is not equal then the condition becomes true. <= If the first operand is less than or equal to the second operand, then the condition becomes true. >= If the first operand is greater than or equal to the second operand, then the condition becomes true. <> If the value of two operands is not equal, then the condition becomes true. > If the first operand is greater than the second operand, then the condition becomes true. < If the first operand is less than the second operand, then the condition becomes true.
  • 23. Example : a = 13 b = 33 print(a > b) 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 True We can also apply relational operators for str types also. Example : a=“hello” b=“hello” print(“a>b is”, a>b) print(“a>b is”, a>=b) print(“a>b is”, a<b) print(“a>b is”, a<=b) Output : a>b is False a>=b is True a<b is False a<=b True
  • 24. 3.Logical Operators:(and,or,not) The logical operators are used primarily in the expression evaluation to make a decision. 1.For Boolean Types: Operator Description and If both the expression are true, then the condition will be true. If a and b are the two expressions, a → true, b → true => a and b → true. Or If one of the expressions is true, then the condition will be true. If a and b are the two expressions, a → true, b → false => a or b → true. Not If an expression a is true then not (a) will be false and vice versa. Example : a=10 b=20 c=5 if a>b and a>c: print(“ a is biggest”) elif b>c: print(“b Is biggest”) else: print(“c is biggest”) Output : b is biggest
  • 25. 2.For non Boolean types: X and Y: If x is evaluates to false return X otherwise return Y. Ex: 10 and 20 -> 20 0 and 20 -> 0 X or Y: If x is evaluates to True return X otherwise return Y. Ex: 10 and 20 ->10 0 or 20 ->20 not X : 0 means ->False Non-zero means -> True Empty string means -> False If x is evaluates to False Then result is True otherwise False. Ex : not 10 ->False not 0 ->True
  • 26. 4.Bitwse Operators: The bitwise operators perform bit by bit operation on the values of the two operands. Operator Description & (binary and) If both the bits at the same place in two operands are 1, then 1 is copied to the result. Otherwise, 0 is copied. | (binary or) The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will be 1. ^ (binary xor) The resulting bit will be 1 if both the bits are different otherwise the resulting bit will be 0. ~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit will be 1 and vice versa. << (left shift) The left operand value is moved left by the number of bits present in the right operand. >> (right shift) The left operand is moved right by the number of bits present in the right operand. Program: a = 10 b = 4 print(a & b) print(a | b) print(~a) print(a ^ b) print(a >> 2) print(a << 2) Output: 0 14 -11 14 2 40
  • 27. 5.Assignment Operators: The assignment operators are used to assign the value of the right expression to the left operand. perator Description Example = Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c += Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a -= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a *= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a /= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a %= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a **= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a //= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a Program : a = 21 b = 10 c = 0 c = a + b print "Line 1 - Value of c is ", c c += a print "Line 2 - Value of c is ", c c *= a print "Line 3 - Value of c is ", c c /= a print "Line 4 - Value of c is ", c c = 2 c %= a print "Line 5 - Value of c is ", c c **= a print "Line 6 - Value of c is ", c c //= a print "Line 7 - Value of c is ", c
  • 28. 6.Special Operators: 1.Identity Operators: We can use identity operators for address comparison.  the identity operators both are used to check if two values are refer the same part of the memory. It return True (or) False 2.Membership Operators: We can use Membership operators to check whether the given object present in the given collection.(It may be string ,list,Tuple or Dict) Operator Description is It is evaluated to be true if the reference present at both sides point to the same object. is not It is evaluated to be true if the reference present at both sides do not point to the same object. Operator Description in It is evaluated to be True if value is found in the sequence (list, tuple, or dictionary). not in It is evaluated to be True if value is not found in the sequence (list, tuple, or dictionary).
  • 29. Ex: X=“hello learning python is very easy” print(‘h’ in X) ->True print(‘d’ in X) -> False print(‘d’ not in X) -> True Print(‘python’ in X) ->True Ex: list1=[“sunny”,”bunny”,”chinny”,”pinny”] print(“sunny” in list1) -> True print(“tunny” in list1) -> False print(“tunny” not in list1) -> True
  • 30. String Operations: ( + , * ) The + operator performs string concatenation, which means it joins the strings by linking them end-to- end. Example: first = 'throat' second = 'warbler’ Print( first + second) Output : throatwarbler The * operator also works on strings; it performs repetition. Example: Print( 'Spam'*3) Output : 'SpamSpamSpam'
  • 31. Functions : What is Function: Function is a Block of code to perform specific Operation, it only runs when it is called. we can pass data to functions Known as parameters. A Functions can return data as result. Why Functions:  Easy to Understand Easy to Read Easy to Debug Code Reusability Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
  • 32. Types Of Functions: Python supports 2 types of functions: 1.Built in Functions 2.User Defined Functions 1.Built in Functions: The functions which are coming along with python software automatically, are called built in functions (or) predefined functions. Ex : id() type() input() print() eval()
  • 33. 2.User Defined Functions: The functions which are developed by programmer explicitly according to business requirements are called user defined functions. Syntax to create user defined functions: def function_name(parameters): function Block return value In python a functions is defined using “def” Keyword A function accepts the parameter (argument), and they can be optional. The function block is started with the colon (:), and block statements must be at the same indentation. The return statement is used to return the value. A function can have only one return Program : def hello_world(): print(“hello world”) hello_world() function call
  • 34. Math Functions: Python has a math module that provides most of the familiar mathematical functions.  A module is a file that contains a collection of related functions. Before we can use the functions in a module, we have to import it with an import statement: import modulename EX: import math This statement creates a module object named math. we can access members by using module name. modulename.variable modulename.function() Ex: import math s=math.sqrt(4) print(s) Output : 2
  • 35. Module Aliasing: Syntax: import modulename as aliasname Ex: import math as m original module name alias name. Ex: import math as m s=m.sqrt(4) print(s) Output : 2 Member Aliasing: Syntax: from modulename import module1 as aliasname,moule2 as aliasname,…. Ex: from math import sqrt as st, pow as pw Ex : s=st(4) p=pw(2,2) print(s) print(p)
  • 36. Coposition : So far, we have looked at the elements of a program—variables, expressions, and statements. One of the most useful features of programming languages is their ability to take small building blocks and compose them.  For example, the argument of a function can be any kind of expression, including arithmetic operators:  x = math.sin(degrees / 360.0 * 2 * math.pi) And even function calls:  x = math.exp(math.log(x+1))  Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: the left side of an assignment statement has to be a variable name.  Any other expression on the left side is a syntax error (we will see exceptions to this rule later).  minutes = hours * 60 # right
  • 37. FLOW OF EXECUTION: To ensure that a function is defined before its first use, you have to know the order statements run in, which is called the flow of execution.  Execution always begins at the first statement of the program. Statements are run one at a time, in order from top to bottom.  Function definitions do not alter the flow of execution of the program, but remember that statements inside the function don’t run until the function is called.
  • 38. Parameters and Arguments: Parameters are inputs to the function. if a function contains parameters, then at the time of calling, compulsory we should provide values otherwise, otherwise we will get error. Ex: Write a function to take name of the student as input and print message by name. def wish(name): print(“ Hi”,name,”you look Gorgeous !”) wish(“ Selena”) wish(“ Lisa”) Output : Hi Selena you look Gorgeous ! Hi Lisa you look Gorgeous !
  • 39. Types of arguments: def f1(a,b): satement1 statement2 : : statement f1(10,20) There are 4 types of actual arguments in python: 1.positional Arguments 2.Keyword Arguments 3.Default Arguments 4.Variable Length Arguments Formal arguments Actual arguments
  • 40. 1.Positional Arguments: These are the arguments passed to function in correct positional order. EX: def add(a,b): print(a+b) add(10,20) add(100,200) OUTPUT: 30 300 The number of arguments and position of arguments must be matched. if we change the order then result may be changed. If we change the number of arguments then we will get error.
  • 41. 2.Keyword Arguments: We can pass argument values by keyword i.e by parameter name. EX: def wish(name,msg): print(“Hello”name,msg) wish(name=“Selena ”,msg=“Good Morning”) wish(msg=“Good Morning”,name=“ Selena ”) OUTPUT: Hello Selena Good Morning Hello Selena Good Morning Here the order of arguments is not important but the number of arguments must be matched.
  • 42. 3.Default Arguments: Some times we can provide default values for our positional arguments. EX: def wish(name=“Guest ”): print(“hello”,name,”good morning”) wish(“Selena”) wish() OUTPUT: Hello Selena good morning Hello Guest good morning If we are not passing any name then only default value will be considered.
  • 43. 4.Vaiable Length Arguments: Some times we can pass variable number of arguments to our function, such type of arguments are called variable length arguments. We can declare a variable length arguments with * symbol as follows. EX: def f1(*N): EX: def sum(*n): total=0 for i in n: total=total+n print(“the sum =”,total) sum() sum(10) sum(10,20) sum(10,20,30,40) OUTPUT: the sum=0 the sum=10 the sum=30 the sum=100
  • 44. Variables and Parameters are local: 1.Local Variables: The variables which are declared inside a function are called local variables. Local variables are available only for the function in which we declared it. i.e from out side of function we cannot access. EX: def f1(): a=10 ->Local variable print(a) -> valid def f2(): print(a) ->Invalid f1() f2() NameError: name ‘a’ is not defined 2. Global Variables : The variables which are declared out side of function are called global variables. These variables can be accessed in all functions of that module. EX: a=10 -> global variable def f1(): print(a) -> valid def f2(): print(a) ->valid f1() f2()
  • 45. Fruitful Functions : Void Functions: Which are the functions return values are called fruitful functions. The function return values by executing “return” statement. EX: def f1(a,b): c=a+b return c sum=f1(10,20) print(sum) OUTPUT: 30 Which are the functions are not return values are called void functions . EX: def f1(a,b): c=a+b print( c ) f1(10,20) OUTPUT: 30