SlideShare a Scribd company logo
1 of 86
Dr.M.Rajendiran
Dept. of Computer Science and Engineering
Panimalar Engineering College
Install Python 3 On Ubuntu
Prerequisites
Step 1.A system running Ubuntu
Step 2.A user account with sudo privileges
Step 3.Access to a terminal command-line (Ctrl–Alt–T)
Step 4.Make sure your environment is configured to use
Python 3.8
2
Install Python 3
Now you can start the installation of Python 3.8.
$sudo apt install python3.8
Allow the process to complete and verify the Python
version was installed successfully
$python ––version
3
Installing and using Python on Windows is very simple.
Step 1: Download the Python Installer binaries
Step 2: Run the Executable Installer
Step 3: Add Python to environmental variables
Step 4: Verify the Python Installation
4
Python Installation
Open the Python website in your web browser.
https://www.python.org/downloads/windows/
Once the installer is downloaded, run the Python installer.
Add the following path
C:Program FilesPython37-32: for 64-bit installation
Once the installation is over, you will see a Python Setup
Successful window.
You are ready to start developing Python applications in
your Windows 10 system.
5
Introduction
Python is a general-purpose interpreted, interactive, object-
oriented, and high-level programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”.
Python was released in the year 2000.
Python is interpreted
Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it.
Introduction
Python is Interactive: You can actually sit at a Python
prompt and interact with the interpreter directly to write your
programs.
Python is Object-Oriented: Python supports Object-
Oriented style or technique of programming that
encapsulates code within objects.
Python is a Beginner's Language: Python is a great
language for the beginner level programmers and supports
the development of a wide range of applications.
Features
Easy-to-learn
Easy-to-maintain
Portable
Interpreted
Extensible
Free and Open Source
High Level Language
Scalable
Applications
Bit Torrent(a stream flowing with great force) file
sharing
Google search engine, YouTube
Intel, Cisco, HP, IBM
i–Robot
NASA(National Aeronautics and Space Administration)
Facebook, Drop box
Applications
Python interpreter:
1.Interpreter
To execute a program in a high-level language by
translating it one line at a time.
2.Compiler
To translate a program written in a high-level language into
a low-level language all at once, in preparation for later
execution.
Modes of python interpreter
Python Interpreter is a program that reads and executes
python code. It uses two modes of execution.
1. Interactive mode
2. Script mode
1.Interactive mode
Interactive Mode, as the name suggests, allows us to interact
with operating system.
When we type python statement, interpreter displays the
result(s) immediately.
Modes of python interpreter
Advantages:
Python, in interactive mode, is good enough to learn,
experiment or explore.
Working in interactive mode is convenient for beginners
and for testing small pieces of code
Drawback:
We cannot save the statements and have to retype all the
statements once again to re-run them.
In interactive mode, you type python programs and the
interpreter displays the result.
Modes of python interpreter
2.Script mode
In script mode, we type python program in a file and then
use interpreter to execute the content of the file.
Scripts can be saved to disk for future use.
Python scripts have the extension .py, meaning that the
filename ends with .py
Save the code with filename.py and run the interpreter in
script mode to execute the script.
Integrated Development Learning Environment (IDLE)
It a graphical user interface which is completely written in
python.
It is bundled with the default implementation of the python
language and also comes with optional part of the python
packaging.
Features
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
VALUES AND DATA TYPES
Values
Value can be any letter, number or string.
Values are different data types
Eg: 2, 42.0, and 'Hello, World!'.
Data type
Every value in python has a data type.
It is a set of values, and the allowable operations on those
values.
Python has five standard data types:
VALUES AND DATA TYPES
1.Numbers
 It stores numerical values.
 This data type is immutable (i.e. values/items cannot be changed).
Python supports following number types
1. Integers
2. Floating point numbers
3. Complex numbers.
VALUES AND DATA TYPES
1.1Integer
Integers are the whole numbers consisting of positive(+ve) or negative(–
ve) sign.
Integers can be any length, it is only limited by the memory available
Example:
a=10
a=eval(input(“enter a value”))
a=int(input(“enter a value”))
1.2 Float
It has decimal part and fractional part.
It is accurate upto 15 decimal places.
VALUES AND DATA TYPES
Example:
a=3.15
a=eval(input(“enter a value”))
a=float(input(“enter a value”))
1.3 Complex
It is a combination of real and imaginary part.
Example:
2+5j
a+bi
VALUES AND DATA TYPES
2.Boolean
Boolean data type have two values. It has either 0 or 1.
0 means False
1 means True
True and False is a keyword.
Example:
>>> 3==5
False
>>> True+True
2
>>> False+True
1
>>> False*True
0
VALUES AND DATA TYPES
3.Sequence
 A sequence is an ordered collection of items, indexed by positive
integers.
 It is a combination of mutable (value can be changed) and immutable
(values cannot be changed) data types.
There are three types of sequence data type available in python, they are
1. Strings
2. Lists
3. Tuples
VALUES AND DATA TYPES
3.1 Strings
 String is defined as a continues set of characters represented in
quotation marks (either single quotes ( ‘ ) or double quotes ( “ ).
 An individual character in a string is accessed using a subscript (index).
 The subscript should always be an integer (positive or negative).
 A subscript starts from 0 to n-1.
 Strings are immutable i.e. the contents of the string cannot be changed
after it is created.
 Python will get the input at run time by default as a string.
 Python does not support character data type. A string of size 1 can
be treated as characters.
VALUES AND DATA TYPES
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)
Operations on string
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
VALUES AND DATA TYPES
.
Indexing >>>a=”HELLO”
>>>print(a[0])
>>>H
>>>print(a[1])
>>>O
Positive indexing helps in accessing the
string from the beginning.
Negative subscript helps in accessing the
string from the end.
Slicing
print[0:4] – HELL
print[ :3] – HEL
print[0: ]
HELLO
The slice[n : m] operator extracts sub string
from the strings.
A segment of a string is called a slice.
Concatenation
a=”raj”
b=”man”
print(a+b)
rajman
The + operator joins the text on both sides
of the operator.
Repetitions
a=”welcome ”
print(a*3)
welcome welcome
welcome
The * operator repeats the string on the left
hand side times the value on right hand
side.
Membership
>>> s="good morning"
>>>"m" in
s True
>>> "a" not in
s True
Using membership operators to check a
particular character is in string or not.
Returns true if present
VALUES AND DATA TYPES
3.2 Lists
 List is an ordered sequence of items. Values in the list are called
elements or items.
 Values are separated by commas and enclosed within square
brackets[].
 Items in the lists can be different data types.
 Lists are mutable(values of list can be changed)
Operations on list
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
VALUES AND DATA TYPES
.create a list
>>> a=[2,3,4,5,6,7,8,9,10]
>>> print(a)
[2, 3, 4, 5, 6, 7, 8, 9, 10]
This is way we can create a list
at compile time
Indexing
>>>print(a[0])
2
>>> print(a[8])
10
>>> print(a[1])
10
Accessing the item in the
position 0
Accessing the item in the
position 8
Accessing a last element
using negative indexing.
Slicing
>>> print(a[0:3])
[2, 3, 4]
>>> print(a[0:])
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[:8])
[2, 3, 4, 5, 6, 7, 8, 9]
Printing a part of the string.
Concatenation
>>>b=[20,30]
>>> print(a+b)
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
Adding and printing the items of
two lists.
Repetition
>>> print(b*3)
[20, 30, 20, 30, 20, 30]
Create a multiple copies of the
same string.
VALUES AND DATA TYPES
. Updating the list
>>> print(a[2])
4
>>> a[2]=100
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Updating the list using index
value
Inserting an
element
>>> a. insert(0,“tham")
>>> print(a)
a=[“tham”,2,3,4,5,6,7,8,9,10]
Inserting an element in 0th
position
Removing an
element
>>> a. remove(“tham”)
>>> print(a)
a=[2,3,4,5,6,7,8,9,10]
Removing an element
by giving the element directly
VALUES AND DATA TYPES
3.3Tuple
 A tuple is an ordered sequence of items same as list.
 The set of elements is enclosed in parenthesis instead of square
brackets.
 A tuple is an immutable. i.e. cannot be modified.
 Tuples are faster than lists.
 Tuples can be used as keys in dictionaries.
 Tuples are used to write-protect data and cannot be change
dynamically
 Tuple have no append or extend method.
 Elements can not be removed from a tuple.
VALUES AND DATA TYPES
Operations on Tuple
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
VALUES AND DATA TYPES
.
Creating a tuple
>>>a=(20,40,60,”apple”,”ball”)
Creating the tuple with
elements of different data
types.
Indexing
>>>print(a[0])
20
>>> a[2] 60
Accessing the item in the
position 0
Accessing the item in the
position 2
Slicing
>>>print(a[1:3])
(40,60)
Displaying items from 1st till
2nd.
Concatenation
>>> b=(2,4)
>>>print(a+b)
>>>(20,40,60,”apple”,”ball”,2,4)
Adding tuple elements at the
end of another tuple
elements
Repetition
>>>print(b*2)
>>>(2,4,2,4)
repeating the tuple in n no of
times
updating a tuple
>>>a[2]=100
Type Error: 'tuple' object does
not support item assignment
Altering the tuple data type
leads to error.
VALUES AND DATA TYPES
4.Dictionaries
Dictionaries are unordered sets.
Dictionary is created by using curly braces. i,e. { }
Dictionaries are accessed via keys.
A dictionary is an associative array. Any key of the
dictionary is associated (or mapped) to a value.
The values of a dictionary can be any Python data type. So
dictionaries are key value-pairs
Dictionaries don't support the sequence data types like
strings, tuples and lists.
VALUES AND DATA TYPES
5.Sets
The set datatype is an unordered collection of unique items
The collection is mutable.(i.e. can be add or remove)
Set is defined by value separated by comma inside curly
braces.{}
It has no duplicate entry.
Creating a
dictionary
>>>a={'name':"abi",'age':18,'mark':1
00}
>>>print(a)
{'name': 'abi', 'age': 18, 'mark': 100}
Creating the dictionary
with elements of different
data
types.
Indexing
>>>print(a['name'])
abi
Accessing the item with
keys.
VALUES AND DATA TYPES
Example:
a={1,2,3,4,5,6,7,6,7}
print(a)
a={1,2,3,4,5,6,7}
Scalar type
A scalar is a type that can have a single value such as 5,3.14, “THAM”
Example: int, float, complex, boolean and string
Escape sequence
n – move to newline
t – move one tap space horizontally
v – move in space vertically
b – back space
VARIABLES
A variable is an identifier that refers to a value
While creating a variable, memory space is reserved in memory
Based on the data type of a variable, the interpreter allocates
memory
The assignment statements are used to create a new variable
and assign values to them.
Variable names can contain letters, underscore and numbers but
do not start with numbers.
Underscore(_) can be used in variable names.
Example:
a=5 // single assignment
a,b,c=2,3,4 // multiple assignment
a=b=c=2 //assigning one value to multiple variables
KEYWORDS
Keywords are the reserved words in python.
We cannot use a keyword as variable name, function name or any
other identifier.
They are used to define the syntax and structure of the python
language.
Keywords are case sensitive.
IDENTIFIERS
Identifier is the name given to entities like class, functions,
variables etc. in python.
Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_).
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like !, @, #, $, % etc. in our
identifier.
Identifier can be of any length.
Valid Identifiers
num,Num,Num1,_num,num_temp2,IF,Else
Invalid Identifiers
Num 1,num 1,addition of program,1Num,num.no,if,else
STATEMENTS
Instructions that a python interpreter can executes are called
statements.
A statement is a unit of code like creating a variable or displaying a
value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n.
The second line is a print statement that displays the value of n.
There are two types of statements available
1. single line statements
2. multi line statements
STATEMENTS
1.Single line statements
single line statements are end with newline
Examples:
a=1
b=2
c=a+b
2.Multiline statements
python allows the user to write multi line statement using line
continuation character () to denote that the line should continue.
Example:
total=mark1+
mark2+
mark3
INPUT AND OUTPUT
INPUT
Input is a data entered by user in the program.
In python, input () function is available for input.
Syntax:
variable = input (“data”)
Example:
a=input("enter the name:")
Data type Compile time Run time
int a=10 a=int(input(“enter a”))
float a=10.5 a=float(input(“enter a”))
string a=”panimalar” a=input(“enter a string”)
list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))
INPUT AND OUTPUT
OUTPUT
An output can be displayed to the user using print statement.
Syntax:
print (expression/constant/variable)
Example:
print ("Hello") // Hello
print(5) //5
print(3+5) //8
print(c)
COMMENTS
Comments are used to provide more details about the program like
name of the program, author of the program, date and time, etc.
Types of comments
1. Single line comments
2. Multi line comments
1.Single line comments(#)
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Example:
Percentage = (minute * 100) / 60 # calculating percentage of an hour
COMMENTS
2.Multi line comments(“””……”””)
Multiple line comments can be written using triple quotes “”” ……….”””
Example:
“”” This program is created by Robert in Dell lab on 12/12/20 based on
newtons method”””
LINES AND INDENTATION
Most of the programming languages like C, C++, Java use braces { }
to define a block of code. But, python uses indentation.
Blocks of code are denoted by line indentation.
It is a space given to the block of codes for class and function
definitions or flow control.
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
TUPLE ASSIGNMENT
A tuple using a single assignment statement.
Python has a very powerful tuple assignment.
Tuple of variables on the left to be assigned values from a tuple on
the right.
The left side is a tuple of variables, the right side is a tuple of values.
Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before any of the
assignments.
(a,b,c)=(3,4,5)
(a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack Swapping two
numbers using tuple
(a, b) = (b, a)
OPERATORS
An operator is symbol that tells the compiler to perform specific
mathematical or logical manipulations.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called
operands and + is called operator.
Types of Operators
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
OPERATORS
Arithmetic operators
They are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Operator Description
Example
a=9,b=2
+ Addition Adds values on either side of the operator. a + b = 11
- Subtraction Subtracts operand. Right hand operand from left hand a – b = 7
* Multiplication Multiplies values on either side of the operator a * b = 18
/ Division Divides left hand operand by right hand operand b / a = 4
% Modulus
Divides left hand operand by right hand operand and
returns remainder
b % a = 1
** Exponent
Performs operators exponential (power) calculation on
operators
a**b =9 to the
power 2
//
Floor Division The division of operands where the
result is the quotient in which the digits after the
decimal point are removed
5//2=4.0
OPERATORS
Comparison (Relational) Operators
Comparison operators are used to compare values.
It either returns True or False according to the condition.
Operator Description
Example
a=10,b=20
==
If the values of two operands are equal, then the condition becomes
true.
(a == b)
is not true.
!= If values of two operands are not equal, then condition becomes true. (a!=b)
is true
>
If the value of left operand is greater than the value of right operand,
then condition becomes true.
(a > b)
is not true.
<
If the value of left operand is less than the value of right operand,
then condition becomes true.
(a < b)
is true.
>=
If the value of left operand is greater than or equal to the value of
right operand, then condition becomes true.
(a >= b)
is not true.
<=
If the value of left operand is less than or equal to the value of right
operand, then condition becomes true.
(a <= b)
is true.
OPERATORS
Assignment Operators
Assignment operators are used in Python to assign values to
variables.
Operator 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
OPERATORS
Logical Operators
Logical operators are and, or, not operators.
.
%= 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
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x
OPERATORS
Bitwise Operators
Bitwise operators act on operands as if they are binary digits. They
operate bit by bit.
Let x = 10 (0000 1010) and y = 4 (0000 0100)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)
OPERATORS
Membership Operators
Evaluates to find a value or a variable is in the specified sequence
of string, list, tuple, dictionary or not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in
operators are used.
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in
True if value/variable is not found in the
sequence
5 not in x
OPERATORS
Identity Operators
They are used to check if two values (or variables) are located on
the same part of the memory.
Example
x = 5
y = 5
a = 'Hello'
b = 'Hello'
print(x is not y) // False
print(a is b)//True
Operator Meaning Example
is True if the operands are identical x is True
is not True if the operands are not identical x is not True
Operator Precedence
When an expression contains more than one operator, the order of
evaluation depends on the rules of precedence.
Operator Description
() Parenthesis
** Exponentiation (raise to the power)
~ + - Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
Is, is not Identity operators
In, not in Membership operators
and,or,not Logical operators
Expressions
An expression is a combination of values, variables, and operators.
A value and a variable itself considered as an expression.
The following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
hifriend
FUNCTIONS
Function is a sub program which consists of set of instructions used
to perform a specific task.
A large program is divided into number of sub program called
function.
Need for Function
When the program is too complex and large they are divided into
sub program.
Each sub program is separately coded and combined into single
program. Each subprogram is called as function.
Debugging, Testing and maintenance becomes easy when the
program is divided into subprograms.
Functions are used to avoid rewriting same code again and again in
a program.
Function provides code re-usability
The length of the program is reduced.
FUNCTIONS
TYPES OF FUNCTION
1. Built in function
2. user defined function
1.Built in function
Built in functions are the functions that are already created and
stored in python.
These built in functions are always available for usage and
accessed by a programmer.
It cannot be modified.
FUNCTIONS
.
Built in function Description
>>>max(3,4)
4 # returns largest element
>>>min(3,4)
3 # returns smallest element
>>>len("hello")
5 #returns length of an object
>>>range(2,8)
[2, 3, 4, 5, 6, 7] #returns range of given values
>>>round(7.8)
8.0 #returns rounded integer of the given number
>>>chr(5)
x05' #returns a character (a string) from an integer
>>>float(5)
5.0 #returns float number from string or integer
>>>int(5.0)
5 # returns integer from string or float
>>>pow(3,5)
243 #returns power of given number
>>>type( 5.6)
<type 'float'> #returns data type of object to which it belongs
>>>t=tuple([4,6.0,7])
>>>t
(4, 6.0, 7)
# to create tuple of items from list
>>>print("good morning")
Good morning # displays the given object
FUNCTIONS
2.User defined function
User defined functions are the functions that programmers create for
their requirement and use.
These functions can then be combined to form module which can be
used in other programs by importing them.
Advantages
The programmer can write their own functions which are known as
user defined function.
These functions can create by using keyword def.
Example:
add(), sub()
Elements of User defined function
There are two elements in user defined function.
1. function definition
2. function call
FUNCTIONS
1.Function definition
A function definition specifies the name of a new function and the
sequence of statements that execute when the function is called.
Syntax:
def function name(parameter list): ----Function header
statement 1
statement 2
....
....
statement n
def is a keyword that indicates that this is a function definition.
The rules for function names are the same as for variable names
The first line of the function definition is called the header, the rest is
called body of function.
The header has to end with a colon and the body has to be indented.
The function contains any number of statements.
Parameter list contains list of values used inside the function.
 Body of the function
FUNCTIONS
Example:
def add():
a=eval(input(“enter a value”))
b=eval(input(“enter a value”))
c=a+b
print(c)
2.Function call()
A function is called by using the function name followed by
parenthesis().
Argument is a list of values provided to the function when the
function is called
The statements inside the function does not executed until the
function is called.
Function can be called n number of times
FUNCTIONS
Syntax:
function name(argument list)
Example:
add() or add(a,b)
Flow of Execution
The order in which statements are executed is called the flow of
execution
Program execution starts from first statement.
One statement is executed at a time from top to bottom.
Function definitions do not alter the flow of execution of the program.
The statement inside the function are not executed until the function
is called.
FUNCTIONS
When a function is called, the control flow jumps to the body of the
function, execute the statements and return back to the place in the
program where the function call was made.
FUNCTION PROTOTYPES
Based on arguments and return type functions are classified into
four types.
1. Function without arguments and without return type
2. Function with arguments and without return type
3. Function without arguments and with return type
4. Function with arguments and with return type
FUNCTION PROTOTYPES
1. Function without arguments and without return type
In this type no argument is passed through the function call and no
output is return to main function
The sub function will read the input values perform the operation and
print the result in the same block.
Example
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
print(c)
add()
Output:
enter a 5
enter b 10
15
FUNCTION PROTOTYPES
2. Function with arguments and without return type
Arguments are passed through the function call but output is not
return to the main function.
Example:
def add(a,b):
c=a+b
print(c)
a=int(input("enter a"))
b=int(input("enter b"))
add(a,b)
OUTPUT:
enter a 5
enter b 10
15
FUNCTION PROTOTYPES
3. Function without arguments and with return type
In this type no argument is passed through the function call but
output is return to the main function.
Example:
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
return c
c=add()
print(c)
OUTPUT:
enter a 5
enter b 10
15
FUNCTION PROTOTYPES
4. Function with arguments and with return type
In this type arguments are passed through the function call and
output is return to the main function.
Example:
def add(a,b):
c=a+b
return c
a=int(input("enter a"))
b=int(input("enter b"))
c=add(a,b)
print(c)
OUTPUT:
enter a 5
enter b 10
15
FRUITFUL FUNCTION
Fruitful functions are functions that return value or A function that
yields a return value.
Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
VOID FUNCTION
Void function is a function that always return none.
It represents the absence of value.
Example:
print("Hello")
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
PARAMETERS AND ARGUMENTS
Parameters
 Parameters are the value(s) provided in the function header within
parenthesis.
 These are the values required by function to work.
 If there is more than one value, separated by comma.
Example: def add(a,b):
Arguments
 Arguments are the value(s) provided in function call statement.
 List of arguments should be same way as parameters are listed.
 Bounding of parameters to arguments is done 1:1, and there should be
same number and type of arguments as mentioned in parameter list.
Example: add(a,b)
PARAMETERS AND ARGUMENTS
Return Statement
 The return statement is used to exit a function and go back to the place
from where it was called.
 If the return statement has no arguments, then it will not return any
values. But exits from function.
Syntax:
return variable
Example:
def add(a,b):
c=a+b
return c
a=5
b=4
c=add(a,b)
print(c)
No Example Description
1 return a return 1 variable
2 return a,b return 2 variables
3 return a,b,c return 3 variables
4 return a+b return expression
5 return 8 return value
PARAMETERS AND ARGUMENTS
ARGUMENTS TYPES
You can call a function by using the following types of formal arguments
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1.Required Arguments:
 The number of arguments in the function call should match exactly with
the function definition.
PARAMETERS AND ARGUMENTS
. Example Output
def student( name, roll ):
print(name,roll)
student("george",98)
George
98
def student( name, roll ):
print(name,roll)
student(101,”rithika”)
101
rithika
def student( name, roll ):
print(name,roll)
student(101)
student() missing 1 required
positional
argument: 'name'
def student( name, roll ):
print(name,roll)
student()
student() missing 2 required
positional
arguments: ‘name' and ‘roll'
PARAMETERS AND ARGUMENTS
2.Keyword Arguments
 Python interpreter is able to use the keywords provided to match the
values with parameters even though if they are arranged in out of order.
Example Output
def student( name, roll,mark):
print(name,roll,mark)
student (mark=90,roll=102,name="bala")
bala
102
90
def student( name, roll,mark):
print(name,roll,mark)
student (name="bala", roll=102, mark=90)
bala
102
90
PARAMETERS AND ARGUMENTS
3.Default Arguments
 Assumes a default value if a value is not provided in the function call for
that argument.
 It allows us to miss one or more arguments.
Example Output
def student( name="raja", roll=101,mark=50):
print(name,roll,mark)
student (mark=90,roll=102,name="bala")
bala
102
90
def student( name="raja", roll=101,mark=50):
print(name,roll,mark)
student (name="bala", roll=102)
bala
102
90
def student( name="raja", roll=101,mark=50):
print(name,roll,mark)
student ()
raja
101
50
PARAMETERS AND ARGUMENTS
4.Variable length Arguments
 If we want to specify more arguments than function header parameter,
variable length arguments are used.
 It is denoted by * symbol before parameter.
Example Output
def student( name,mark):
print(name,mark)
student (“bala”,90)
bala
90
def student( name, roll,*mark):
print(name,roll,mark)
student ("raja",101,90,80)
raja
101
90
80
MODULES
A module is a file containing python definitions, functions,
statements and instructions.
Standard library of python is extended as modules.
Programmer needs to import the module.
Once we import a module, we can use to any of its functions or
variables in our code.
There is large number of standard modules also available in
python.
Standard modules can be imported the same way as import our
user-defined modules.
MODULE
Two ways to import your module:
1. import keyword
2. from keyword
1.Import keyword
 Import keyword is used to get all functions from the module.
 Every module contains many function.
 To access one of the function , you have to specify the name of the
module and the name of the function separated by dot .
 This format is called dot notation.
Syntax:
import module_name
module_name.function_name(variable)
MODULE
Importing built-in module
import math
x=math.sqrt(25)
print(x)
Importing user-defined module
cal.py
def add(a,b):
c=a+b
return c
import cal
x=cal.add(5,4)
print(x)
MODULE
2.from keyword
 from keyword is used to get only particular function from the module.
Syntax:
from module_name import function_name
#Importing built-in module
from math import sqrt
x=sqrt(25)
print(x)
#Importing user-defined module
from cal import add
x=add(5,4)
print(x)
add.py
def add(a,b):
c=a+b
return c
MODULE
2.from keyword
 from keyword is used to get only particular function from the module.
Syntax:
from module_name import function_name
#Importing built-in module
from math import sqrt
x=sqrt(25)
print(x)
#Importing user-defined module
from cal import add
x=add(5,4)
print(x)
add.py
def add(a,b):
c=a+b
return c
BUILT-IN MODULES
. Built-in Function Description
math.ceil(x)
Return the ceiling of x, the smallest integer
greater than or equal to x
math.floor(x)
Return the floor of x, the largest integer less
than or equal to x.
math.factorial(x) Return x factorial
math.sqrt(x) Return the square root of x
math.log(x) Return the natural logarithm of x
math.log10(x) Returns the base-10 logarithms
math.log2(x) Return the base-2 logarithms
math.sin(x) Returns sin of x radians
math.cos(x) Returns cosine of x radians
BUILT-IN MODULES
Generate pseudo-random numbers
Random Function Description
random.randrange(stop) Return random numbers from 0
random.randrange(start, stop[,
step])
Return the random numbers in a range
random.uniform(a, b) Return a random floating point number
SAMPLE PROGRAMS
.
Swapping two number Output
a = int(input("Enter a value "))
b = int(input("Enter b value "))
c = a
a = b
b = c
print("a=",a,"b=",b,)
Enter a value 5
Enter b value 8
a=8
b=5
Distance between two points Output
import math
x1=int(input("enter x1"))
y1=int(input("enter y1"))
x2=int(input("enter x2"))
y2=int(input("enter y2"))
distance =math.sqrt((x2-
x1)**2)+((y2-y1)**2)
print(distance)
enter x1 7
enter y1 6
enter x2 5
enter y2 7
2.5
SAMPLE PROGRAMS
.
Circulate n numbers Output
a=list(input("enter the list"))
print(a)
for i in range(1,len(a),1):
print(a[i:]+a[:i])
enter the list '1234'
['1', '2', '3', '4']
['2', '3', '4', '1']
['3', '4', '1', '2']
['4', '1', '2', '3']
Practice
An evaluate the following expressions
No. Expression output
1 a=9-12/3+3*2-1 Ans:a=10
2 A=2*3+4%5-3/2+6 Ans:A=15
3
find m=?
m=-43||8&&0||-2
Ans:m=1
4
a=2,b=12,c=1
d=a<b>c
Ans:d=0
5
a=2,b=12,c=1
d=a<b>c-1
Ans:d=1
6 a=2*3+4%5-3//2+6 Ans:a=15
.

More Related Content

What's hot

Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Pedro Rodrigues
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonYi-Fan Chu
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialQA TrainingHub
 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slidesrfojdar
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in PythonDevashish Kumar
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming LanguageR.h. Himel
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introductionSiddique Ibrahim
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaEdureka!
 
Presentation on python data type
Presentation on python data typePresentation on python data type
Presentation on python data typeswati kushwaha
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An IntroductionSwarit Wadhe
 

What's hot (20)

Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Python programming
Python  programmingPython  programming
Python programming
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slides
 
Python
PythonPython
Python
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
 
Presentation on python data type
Presentation on python data typePresentation on python data type
Presentation on python data type
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 
Python basics
Python basicsPython basics
Python basics
 

Similar to Python for Beginners(v1)

PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...manikamr074
 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.pptVicVic56
 
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdf
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdfCode In PythonFile 1 main.pyYou will implement two algorithms t.pdf
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdfaishwaryaequipment
 
1. python programming
1. python programming1. python programming
1. python programmingsreeLekha51
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxusvirat1805
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txvishwanathgoudapatil1
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data sciencedeepak teja
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizeIruolagbePius
 
Python lab basics
Python lab basicsPython lab basics
Python lab basicsAbi_Kasi
 
FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...
FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...
FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...admin369652
 
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network InstituteScode Network Institute
 

Similar to Python for Beginners(v1) (20)

PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.ppt
 
Python basics
Python basicsPython basics
Python basics
 
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdf
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdfCode In PythonFile 1 main.pyYou will implement two algorithms t.pdf
Code In PythonFile 1 main.pyYou will implement two algorithms t.pdf
 
1. python programming
1. python programming1. python programming
1. python programming
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. tx
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Python
PythonPython
Python
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
 
Python lab basics
Python lab basicsPython lab basics
Python lab basics
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...
FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...
FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...
 
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
 

More from Panimalar Engineering College (8)

Python for Data Science
Python for Data SciencePython for Data Science
Python for Data Science
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
Cellular Networks
Cellular NetworksCellular Networks
Cellular Networks
 
Wireless Networks
Wireless NetworksWireless Networks
Wireless Networks
 
Wireless Networks
Wireless NetworksWireless Networks
Wireless Networks
 
Multiplexing,LAN Cabling,Routers,Core and Distribution Networks
Multiplexing,LAN Cabling,Routers,Core and Distribution NetworksMultiplexing,LAN Cabling,Routers,Core and Distribution Networks
Multiplexing,LAN Cabling,Routers,Core and Distribution Networks
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Python for Beginners(v1)

  • 1. Dr.M.Rajendiran Dept. of Computer Science and Engineering Panimalar Engineering College
  • 2. Install Python 3 On Ubuntu Prerequisites Step 1.A system running Ubuntu Step 2.A user account with sudo privileges Step 3.Access to a terminal command-line (Ctrl–Alt–T) Step 4.Make sure your environment is configured to use Python 3.8 2
  • 3. Install Python 3 Now you can start the installation of Python 3.8. $sudo apt install python3.8 Allow the process to complete and verify the Python version was installed successfully $python ––version 3
  • 4. Installing and using Python on Windows is very simple. Step 1: Download the Python Installer binaries Step 2: Run the Executable Installer Step 3: Add Python to environmental variables Step 4: Verify the Python Installation 4
  • 5. Python Installation Open the Python website in your web browser. https://www.python.org/downloads/windows/ Once the installer is downloaded, run the Python installer. Add the following path C:Program FilesPython37-32: for 64-bit installation Once the installation is over, you will see a Python Setup Successful window. You are ready to start developing Python applications in your Windows 10 system. 5
  • 6. Introduction Python is a general-purpose interpreted, interactive, object- oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Python got its name from “Monty Python’s flying circus”. Python was released in the year 2000. Python is interpreted Python is processed at runtime by the interpreter. You do not need to compile your program before executing it.
  • 7. Introduction Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. Python is Object-Oriented: Python supports Object- Oriented style or technique of programming that encapsulates code within objects. Python is a Beginner's Language: Python is a great language for the beginner level programmers and supports the development of a wide range of applications.
  • 9. Applications Bit Torrent(a stream flowing with great force) file sharing Google search engine, YouTube Intel, Cisco, HP, IBM i–Robot NASA(National Aeronautics and Space Administration) Facebook, Drop box
  • 10. Applications Python interpreter: 1.Interpreter To execute a program in a high-level language by translating it one line at a time. 2.Compiler To translate a program written in a high-level language into a low-level language all at once, in preparation for later execution.
  • 11. Modes of python interpreter Python Interpreter is a program that reads and executes python code. It uses two modes of execution. 1. Interactive mode 2. Script mode 1.Interactive mode Interactive Mode, as the name suggests, allows us to interact with operating system. When we type python statement, interpreter displays the result(s) immediately.
  • 12. Modes of python interpreter Advantages: Python, in interactive mode, is good enough to learn, experiment or explore. Working in interactive mode is convenient for beginners and for testing small pieces of code Drawback: We cannot save the statements and have to retype all the statements once again to re-run them. In interactive mode, you type python programs and the interpreter displays the result.
  • 13. Modes of python interpreter 2.Script mode In script mode, we type python program in a file and then use interpreter to execute the content of the file. Scripts can be saved to disk for future use. Python scripts have the extension .py, meaning that the filename ends with .py Save the code with filename.py and run the interpreter in script mode to execute the script.
  • 14. Integrated Development Learning Environment (IDLE) It a graphical user interface which is completely written in python. It is bundled with the default implementation of the python language and also comes with optional part of the python packaging. Features Multi-window text editor with syntax highlighting. Auto completion with smart indentation. Python shell to display output with syntax highlighting.
  • 15. VALUES AND DATA TYPES Values Value can be any letter, number or string. Values are different data types Eg: 2, 42.0, and 'Hello, World!'. Data type Every value in python has a data type. It is a set of values, and the allowable operations on those values. Python has five standard data types:
  • 16. VALUES AND DATA TYPES 1.Numbers  It stores numerical values.  This data type is immutable (i.e. values/items cannot be changed). Python supports following number types 1. Integers 2. Floating point numbers 3. Complex numbers.
  • 17. VALUES AND DATA TYPES 1.1Integer Integers are the whole numbers consisting of positive(+ve) or negative(– ve) sign. Integers can be any length, it is only limited by the memory available Example: a=10 a=eval(input(“enter a value”)) a=int(input(“enter a value”)) 1.2 Float It has decimal part and fractional part. It is accurate upto 15 decimal places.
  • 18. VALUES AND DATA TYPES Example: a=3.15 a=eval(input(“enter a value”)) a=float(input(“enter a value”)) 1.3 Complex It is a combination of real and imaginary part. Example: 2+5j a+bi
  • 19. VALUES AND DATA TYPES 2.Boolean Boolean data type have two values. It has either 0 or 1. 0 means False 1 means True True and False is a keyword. Example: >>> 3==5 False >>> True+True 2 >>> False+True 1 >>> False*True 0
  • 20. VALUES AND DATA TYPES 3.Sequence  A sequence is an ordered collection of items, indexed by positive integers.  It is a combination of mutable (value can be changed) and immutable (values cannot be changed) data types. There are three types of sequence data type available in python, they are 1. Strings 2. Lists 3. Tuples
  • 21. VALUES AND DATA TYPES 3.1 Strings  String is defined as a continues set of characters represented in quotation marks (either single quotes ( ‘ ) or double quotes ( “ ).  An individual character in a string is accessed using a subscript (index).  The subscript should always be an integer (positive or negative).  A subscript starts from 0 to n-1.  Strings are immutable i.e. the contents of the string cannot be changed after it is created.  Python will get the input at run time by default as a string.  Python does not support character data type. A string of size 1 can be treated as characters.
  • 22. VALUES AND DATA TYPES 1. single quotes (' ') 2. double quotes (" ") 3. triple quotes(“”” “”””) Operations on string 1. Indexing 2. Slicing 3. Concatenation 4. Repetitions 5. Member ship
  • 23. VALUES AND DATA TYPES . Indexing >>>a=”HELLO” >>>print(a[0]) >>>H >>>print(a[1]) >>>O Positive indexing helps in accessing the string from the beginning. Negative subscript helps in accessing the string from the end. Slicing print[0:4] – HELL print[ :3] – HEL print[0: ] HELLO The slice[n : m] operator extracts sub string from the strings. A segment of a string is called a slice. Concatenation a=”raj” b=”man” print(a+b) rajman The + operator joins the text on both sides of the operator. Repetitions a=”welcome ” print(a*3) welcome welcome welcome The * operator repeats the string on the left hand side times the value on right hand side. Membership >>> s="good morning" >>>"m" in s True >>> "a" not in s True Using membership operators to check a particular character is in string or not. Returns true if present
  • 24. VALUES AND DATA TYPES 3.2 Lists  List is an ordered sequence of items. Values in the list are called elements or items.  Values are separated by commas and enclosed within square brackets[].  Items in the lists can be different data types.  Lists are mutable(values of list can be changed) Operations on list 1. Indexing 2. Slicing 3. Concatenation 4. Repetitions
  • 25. VALUES AND DATA TYPES .create a list >>> a=[2,3,4,5,6,7,8,9,10] >>> print(a) [2, 3, 4, 5, 6, 7, 8, 9, 10] This is way we can create a list at compile time Indexing >>>print(a[0]) 2 >>> print(a[8]) 10 >>> print(a[1]) 10 Accessing the item in the position 0 Accessing the item in the position 8 Accessing a last element using negative indexing. Slicing >>> print(a[0:3]) [2, 3, 4] >>> print(a[0:]) [2, 3, 4, 5, 6, 7, 8, 9, 10] >>> print(a[:8]) [2, 3, 4, 5, 6, 7, 8, 9] Printing a part of the string. Concatenation >>>b=[20,30] >>> print(a+b) [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30] Adding and printing the items of two lists. Repetition >>> print(b*3) [20, 30, 20, 30, 20, 30] Create a multiple copies of the same string.
  • 26. VALUES AND DATA TYPES . Updating the list >>> print(a[2]) 4 >>> a[2]=100 >>> print(a) [2, 3, 100, 5, 6, 7, 8, 9, 10] Updating the list using index value Inserting an element >>> a. insert(0,“tham") >>> print(a) a=[“tham”,2,3,4,5,6,7,8,9,10] Inserting an element in 0th position Removing an element >>> a. remove(“tham”) >>> print(a) a=[2,3,4,5,6,7,8,9,10] Removing an element by giving the element directly
  • 27. VALUES AND DATA TYPES 3.3Tuple  A tuple is an ordered sequence of items same as list.  The set of elements is enclosed in parenthesis instead of square brackets.  A tuple is an immutable. i.e. cannot be modified.  Tuples are faster than lists.  Tuples can be used as keys in dictionaries.  Tuples are used to write-protect data and cannot be change dynamically  Tuple have no append or extend method.  Elements can not be removed from a tuple.
  • 28. VALUES AND DATA TYPES Operations on Tuple 1. Indexing 2. Slicing 3. Concatenation 4. Repetitions
  • 29. VALUES AND DATA TYPES . Creating a tuple >>>a=(20,40,60,”apple”,”ball”) Creating the tuple with elements of different data types. Indexing >>>print(a[0]) 20 >>> a[2] 60 Accessing the item in the position 0 Accessing the item in the position 2 Slicing >>>print(a[1:3]) (40,60) Displaying items from 1st till 2nd. Concatenation >>> b=(2,4) >>>print(a+b) >>>(20,40,60,”apple”,”ball”,2,4) Adding tuple elements at the end of another tuple elements Repetition >>>print(b*2) >>>(2,4,2,4) repeating the tuple in n no of times updating a tuple >>>a[2]=100 Type Error: 'tuple' object does not support item assignment Altering the tuple data type leads to error.
  • 30. VALUES AND DATA TYPES 4.Dictionaries Dictionaries are unordered sets. Dictionary is created by using curly braces. i,e. { } Dictionaries are accessed via keys. A dictionary is an associative array. Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are key value-pairs Dictionaries don't support the sequence data types like strings, tuples and lists.
  • 31. VALUES AND DATA TYPES 5.Sets The set datatype is an unordered collection of unique items The collection is mutable.(i.e. can be add or remove) Set is defined by value separated by comma inside curly braces.{} It has no duplicate entry. Creating a dictionary >>>a={'name':"abi",'age':18,'mark':1 00} >>>print(a) {'name': 'abi', 'age': 18, 'mark': 100} Creating the dictionary with elements of different data types. Indexing >>>print(a['name']) abi Accessing the item with keys.
  • 32. VALUES AND DATA TYPES Example: a={1,2,3,4,5,6,7,6,7} print(a) a={1,2,3,4,5,6,7} Scalar type A scalar is a type that can have a single value such as 5,3.14, “THAM” Example: int, float, complex, boolean and string Escape sequence n – move to newline t – move one tap space horizontally v – move in space vertically b – back space
  • 33. VARIABLES A variable is an identifier that refers to a value While creating a variable, memory space is reserved in memory Based on the data type of a variable, the interpreter allocates memory The assignment statements are used to create a new variable and assign values to them. Variable names can contain letters, underscore and numbers but do not start with numbers. Underscore(_) can be used in variable names. Example: a=5 // single assignment a,b,c=2,3,4 // multiple assignment a=b=c=2 //assigning one value to multiple variables
  • 34. KEYWORDS Keywords are the reserved words in python. We cannot use a keyword as variable name, function name or any other identifier. They are used to define the syntax and structure of the python language. Keywords are case sensitive.
  • 35. IDENTIFIERS Identifier is the name given to entities like class, functions, variables etc. in python. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). An identifier cannot start with a digit. Keywords cannot be used as identifiers. Cannot use special symbols like !, @, #, $, % etc. in our identifier. Identifier can be of any length. Valid Identifiers num,Num,Num1,_num,num_temp2,IF,Else Invalid Identifiers Num 1,num 1,addition of program,1Num,num.no,if,else
  • 36. STATEMENTS Instructions that a python interpreter can executes are called statements. A statement is a unit of code like creating a variable or displaying a value. >>> n = 17 >>> print(n) Here, The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n. There are two types of statements available 1. single line statements 2. multi line statements
  • 37. STATEMENTS 1.Single line statements single line statements are end with newline Examples: a=1 b=2 c=a+b 2.Multiline statements python allows the user to write multi line statement using line continuation character () to denote that the line should continue. Example: total=mark1+ mark2+ mark3
  • 38. INPUT AND OUTPUT INPUT Input is a data entered by user in the program. In python, input () function is available for input. Syntax: variable = input (“data”) Example: a=input("enter the name:") Data type Compile time Run time int a=10 a=int(input(“enter a”)) float a=10.5 a=float(input(“enter a”)) string a=”panimalar” a=input(“enter a string”) list a=[20,30,40,50] a=list(input(“enter a list”)) tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))
  • 39. INPUT AND OUTPUT OUTPUT An output can be displayed to the user using print statement. Syntax: print (expression/constant/variable) Example: print ("Hello") // Hello print(5) //5 print(3+5) //8 print(c)
  • 40. COMMENTS Comments are used to provide more details about the program like name of the program, author of the program, date and time, etc. Types of comments 1. Single line comments 2. Multi line comments 1.Single line comments(#) A hash sign (#) is the beginning of a comment. Anything written after # in a line is ignored by interpreter. Example: Percentage = (minute * 100) / 60 # calculating percentage of an hour
  • 41. COMMENTS 2.Multi line comments(“””……”””) Multiple line comments can be written using triple quotes “”” ……….””” Example: “”” This program is created by Robert in Dell lab on 12/12/20 based on newtons method”””
  • 42. LINES AND INDENTATION Most of the programming languages like C, C++, Java use braces { } to define a block of code. But, python uses indentation. Blocks of code are denoted by line indentation. It is a space given to the block of codes for class and function definitions or flow control. Example: a=3 b=1 if a>b: print("a is greater") else: print("b is greater")
  • 43. TUPLE ASSIGNMENT A tuple using a single assignment statement. Python has a very powerful tuple assignment. Tuple of variables on the left to be assigned values from a tuple on the right. The left side is a tuple of variables, the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. (a,b,c)=(3,4,5) (a, b, c, d) = (1, 2, 3) ValueError: need more than 3 values to unpack Swapping two numbers using tuple (a, b) = (b, a)
  • 44. OPERATORS An operator is symbol that tells the compiler to perform specific mathematical or logical manipulations. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator. Types of Operators 1. Arithmetic Operators 2. Comparison (Relational) Operators 3. Assignment Operators 4. Logical Operators 5. Bitwise Operators 6. Membership Operators 7. Identity Operators
  • 45. OPERATORS Arithmetic operators They are used to perform mathematical operations like addition, subtraction, multiplication etc. Operator Description Example a=9,b=2 + Addition Adds values on either side of the operator. a + b = 11 - Subtraction Subtracts operand. Right hand operand from left hand a – b = 7 * Multiplication Multiplies values on either side of the operator a * b = 18 / Division Divides left hand operand by right hand operand b / a = 4 % Modulus Divides left hand operand by right hand operand and returns remainder b % a = 1 ** Exponent Performs operators exponential (power) calculation on operators a**b =9 to the power 2 // Floor Division The division of operands where the result is the quotient in which the digits after the decimal point are removed 5//2=4.0
  • 46. OPERATORS Comparison (Relational) Operators Comparison operators are used to compare values. It either returns True or False according to the condition. Operator Description Example a=10,b=20 == If the values of two operands are equal, then the condition becomes true. (a == b) is not true. != If values of two operands are not equal, then condition becomes true. (a!=b) is true > If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true. < If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true. >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true. <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.
  • 47. OPERATORS Assignment Operators Assignment operators are used in Python to assign values to variables. Operator 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
  • 48. OPERATORS Logical Operators Logical operators are and, or, not operators. . %= 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 Operator Meaning Example and True if both the operands are true x and y or True if either of the operands is true x or y not True if operand is false (complements the operand) not x
  • 49. OPERATORS Bitwise Operators Bitwise operators act on operands as if they are binary digits. They operate bit by bit. Let x = 10 (0000 1010) and y = 4 (0000 0100) Operator Meaning Example & Bitwise AND x & y = 0 (0000 0000) | Bitwise OR x | y = 14 (0000 1110) ~ Bitwise NOT ~x = -11 (1111 0101) ^ Bitwise XOR x ^ y = 14 (0000 1110) >> Bitwise right shift x >> 2 = 2 (0000 0010) << Bitwise left shift x << 2 = 40 (0010 1000)
  • 50. OPERATORS Membership Operators Evaluates to find a value or a variable is in the specified sequence of string, list, tuple, dictionary or not. Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are used. Example: x=[5,3,6,4,1] >>> 5 in x True >>> 5 not in x False Operator Meaning Example in True if value/variable is found in the sequence 5 in x not in True if value/variable is not found in the sequence 5 not in x
  • 51. OPERATORS Identity Operators They are used to check if two values (or variables) are located on the same part of the memory. Example x = 5 y = 5 a = 'Hello' b = 'Hello' print(x is not y) // False print(a is b)//True Operator Meaning Example is True if the operands are identical x is True is not True if the operands are not identical x is not True
  • 52. Operator Precedence When an expression contains more than one operator, the order of evaluation depends on the rules of precedence. Operator Description () Parenthesis ** Exponentiation (raise to the power) ~ + - Complement, unary plus and minus * / % // Multiply, divide, modulo and floor division + - Addition and subtraction >> << Right and left bitwise shift & Bitwise 'AND' ^ | Bitwise exclusive `OR' and `OR' <= < > >= Comparison operators <> == != Equality operators = %= /= //= -= += *= **= Assignment operators Is, is not Identity operators In, not in Membership operators and,or,not Logical operators
  • 53. Expressions An expression is a combination of values, variables, and operators. A value and a variable itself considered as an expression. The following are all legal expressions: >>> 42 42 >>> a=2 >>> a+3+2 7 >>> z=("hi"+"friend") >>> print(z) hifriend
  • 54. FUNCTIONS Function is a sub program which consists of set of instructions used to perform a specific task. A large program is divided into number of sub program called function. Need for Function When the program is too complex and large they are divided into sub program. Each sub program is separately coded and combined into single program. Each subprogram is called as function. Debugging, Testing and maintenance becomes easy when the program is divided into subprograms. Functions are used to avoid rewriting same code again and again in a program. Function provides code re-usability The length of the program is reduced.
  • 55. FUNCTIONS TYPES OF FUNCTION 1. Built in function 2. user defined function 1.Built in function Built in functions are the functions that are already created and stored in python. These built in functions are always available for usage and accessed by a programmer. It cannot be modified.
  • 56. FUNCTIONS . Built in function Description >>>max(3,4) 4 # returns largest element >>>min(3,4) 3 # returns smallest element >>>len("hello") 5 #returns length of an object >>>range(2,8) [2, 3, 4, 5, 6, 7] #returns range of given values >>>round(7.8) 8.0 #returns rounded integer of the given number >>>chr(5) x05' #returns a character (a string) from an integer >>>float(5) 5.0 #returns float number from string or integer >>>int(5.0) 5 # returns integer from string or float >>>pow(3,5) 243 #returns power of given number >>>type( 5.6) <type 'float'> #returns data type of object to which it belongs >>>t=tuple([4,6.0,7]) >>>t (4, 6.0, 7) # to create tuple of items from list >>>print("good morning") Good morning # displays the given object
  • 57. FUNCTIONS 2.User defined function User defined functions are the functions that programmers create for their requirement and use. These functions can then be combined to form module which can be used in other programs by importing them. Advantages The programmer can write their own functions which are known as user defined function. These functions can create by using keyword def. Example: add(), sub() Elements of User defined function There are two elements in user defined function. 1. function definition 2. function call
  • 58. FUNCTIONS 1.Function definition A function definition specifies the name of a new function and the sequence of statements that execute when the function is called. Syntax: def function name(parameter list): ----Function header statement 1 statement 2 .... .... statement n def is a keyword that indicates that this is a function definition. The rules for function names are the same as for variable names The first line of the function definition is called the header, the rest is called body of function. The header has to end with a colon and the body has to be indented. The function contains any number of statements. Parameter list contains list of values used inside the function.  Body of the function
  • 59. FUNCTIONS Example: def add(): a=eval(input(“enter a value”)) b=eval(input(“enter a value”)) c=a+b print(c) 2.Function call() A function is called by using the function name followed by parenthesis(). Argument is a list of values provided to the function when the function is called The statements inside the function does not executed until the function is called. Function can be called n number of times
  • 60. FUNCTIONS Syntax: function name(argument list) Example: add() or add(a,b) Flow of Execution The order in which statements are executed is called the flow of execution Program execution starts from first statement. One statement is executed at a time from top to bottom. Function definitions do not alter the flow of execution of the program. The statement inside the function are not executed until the function is called.
  • 61. FUNCTIONS When a function is called, the control flow jumps to the body of the function, execute the statements and return back to the place in the program where the function call was made.
  • 62. FUNCTION PROTOTYPES Based on arguments and return type functions are classified into four types. 1. Function without arguments and without return type 2. Function with arguments and without return type 3. Function without arguments and with return type 4. Function with arguments and with return type
  • 63. FUNCTION PROTOTYPES 1. Function without arguments and without return type In this type no argument is passed through the function call and no output is return to main function The sub function will read the input values perform the operation and print the result in the same block. Example def add(): a=int(input("enter a")) b=int(input("enter b")) c=a+b print(c) add() Output: enter a 5 enter b 10 15
  • 64. FUNCTION PROTOTYPES 2. Function with arguments and without return type Arguments are passed through the function call but output is not return to the main function. Example: def add(a,b): c=a+b print(c) a=int(input("enter a")) b=int(input("enter b")) add(a,b) OUTPUT: enter a 5 enter b 10 15
  • 65. FUNCTION PROTOTYPES 3. Function without arguments and with return type In this type no argument is passed through the function call but output is return to the main function. Example: def add(): a=int(input("enter a")) b=int(input("enter b")) c=a+b return c c=add() print(c) OUTPUT: enter a 5 enter b 10 15
  • 66. FUNCTION PROTOTYPES 4. Function with arguments and with return type In this type arguments are passed through the function call and output is return to the main function. Example: def add(a,b): c=a+b return c a=int(input("enter a")) b=int(input("enter b")) c=add(a,b) print(c) OUTPUT: enter a 5 enter b 10 15
  • 67. FRUITFUL FUNCTION Fruitful functions are functions that return value or A function that yields a return value. Example: Root=sqrt(25) Example: def add(): a=10 b=20 c=a+b return c c=add() print(c)
  • 68. VOID FUNCTION Void function is a function that always return none. It represents the absence of value. Example: print("Hello") Example: def add(): a=10 b=20 c=a+b print(c) add()
  • 69. PARAMETERS AND ARGUMENTS Parameters  Parameters are the value(s) provided in the function header within parenthesis.  These are the values required by function to work.  If there is more than one value, separated by comma. Example: def add(a,b): Arguments  Arguments are the value(s) provided in function call statement.  List of arguments should be same way as parameters are listed.  Bounding of parameters to arguments is done 1:1, and there should be same number and type of arguments as mentioned in parameter list. Example: add(a,b)
  • 70. PARAMETERS AND ARGUMENTS Return Statement  The return statement is used to exit a function and go back to the place from where it was called.  If the return statement has no arguments, then it will not return any values. But exits from function. Syntax: return variable Example: def add(a,b): c=a+b return c a=5 b=4 c=add(a,b) print(c) No Example Description 1 return a return 1 variable 2 return a,b return 2 variables 3 return a,b,c return 3 variables 4 return a+b return expression 5 return 8 return value
  • 71. PARAMETERS AND ARGUMENTS ARGUMENTS TYPES You can call a function by using the following types of formal arguments 1. Required arguments 2. Keyword arguments 3. Default arguments 4. Variable-length arguments 1.Required Arguments:  The number of arguments in the function call should match exactly with the function definition.
  • 72. PARAMETERS AND ARGUMENTS . Example Output def student( name, roll ): print(name,roll) student("george",98) George 98 def student( name, roll ): print(name,roll) student(101,”rithika”) 101 rithika def student( name, roll ): print(name,roll) student(101) student() missing 1 required positional argument: 'name' def student( name, roll ): print(name,roll) student() student() missing 2 required positional arguments: ‘name' and ‘roll'
  • 73. PARAMETERS AND ARGUMENTS 2.Keyword Arguments  Python interpreter is able to use the keywords provided to match the values with parameters even though if they are arranged in out of order. Example Output def student( name, roll,mark): print(name,roll,mark) student (mark=90,roll=102,name="bala") bala 102 90 def student( name, roll,mark): print(name,roll,mark) student (name="bala", roll=102, mark=90) bala 102 90
  • 74. PARAMETERS AND ARGUMENTS 3.Default Arguments  Assumes a default value if a value is not provided in the function call for that argument.  It allows us to miss one or more arguments. Example Output def student( name="raja", roll=101,mark=50): print(name,roll,mark) student (mark=90,roll=102,name="bala") bala 102 90 def student( name="raja", roll=101,mark=50): print(name,roll,mark) student (name="bala", roll=102) bala 102 90 def student( name="raja", roll=101,mark=50): print(name,roll,mark) student () raja 101 50
  • 75. PARAMETERS AND ARGUMENTS 4.Variable length Arguments  If we want to specify more arguments than function header parameter, variable length arguments are used.  It is denoted by * symbol before parameter. Example Output def student( name,mark): print(name,mark) student (“bala”,90) bala 90 def student( name, roll,*mark): print(name,roll,mark) student ("raja",101,90,80) raja 101 90 80
  • 76. MODULES A module is a file containing python definitions, functions, statements and instructions. Standard library of python is extended as modules. Programmer needs to import the module. Once we import a module, we can use to any of its functions or variables in our code. There is large number of standard modules also available in python. Standard modules can be imported the same way as import our user-defined modules.
  • 77. MODULE Two ways to import your module: 1. import keyword 2. from keyword 1.Import keyword  Import keyword is used to get all functions from the module.  Every module contains many function.  To access one of the function , you have to specify the name of the module and the name of the function separated by dot .  This format is called dot notation. Syntax: import module_name module_name.function_name(variable)
  • 78. MODULE Importing built-in module import math x=math.sqrt(25) print(x) Importing user-defined module cal.py def add(a,b): c=a+b return c import cal x=cal.add(5,4) print(x)
  • 79. MODULE 2.from keyword  from keyword is used to get only particular function from the module. Syntax: from module_name import function_name #Importing built-in module from math import sqrt x=sqrt(25) print(x) #Importing user-defined module from cal import add x=add(5,4) print(x) add.py def add(a,b): c=a+b return c
  • 80. MODULE 2.from keyword  from keyword is used to get only particular function from the module. Syntax: from module_name import function_name #Importing built-in module from math import sqrt x=sqrt(25) print(x) #Importing user-defined module from cal import add x=add(5,4) print(x) add.py def add(a,b): c=a+b return c
  • 81. BUILT-IN MODULES . Built-in Function Description math.ceil(x) Return the ceiling of x, the smallest integer greater than or equal to x math.floor(x) Return the floor of x, the largest integer less than or equal to x. math.factorial(x) Return x factorial math.sqrt(x) Return the square root of x math.log(x) Return the natural logarithm of x math.log10(x) Returns the base-10 logarithms math.log2(x) Return the base-2 logarithms math.sin(x) Returns sin of x radians math.cos(x) Returns cosine of x radians
  • 82. BUILT-IN MODULES Generate pseudo-random numbers Random Function Description random.randrange(stop) Return random numbers from 0 random.randrange(start, stop[, step]) Return the random numbers in a range random.uniform(a, b) Return a random floating point number
  • 83. SAMPLE PROGRAMS . Swapping two number Output a = int(input("Enter a value ")) b = int(input("Enter b value ")) c = a a = b b = c print("a=",a,"b=",b,) Enter a value 5 Enter b value 8 a=8 b=5 Distance between two points Output import math x1=int(input("enter x1")) y1=int(input("enter y1")) x2=int(input("enter x2")) y2=int(input("enter y2")) distance =math.sqrt((x2- x1)**2)+((y2-y1)**2) print(distance) enter x1 7 enter y1 6 enter x2 5 enter y2 7 2.5
  • 84. SAMPLE PROGRAMS . Circulate n numbers Output a=list(input("enter the list")) print(a) for i in range(1,len(a),1): print(a[i:]+a[:i]) enter the list '1234' ['1', '2', '3', '4'] ['2', '3', '4', '1'] ['3', '4', '1', '2'] ['4', '1', '2', '3']
  • 85. Practice An evaluate the following expressions No. Expression output 1 a=9-12/3+3*2-1 Ans:a=10 2 A=2*3+4%5-3/2+6 Ans:A=15 3 find m=? m=-43||8&&0||-2 Ans:m=1 4 a=2,b=12,c=1 d=a<b>c Ans:d=0 5 a=2,b=12,c=1 d=a<b>c-1 Ans:d=1 6 a=2*3+4%5-3//2+6 Ans:a=15
  • 86. .