Python Programming
Python Programming
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
Why Python?
● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
● Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a functional way.
Good to know
● The most recent major version of Python is Python 3, which we shall be using in this tutorial.
However, Python 2, although not being updated with anything other than security updates, is
still quite popular.
● In this tutorial Python will be written in a text editor. It is possible to write Python in an
Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which
are particularly useful when managing larger collections of Python files.
● Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
● Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
● Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.
Example
print("Hello, World!")
Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line ata time.
This is an example of a print statement. It displays a result on the screen. In this case, the result
is the words.
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.
It is bundled with the default implementation of the python language and also comes
with optional part of the Python packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.
Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable, that
variable is declared automatically.
Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication and division.
There are 7 arithmetic operators in Python :
1. Addition
2. Subtraction
3. Multiplication
34
4. Division
5. Modulus
6. Exponentiation
7. Floor division
1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values.
Example :
val1 = 2
val2 = 3
print(res)
Output :
5
2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract the second
value from the first value.
Example :
val1 = 2
val2 = 3
print(res)
Output :
-1
3. Multiplication Operator : In Python, * is the multiplication operator. It is used to find the product
of 2 values.
Example :
val1 = 2
35
val2 = 3
print(res)
Output :
6
4. Division Operator : In Python, / is the division operator. It is used to find the quotient when first
operand is divided by the second.
Example :
val1 = 3
val2 = 2
print(res)
Output :
1.5
5. Modulus Operator : In Python, % is the modulus operator. It is used to find the remainder when
first operand is divided by the second.
Example :
val1 = 3
val2 = 2
36
res = val1 % val2
print(res)
Output :
1
6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used to raise the first
operand to power of second.
Example :
val1 = 2
val2 = 3
print(res)
Output :
8
7. Floor division : In Python, // is used to conduct the floor division. It is used to find the floorof the
quotient when first operand is divided by the second.
Example :
val1 = 3
val2 = 2
print(res)
Output :
37
1
Numbers:
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) datatypes
38
There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
Strings:
Indexing:
39
Positive indexing helps in accessing the string from the beginning
● Negative subscript helps in accessing the string from the end.
● Subscript 0 or –ven(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H”
● Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership
Creating a string >>> s="good morning" Creating the list with elements of
different data types.
Indexing >>>print(s[2] ❖ Accessing th ite i th
)o position0
>>>print(s[6]) ❖ Accessing e m n e
O position2
th ite i th
e m n e
40
in, not in >>> s="good morning" Using membership operators to
(membership >>>"m" in s True check a particular character is in
operator) >>> "a" not in s string or not. Returns true if
True present.
Lists
❖ List is an ordered sequence of items. Values in the list are called elements /items.
❖ It can be written as a list of comma-separated items (values) between square brackets[].
❖ Items in the lists can be of different datatypes.
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
41
Creating a list >>>list1=["python", 7.79, 101, Creating the list with
"hello”] elements of different
>>>list2=["god",6.78,9] data types.
Indexing >>>print(list1[0]) python ❖ Accessing the item in
>>>list1[2] the position0
101 ❖ Accessing the item in
the position2
Slicing( >>>print(list1[1:3]) - Displaying items from
ending position -1) [7.79, 101] 1st till2nd.
Slice operator is - Displaying items from
>>>print(list1[1:]) [7.79, 101,
used to extract st
'hello'] 1 position till last.
part of a string, or
some part of a
list
Python
42
Tuple:
❖ A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
❖ A tuple is an immutable list.i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
❖ Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be used.
❖ Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with
"hello”) elements of different data
types.
Indexing >>>print(t[0]) python ❖ Accessing the item in
>>>t[2 the position0
] 101 ❖ Accessing the item in
the position2
Slicing( po ending >>>print(t[1:3]) ❖ Displaying items
sition -1) (7.79, 101) from1st till2nd.
Altering the tuple data type leads to error. Following error occurs when user tries to do.
43
>>>t[0]="a"
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
Dictionaries:
If you try to access a key which doesn't exist, you will get an error message:
>>>words = {"house" : "Haus", "cat":"Katze"}
>>>words["car"]
Traceback (most recent call last): File
"<stdin>", line 1, in <module>KeyError:
'car'
Data type Compile time Run time
44
STATEMENTS AND EXPRESSIONS:
Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying avalue.
>>> 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.
Expressions:
-An expression is a combination of values, variables, and operators.
42
>>> a=2
>>>a+3+2 7
>>> z=("hi"+"friend")
40
Example:
>>> x=input("enter the name:")
enter the name: george
i t( i / t t/ i bl )
Example:
>>> print ("Hello")
Hello
Operators:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator
Types of Operators:
-Python language supports the following types of operators
● Arithmetic Operators
● Comparison (Relational)Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
● Membership Operators
● Identity Operators
41
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc.
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
Examples O
u
a=10 t
b=5 print("a+b=",a+b) print("a-b=",a- p
b) print("a*b=",a*b)
u
print("a/b=",a/b) print("a%b=",a%b)
print("a//b=",a//b) t:
print("a**b=",a**b) a
+
b
=
1
5
a
-
b
=
5
a*b= 50
42
a =
/ 0
b a
= /
2. /
0 b
a =
% 2
b a**b= 100000
Comparison (Relational)Operators:
● Comparison operators are used to compare values.
● It either returns True or False according to the condition. Assume, a=10 and b=5
43
becomes true. not true.
!= If values of two operands are not equal, then condition becomes (a!=b)
true. is true
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.
>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value of (a <= b) is
right operand, then condition becomes true. true.
Example
O
a=10 u
b=5 print("a>b=>",a>b) t
print("a>b=>",a<b) p
print("a==b=>",a==b) u
print("a!=b=>",a!=b) t:
print("a>=b=>",a<=b) a
print("a>=b=>",a>=b) >
b
=
>
T
r
u
e
a
>
b
=
>
F
a
l
s
e
a
=
=
b
=
44
> b
F =
a >
l F
s a
e l
a! s
= e
b a
= >
> =
T b
r =
u >
e T
a r
> u
= e
Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example
+= Add AND It adds right operand to the left operand and assign the c += a is
result to leftoperand equivalent
to c
=c+a
-= It subtracts right operand from the left operand and c -= a is
Subtract assign the result to left operand equivalent
AND to c
= c -a
*= Multipl It multiplies right operand with the left operand and c *= a is
AN y assign the result to left operand equivalent
D to c
= c *a
/= Divide It divides left operand with the right operand and assign c /= a is
AN the result to left operand equivalent
D to c
= c /ac
/= a is
equivalent
to c
= c /a
45
%= Modulu It takes modulus using two operands and assign the c %= a is
AN s result to left operand equivalent
D to c
=c%a
**= Exponent Performs exponential (power) calculation on c **= a is
AND operators and assign value to the left equivalent
operand to c
= c ** a
//= Floor It performs floor division on operators and assign value c //= a is
Divisio to the left operand equivalent
n to c
= c // a
46
Example Output
Line 1 -
a =21
Value of c
b =10 is 31 Line 2
c=0 - Value of
c=a+b c is 52 Line
print("Line 1 - Value of c is ",c) c += a 3 - Value
print("Line 2 - Value of c is ", c) c *= a of c is 1092
print("Line 3 - Value of c is ",c) c /= a Line 4 -
print("Line 4 - Value of c is ", c) c = 2 Value of c
c %=a is 52.0 Line
print("Line 5 - Value of c is ",c) c **= a 5 - Value
print("Line 6 - Value of c is ",c) c //= a of c is2
print ("Line 7 - Value of c is ", c) Line 6 - Value of
c is 2097152
Line 7 - Value of
c is99864
47
Logical Operators:
-Logical operators are the and, or, not operators.
Output
x
Example a
a = True b = False n
print('a and b is', a and b) print('a or d
b is' ,a or b) print('not a is', not a) y
i
s
F
a
l
s
e
x
o
r
y
i
s
T
r
u
e
n
o
t
x
i
s
F
a
l
s
e
Bitwise Operators:
● A bitwise operation operates on one or more bit patterns at the level of individual bits
Example: Let x = 10 (0000 1010 in
binary)and
49
- e s
V o -
a f 6
l c 1
u i
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a|b; # 61 = 00111101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c c = a^b;
# 49 = 00110001
print "Line 3 - Value of c is ", c c =~a; # - print "Line 4 - Value of c is ", c
61 = 11000011 c = a<<2; # 240 = 11110000
print "Line 5 - Value of c is ", c
c = a>>2; # 15 = 00001111
print "Line 6 - Value of c is ", c
Membership Operators:
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False
50
Identity Operators:
i) They are used to check if two values (or variables) are located on the
same partof the memory.
Example
O
x =5 u
y =5 t
x2 = 'Hello' y2= 'Hello' p
print(x1 is not y1) print(x2 is y2) u
t
F
a
l
s
e
T
r
u
e
51
OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
Operator Description
52
Examples:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 A=6+4- m=-43||8&&0||-2
a=9-4+6-1 1+6 m=- 43||0||-2
a=5+6-1 a=11- A=10-1+6 m=1||-2 m=1
1 a=10 A=9+6 A=15
● Membership Operators
● Identity Operators
Boolean VALUES:
The truth values of an expression is stored as a python data type called bool. There are only two
such values in this data type. True and False.
Boolean Data Types
In the below program we find out the data types of True and False Boolean values.
Example
print(True)
print(type(True))
print(False)
print(type(False))
Output
Running the above code gives us the following result −
True
<class 'bool'>
False
<class 'bool'>
Boolean expression
61
Boolean expression is an expression that evaluates to a Boolean value. It almost always involves a
comparison operator. In the below example we will see how the comparison operators can give us
the Boolean values. The bool() method is used to return the truth value of an ex[resison.
Example
Syntax: bool([x])
Returns True if X evaluates to true else false.
Without parameters it returns false.
Below we have examples which use numbers streams and Boolean values as parameters to the bool
function. The results come out us true or false depending on the parameter.
Expression:
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators,
and sometimes parenthesis. The result of this type of expression is also a numeric value. The
operators used in these expressions are arithmetic operators like addition, subtraction, etc. Here
are some arithmetic operators in Python:
perator
s Syntax Functioning
+ x+y Addition
62
– x–y Subtraction
Multiplicatio
* x*y n
/ x/y Division
// x // y Quotient
% x%y Remainder
Exponentiati
** x ** y on
3. Integral Expressions: These are the kind of expressions that produce only integer results after
all computations and type conversions.
Example:
● Python3
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.
Example:
● Python3
# Floating Expressions
63
a = 13
b=5
c=a/b
print(c)
Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both
sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and
then compared as per relational operator and produce a boolean output in the end. These
expressions are also called Boolean expressions.
Example
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6. Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9.
As we know it is not correct, so it will return False. Studying logical expressions, we also come
across some logical operators which can be seen in logical expressions most often. Here are some
logical operators in Python:
64
r
Example:
Let’s have a look at an exemplar code :
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are performed at
bit level.
Example:
65
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a single
expression, and that will be termed as combinational expressions.
Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
But when we combine different types of expressions or use multiple operators in a single
expression, operator precedence comes into play.
Conditional Statements:
Conditional if
Alternative if… else
66
Chained if…elif…else
Nested if….else
Conditional (if):
conditional (if) is used to test a condition, if the condition is true the
statements inside if will be executed.
syntax:
Flowchart:
67
Alternative (if-else):
In the alternative the condition must be true or false. In this else statement can be
combined with if statement. The else statement contains the block of code that executes
when the condition is false. If the condition is true statements inside the if get executed
otherwise else part gets executed. The alternatives are called branches, because they are
branches in the flow of execution.
syntax:
Flowchart:
Examples:
68
Chained conditionals (if-elif-else)
The elif is short for else if.
● This is used to check more than one condition.
Flowchart:
69
70
student mark system Output
mark=eval(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
Nested conditionals
One conditional can also be nested within another. Any number of condition can be
nested inside one another. In this, if the condition is true it checks another if condition1. If
both the conditions are true statement1 get executed otherwise statement2 get execute. if
the condition is false statement3 gets executed
Syntax
71
Flowchart:
Example:
if(a>c):
print(“the greatest no
is”,a)
else
if(b>c):
print(“the greatest no
else
print(“the greatest no
i. sta
te
ii. whi
le
iii. for
iv.
re
State:
Transition from one process to another process under specified condition with in a time is
called
state.
While loop:
While loop statement in Python is used to repeatedly executes set of statement
as long as a given condition is true.
In while loop, test expression is checked first. The body of the loop is entered only if
the test expression is True. After one iteration, the test expression is checked again.
This process continues until the test expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while start with indentation and the first unintended line marks
the end.
Syntax:
Flow chart:
73
Examples:
74
Reverse the given number: output
n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 321
a=n%10
sum=sum*10+a
n=n//10
print(sum)
n=eval(input("enter
Palindrome or not a number")) enter
outputa number121
org=n The given no is palindrome
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is
palindrome") else:
print("The given no is not palindrome")
75
For loop:
for in range:
syntax
Flowchart:
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over
a
sequence is called traversal. Loop continues until we reach the last element in
the sequence. The body of for loop is separated from the rest of the code using
indentation.
76
Sequence can be a list, strings or tuples
2
2. For loop in list for i in [2,3,5,6,9]:
3
print(i)
5
6
9
for i in (2,3,1): 2
3. For loop in tuple
print(i) 3
1
Examples:
77
check the no is prime or not output
n=eval(input("enter a number")) enter a no:7
for i in range(2,n): The num is a prime number.
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")
3.Loop Control
Structures BREAK
Break statements can alter the flow of a loop.
It terminates the current
loop and executes the remaining statement outside the loop.
If the loop has else statement, that will also gets terminated and come out of the loop
completely.
78
Syntax:
break
Flowchart
example Output
for i in "welcome": w
if(i=="c"): e
brea l
k
print(i
)
79
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the
loop.
Syntax: Continue
Flowchart
Example: Output
80
It is used when a statement is required syntactically but you don’t want any code to
execute.
It is a null statement, nothing happens when it is executed.
Syntax:
pas
s
brea
k
Example Output
for i in w
“welcome”: if e
(i == “c”): l
pas c
s o
print( m
i) e
break continue
synta syntax:
x: continue
break
for i in "welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
brea continue
k print(i)
print(i)
81
w w
e e
l l
o
m
e
82
else statement in loops:
If else statement is used in for loop, the else statement is executed when the loop has
reached the
limit.
The statements inside for loop and statements inside else will also execute.
example output
for i in range(1,6): 1
print(i) 2
else: 3
print("the number greater than 6") 4
5 the number greater than 6
Function:
Fruitful function
Void function
A function that returns
Return a value is called fruitful function.
values
Parameters
Example:
Root=sqrt
Local (25) global
and
Example:
scope Function
def add():
83
a=10
b=20
c=a+b
return c
c=add()
print(c)
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2
variables return a+b–
return expression return
8– return value
• When the program is too complex and large they are divided into parts. Each part
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.
Types of function:
Functions can be classified into two categories:
84
i) user defined function
ii) Built in function
i) Built in functions
• Built in functions are the functions that are already created and stored inpython.
• These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.
85
Built in function Description
• defdefinition:
Function keyword(Sub
is used to define a function.
program)
• Give the function name after def keyword followed by parentheses in which arguments are
given.
• End with colon (:)
• Inside the function add the program statements to be executed
• End with or without return statement
86
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1 statement2…
statement n return[expression]
Example:
def
my_add(a,b):
c=a+b
return
c
my_add(x,y)
Flow of Execution:
• The order in which statements are executed is called the flow of execution
• Execution always begins at the first statement of the program.
• Statements are executed 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 are not executed until the function is called.
• Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.
Function Prototypes:
87
i) Function without arguments and without return type
o In this type no argument is passed through the function call and no output is
return to main function
o The sub function will read the input values perform the operation and print
the result in the same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to the main
function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is
return to the main function.
iv) Function with arguments and with return type
o In this type arguments are passed through the function call and output is
return to the main function
Without Return
Type
Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter print(c)
b")) c=a+b a=int(input("enter
print(c) a"))
add() b=int(input("enter
b")) add(a,b)
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
88
89
Parameters And Arguments:
Parameters:
● Parameters are the value(s) provided in the parenthesis when we write function header.
● These are the values required by function to work.
● If there is more than one value required, all of them will be listed in parameter list
separated by
comma.
● Example: defmy_add(a,b):
Arguments :
● Arguments are the value(s) provided in function call/invoke statement.
● List of arguments should be supplied in same way as parameters are listed.
● Bounding of parameters to arguments is done 1:1, and so there should be same
number and type of arguments as mentioned in parameter list.
● Example:my_add(x,y)
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[expression]
Example:
def my_add(a,b):
c=a+b
return
c x=5
y=4
print(my_add(x,y))
Output:
ARGUMENT TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
90
Required Arguments :The number of arguments in the function call should match
exactly with the function definition.
return
91
Output:
Name: georgeAge56
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.
Output:
Name: georgeAge56
DefaultArguments:
Assumes a default value if a value is not provided in the function call for that
defmy_details( name, age=40 ):
my_details(name="george")
argument.
Output:
Name: georgeAge40
Variable lengthArguments
If we want to specify more arguments than specified while defining the function,
variable length arguments are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")
Output:
rajanrahulmichealärjun
92
Local and Global Scope
Global Scope
The scope of a variable refers to the places that you can see or access a variable.
A variable with global scope can be used anywhere in the program.
It can be created by defining a variable outside the function.
Example output
a=50
def add():
b=20
Global Variable
c=a+b
70
print
© Local Variable
def sub():
b=30
c=a-b 20
print
50
©
print(a)
93
Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20
70
c=a+b
Local Variable
print©
def sub():
20
b=30
print error
© error
print(a
)
print(b)
Function Composition:
Function Composition is the ability to call one function from within another function
It is a way of combining functions such that the result of each function is passed as
the argument of the next function.
In other words the output of one function is given as the input of another
function is known as function composition.
94
Recursion
A function calling itself till it reaches the base value - stop point of function
call. Example: factorial of a given number using recursion
Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to
find fact:"))
fact=fact(n)
print("Fact is",fact)
Explanation
Examples:
95
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)
n=eval(input("enter no. to find sum: "))
sum=sum(n)
print("Fact is",sum)
96
97
98