0% found this document useful (0 votes)
318 views

Python CS1002 PDF

This document provides an introduction to Python programming concepts including: 1. Identifiers are used to name variables and must start with a letter or underscore with remaining characters being letters, numbers, or underscores. 2. Variables are used to store values and can be of different data types like integers, floats, strings, and booleans. 3. Basic input and output operations in Python use functions like print() and input() to display output and take user input.

Uploaded by

dhanraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
318 views

Python CS1002 PDF

This document provides an introduction to Python programming concepts including: 1. Identifiers are used to name variables and must start with a letter or underscore with remaining characters being letters, numbers, or underscores. 2. Variables are used to store values and can be of different data types like integers, floats, strings, and booleans. 3. Basic input and output operations in Python use functions like print() and input() to display output and take user input.

Uploaded by

dhanraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 210

VI

Introduction to Python

Section I

Prof. Kalpesh Joshi


VIT, Pune
Identifiers

VI  An identifier is a word used to name things


 One of the thing an identifiers can name is Variable, therefore
variable name is an example of an identifier.
 Identifiers have following forms
 Identifiers must contain at least one character
 The first character must be an alphabetic letter, underscore .

 Remaining can be alphabet, underscore or digit.

 No other characters are permitted in Identifiers .


 Identify the valid Identifier
x,x2,total,sub-total,FLAG,4all,Class
Reserved keywords

VI  Python reserves some words for special use called reserved


keywords.
 None of reserved keywords should be used by Identifiers, if so
it issues error.
example: Class = 15
In above example it will shows syntax error, since class is
Reserve keyword.
Variables

VI  In algebra, variables defines number same python represents


values other than numbers.
ex: x = 10
print(x)
Where x is variable,
= is assignment operator,
10 is value or integer so it prints variable ‘x’.
 Variable names may be any contiguous sequence of
letters,numbers,underscore.
 We can not use reserved word as variable
Comments in python and Indentation in Python

VI
•Anything after #symbol is comment.
ex: print “Hello world”
avg=sum/num #computes the average of values
•Comments are not part of command which can be used by
anyone reading code.
•Indentation : A code block (body of a function, loop etc.)
starts with indentation and ends with the first unindented
line. The amount of indentation is up to you, but it must be
consistent throughout that block.
•Generally four whitespaces are used for indentation and is
preferred over tabs.
Input, Output operation in in python

VI
Python provides numerous built-in functions that are readily
available to us at the Python prompt.
Some of the functions like input() and print() are widely used
for standard input and output operations respectively.
We use the print() function to output data to the standard
output device (screen).
How to read and write in Python
Every program is eventually a data processor, so we should
VI
know how to input and output data within it. There exists a
function, print(), to output data from any Python program. To use
it, pass a comma separated list of arguments that you want to
print to the print() function. Let's see an example. Press "run"
and then "next" to see how the program is being executed line by
line:
print(5 + 10) # Result : 15
print(3 * 7, (17 - 2) * 8) # Result : 21 120
print(2 ** 16) # two stars are used for exponentiation (2 to the
power of 16) # Result : 65536
print(37 / 3) # single forward slash is a division (12.3333)
print(37 // 3) # double forward slash is an integer division #
it returns only the quotient of the division (i.e. no remainder)
print(37 % 3) # percent sign is a modulus operator # it gives
the remainder of the left value divided by the right value ( Result
: 1)
How to read and write in Python

VI To input data into a program, we use input(). This function


reads a single line of text, as a String.

Here's a program that reads the user's name and greets them:

print('What is your name?')


name = input() # read a single line and store it in the variable
"name“
print('Hi ' + name + '!')
Sum of numbers and strings
Let's try to write a program that inputs two numbers and prints their sum. We
VI read the two numbers and store them in the variables a and b using the
assignment operator =. On the left side of an assignment operator we put the
name of the variable. The name could be a string of latin characters (A-Z, a-
z, 0-9, _) but must start with a letter in the range A-Z or a-z. On the right
side of an assignment operator we put any expression that Python can
evaluate. The name starts pointing to the result of the evaluation. Read this
example, run it and look at the output:

a = input()
b = input()
s=a+b
print (s)

Note: After running the example we can see that it prints 57. As we were
taught in school, 5 + 7 gives 12. So, the program is wrong, and it's important
to understand why. The thing is, in the third line s = a + b Python has
"summed" two strings, rather than two numbers. The sum of two strings
in Python works as follows: they are just glued one after another. It's also
sometimes called "string concatenation".
Sum of numbers and strings

VI  Do you see in the variable inspector, on the right hand side,


that the values bound to variables a and b are wrapped in
quotes? That means that the values there are string, not
numbers. Strings and numbers are represented in Python
differently.
Sum of numbers and strings
 All the values in Python are called "objects". Every object has a certain
VI type. The number 2 corresponds to an object "number 2" of type "int"
(i.e., an integer number). The string 'hello' corresponds to an object
"string 'hello'" of type "str". Every floating-point number is represented as
an object of type "float". The type of an object specifies what kind of
operations may be applied to it. For instance, if the two
variables "first" and "second" are pointing to the objects of type int,
Python can multiply them. However, if they are pointing to the objects of
type str, Python can't do that:
first = 5
second = 7
print(first * second)

# you can use single or double quotes to define a string


first = ‘5’
second = ‘’7’’
print(first * second)
Sum of numbers and strings

VI To cast (convert) the string of digits into an integer number, we


can use the function int().
For example, int('23')gives an int object with value 23.
Given the information above, we can now fix the incorrect
output and output the sum of the two numbers correctly:

a = int(input())
b = int(input())
s=a+b
print(s)

Result : if a= 5 and b=7 then output is 12.


Docstrings

VI  Python also has extended documentation capability, called


docstrings.
 Docstrings can be one line, or multiline.
 Python uses triple quotes at the beginning and end of the
docstring:
 Example
Docstrings are also comments:
"""This is a
multiline docstring."""
print("Hello, World!")
Python Variables
VI
Creating Variables :
Unlike other programming languages, Python has no command for declaring
a variable.
A variable is created the moment you first assign a value to it.

Example:
x=5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type and can even
change type after they have been set.
Python Variables - Example

VI x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Variable Names

VI A variable can have a short name (like x and y) or a more


descriptive name (age, carname, total_volume).

Rules for Python variables:


A variable name must start with a letter or the underscore
character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are
three different variables)

Note : Remember that variables are case-sensitive


Output Variables

VI The Python print statement is often used to output


variables.
To combine both text and a variable, Python uses
the + character:
Example :
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to
another variable:
Example :
x = "Python is "
y = "awesome"
z= x+y
print(z)
Output Variables

VI For numbers, the + character works as a mathematical


operator:
Example :
x=5
y = 10
print(x + y)

Note : If you try to combine a string and a number, Python


will give you an error:
Example:
x=5
y = "John"
print(x + y)
Basic data types in python

VI Every value in Python has a data type. Since everything is


an object in Python programming, data types are actually
classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the
important types are listed below.
1. Integer
2. Floating point number
3. Complex number
4. String
5. Boolean – True – Non zero
false - Zero
Note: We can use the type() function to know which class a
variable or a value belongs to
Python Numbers

VI Python Numbers : There are three numeric types in Python:


1.int
2. float
3.Complex

Variables of numeric types are created when you assign a value to them:
Example :
x = 1 # int
y = 2.8 # float
z = 1j # complex

To verify the type of any object in Python, use the type() function:
Example :
print(type(x))
print(type(y))
print(type(z))
Int

VI Int, or integer, is a whole number, positive or negative, without


decimals, of unlimited length.
Example :
Integers:
x=1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))
Float

VI Float, or "floating point number" is a number, positive or


negative, containing one or more decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float

VI Note:
Float can also be scientific numbers with an "e" to indicate
the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex

VI Complex numbers are written with a "j" as the imaginary part:

Example:
Complex:
x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))
Python Operators

VI 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.
Operators are used to perform operations on variables and
values.

Python divides the operators in the following groups:


Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
+ Addition
Python Arithmetic Operators
Adds values on either side of the operator. a + b = 30

VI
- Subtraction Subtracts right hand operand from left hand a – b = -10
 Arithmetic operators are used with numeric values to
operand.
perform common mathematical operations:
* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand b%a=0


and returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to
operators the power 20

// Floor Division - The division of operands where 9//2 = 4 and


the result is the quotient in which the digits after 9.0//2.0 =
the decimal point are removed. But if one of the 4.0, -11//3
operands is negative, the result is floored, i.e., = -4, -
rounded away from zero (towards negative 11.0//3 = -
infinity) − 4.0
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform
VI common mathematical operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
Assignment operators are used to assign values to variables:
VI
Operator Example Same As
= x=5 x=5
+= x+=3 x=x+3
-= x-=3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Example - Python Assignment Operators
1. x=5
VI x+=3
print(x) { 8}
Operator Example Same As
2. x = 5
x-=3 = x=5 x=5
print(x) {2} += x+=3 x=x+3
3. x = 5
-= x-=3 x=x-3
x% =3
print(x) {2} *= x *= 3 x=x*3
/= x /= 3 x=x/3
4. x = 5
%= x %= 3 x=x%3
x//=3
print(x) {1} //= x //= 3 x = x // 3
5. x = 5 **= x **= 3 x = x ** 3
x **= 3
print(x) {125}
Python Comparison Operators
These operators compare the values on either sides of them and decide
VI the relation among them. They are also called Relational operators.

Operator Name Example


== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal x >= y


to
<= Less than or equal to x <= y
Example - Python Comparison Operators
1. x = 5
VI y=3
print(x == y) Operator Example Same As
# returns False because 5 is not equal to 3
= x=5 x=5
2. x = 5
y=3 += x+=3 x=x+3
print(x != y) -= x-=3 x=x-3
# returns True because 5 is not equal to 3
*= x *= 3 x=x*3
3. x = 5
y=3 /= x /= 3 x=x/3
print(x > y) %= x %= 3 x=x%3
# returns True because 5 is greater than 3
4. x = 5 //= x //= 3 x = x // 3
y=3 **= x **= 3 x = x ** 3
print(x < y)
# returns False because 5 is not less than 3
5. x = 5
y=3
print(x > = y)
# returns True because five is greater, or equal, to 3
Python Logical Operators
Logical operators are used to combine conditional statements:
VI
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of x < 5 or x < 4
the statements is true
not Reverse the result, not(x < 5 and x <
returns False if the 10)
result is true

Example of AND Example of OR


x=5 x=5
print(x > 3 and x < 10) print(x > 3 or x < 4)
# returns True because 5 is greater # returns True because one of the
than 3 AND 5 is less than 10 conditions are true (5 is greater than
3, but 5 is not less than 4)
Example of NOT
x=5
print(not(x > 3 and x < 10))
# returns False because not is
used to reverse the result
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
VI
Operator Description Example Meaning
in Returns True if a sequence with x in y True if the
the specified value is present in operands are
the object identical ( refer to
the same object)
not in Returns True if a sequence with x not in y True if the
the specified value is not operands are not
present in the object identical
( do not refer to
the same object)

Example of not in operator


Example of in operator : x = ["apple", "banana"]
x = ["apple", "banana"]
print("banana" in x) print("pineapple" not in x)
# returns True because a sequence
with the value "banana" is in the # returns True because a
list sequence with the value
"pineapple" is not in the list
Conclusion
Logical operator are same for c and python.
VI For example : x = 5 > 2 means condition true that means x = 2
&& : logical and
∣∣ : logical or
! : not ( false becomes true and true becomes false)

Bitwise operator:

Operator meaning
& Bitwise AND
∣ Bitwise OR
~ Bitwise NOT
^ Bitwise XOR
>> Bitwise right shift
<< Bitwise left shift
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
VI Sr.No. Operator & Description

1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
8 <= < > >=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Control flow statement
Decision making :
VI 1. if statement
2. if … else
3. if … else if …else
4. Nested if statement

1. if statement: This statements control the flow of execution. It is basically used


for testing condition.
The general form of if statement looks like this:

if ( this condition is true )


execute this statement
An "if statement" is written by using the if keyword.
Example
If statement:
a = 33
b = 200
if b > a: ( colon : represents indentation )
print("b is greater than a")
Indentation
python relies on indentation, using whitespace, to define scope in
VI the code. Other programming languages often use curly-brackets
for this purpose.

Example :
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
if…else
VI if else conditional statement in Python has the following syntax:
if condition: true-block several instructions that are executed if
the condition evaluates to True
else: false-block several instructions that are executed if the
condition evaluates to False

Syntax :
if (condition/test expression):
statement1
statement 2 True block

else:
statement 1
statement 2 false block

statement x
if…else
VI Prog: Given number is positive and Negative

n = int( input (“Enter n value ”))


if ( n > 0) :
print(“Positive”)
else:
print(“Negative)
Nested if
VI
when a programmer writes one if statement inside another if statement then
it is called as Nested if statement

There may be a situation when you want to check for another condition
after a condition resolves to true. In such a situation, you can use the nested if
construct.

In a nested if construct, you can have an if...elif...else construct


inside another if...elif...else construct.
Nested if
VI Syntax:
if ( condition1/test expression):
if (condition2/test expression): True
statement1 inner Block
statement n true
else:
statement2 inner
statement n false
else:
statement 3
statement n

Note: In above syntax , if condition1 and condition 2 are correct then


statement 1 will execute . If the condition1 is correct and condition 2 is
incorrect then statement 2 will execute . If the both condition1 and
condition 2 are incorrect then statement 3 is execute.
Example - Nested if
VI Write a programme to read three numbers from a user and check if the
first number is greater or less than the other two numbers

num1= int(input(“Enter the number:”))


num2= int(input(“Enter the number:”))
num3= int(input(“Enter the number:”))
if (num1 > num2):
if ( num2 > num3):
print(num1,”is greater than”, num2,”and”, num3)
else:
print(num1,”is less than”, num2,”and”,num3)
Print(“End of Nested if “)

Output:
Enter the number:12
Enter the number: 34
Enter the number: 56
12 is less than 34 and 56
End of Nested if
Example : Nested if
VI Prog: find largest among 3 number

a = int( input (“Enter value of a”))


b = int( input (“Enter value of b”))
c = int( input (“Enter value of c”))
if ( a > b) :
if ( a > c) # if this condition fails then it executes
print(“a is large”) else part ( c is large )
else:
print(“c is large”)
elif ( b > c) : # if ( a > b) fails then control will enter
print(“ b is large”) at elif . To check one more condition
else: use elif (elseif)
print( “ c is large”)
The elif Statement

VI The elif statement allows you to check multiple expressions for TRUE
and execute a block of code as soon as one of the conditions evaluates
to TRUE.
Similar to the else, the elif statement is optional. However,
unlike else, for which there can be at most one statement, there can be
an arbitrary number of elif statements following an if.

Syntax: In this kind of statements, the


if expression1: expression are checked from
statement(s) top to bottom. When true
elif expression2: condition is found, the associate
statement(s) statement are executed and rest
elif expression3: statement are skipped. If none of
statement(s) condition are found true then
else: else statements are executed.
statement(s) if all other condition are false
and if the final else statement
is not present then no action
takes place.
Example - elif Statements
var = 100
VI If var == 200:
print ("1 - Got a true expression value")
print (var)
elif var == 150:
print ("2 - Got a true expression value")
print (var)
elif var == 100:
print ("3 - Got a true expression value")
print (var)
else:
print ("4 - Got a false expression value")
print (var)

print ("Good bye!")

Output
3 - Got a true expression value
100
Good bye!
if...elif...else construct

VI var = 100
if var < 200:
print ("Expression value is less than 200")
if var == 150:
print ("Which is 150")
elif var == 100:
print ("Which is 100")
elif var == 50:
print ("Which is 50")
elif var < 50:
print ("Expression value is less than 50")
else:
print ("Could not find true expression")
print ("Good bye!")

output
Expression value is less than 200
Which is 100
Good bye!
Nested condition

VI x = int(input( ))
y = int(input( ))
if x > 0:
if y > 0:
# x is greater than 0, y is greater than 0
print("Quadrant I")
else:
# x is greater than 0, y is less or equal than 0
print("Quadrant IV")
else:
if y > 0:
# x is less or equal than 0, y is greater than 0
print("Quadrant II")
else:
# x is less or equal than 0, y is less or equal than 0
print("Quadrant III")

Input Output
2 Quadrant IV
-3
if-elif-else

VI For the given integer X print 1 if it's positive, -1 if it's negative, or 0 if it's equal to
zero.
Try to use the cascade if-elif-else for it.

x = int(input( ))
if x > 0:
print(1)
elif x == 0:
print(0)
else:
print(-1)
Examples

VI Write a python program where a student can get a grade based on marks that he has
scored in any subject. Suppose that marks 90 and above are A’s, marks in the
80s are B’s, 70s are C’s, 60s are D’s, and anything below 60 is an F.

Use ‘if’ statement.

Code:
grade = int (input('Enter your score: '))
if grade>=90:
print('A')
if grade>=80 and grade<90:
print('B')
if grade>=70 and grade<80:
print('C')
if grade>=60 and grade<70:
print('D')
if grade<60:
print('F')
Examples

VI Write a program that asks the user to enter a length in centimeters. If the user enters
a negative length, the program should tell the user that the entry is invalid.
Otherwise, the program should convert the length to inches and print out the result.
There are 2.54 centimeters in an inch.

Use ‘if-else’ statement.

Code:
len = float(input('Enter length in centimeters: '))
if(len<0):
print("The entry is invalid")
else:
inch=len/2.54
print("Equivalent length in inches is:", inch)
Examples

VI Write a program that asks the user for two numbers and prints ‘Numbers are Close’
if the numbers are within 0.001 of each other and ‘Numbers are not close’
otherwise.

Code:
n1 = float(input('Enter number 1: '))
n2 = float(input('Enter number 2: '))
if(n2-n1<=0.001):
print("Numbers are close")
else:
print("Numbers are not close")
Examples

VI Given three integers, determine how many of them are equal to each other. The
program must print one of these numbers: 3 (if all are the same), 2 (if two of them
are equal to each other and the third is different) or 0 (if all numbers are different)

Code:
a = int(input())
b = int(input())
c = int(input())
if a == b == c:
print(3)
elif a == b or b == c or a == c:
print(2)
else:
print(0)
VI
While - loop

VI A while loop statement in Python programming language repeatedly


executes a target statement as long as a given condition is true.
Syntax:
The syntax of a while loop
while expression:
statement(s)
Example – while loop
count = 0
VI while (count < 9):
print( 'The count is:', count)
count = count + 1
print "Good bye!"

When the above code is executed, it produces the following result −


The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Example - While - loop
end=12
VI n=1
while(n<=end):
print(n)
Result : It will print 1 to infinite

end=12
n=1
while(n<=end):
print(n)
n = n+1
Result : It will print 1 to 12
While - loop
Write a program to find the sum of the digits of a given number
VI
num=int(input("please enter the number"))
x=num
sum=0
rem=0
while(num>0): #while loop is used &last digit of number is obtained by
rem=num%10 using modulus operator ,so it gives remainder
num=num//10 # (123/10) it will gives only 12 number (gives only integer)
sum=sum+rem # rem is added to variable sum each time the loop exexutes
print("sum of the digits of an entered number",x,"is=",sum)

Output:
please enter the number123
sum of the digits of an entered number 123 is= 6

Note: The integer number is read from the user. And it is stored in variable num
. Initially the value of sum and rem are initialized to 0. Unless and until the value of
num>0 the statement within the loop continue to be executed. The modulus operator
And division operator are used frequently to obtain the sum of the numbers enterd.
While - loop
Write a program to print factorial of a number using while loop
VI
num=int(input("please enter the number:"))
fact=1
ans=1
while(fact<=num):
ans=ans*fact
fact=fact+1
print("factorial of ",num," is: ",ans)

Output:
please enter the number:6
factorial of 6 is: 720
else: While - loop

VI Python supports to have an else statement associated with a loop statement.


If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.

count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")

Result:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
While – loop - continue

VI It returns the control to the beginning of the while loop.


The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
Syntax:
Continue

Flow Diagram :
Example: While – loop - continue

VI var = 10
while var > 0: false
Condi
var = var -1 tion?
if var == 5: Exit loop
continue True
print ('Current variable value :', var)
print ("Good bye!")

Result: Yes Conti


Current variable value : 9 nue?
Current variable value : 8
Current variable value : 7 No
Current variable value : 6
Current variable value : 4 Body of loop
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
While – loop - continue
x=0 Note: Skip all statements below the continue statement
VI while x < 5 :
if(x==2):
continue
x = x+1
print("\nx =",x)
print("This is statement 1 inside while loop ")
print("This is statement 2 inside while loop ")
print("This is statement 3 inside while loop ")
print("This is statement 4 inside while loop ")
else :
print("\nThis is statement in else part of while ")

print("\nThis is statement outside while loop ")


Result :
x=1 x=2
This is statement 1 inside while loop This is statement 1 inside while loop
This is statement 2 inside while loop This is statement 2 inside while loop
This is statement 3 inside while loop This is statement 3 inside while loop
This is statement 4 inside while loop This is statement 4 inside while loop
Python break statement

VI It terminates the current loop and resumes execution at the next statement,
just like the traditional break statement in C.
The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.
Syntax:
The syntax for a break statement in Python is as follows −
break
Flow Diagram:
Example: While – loop - break

VI var = 10 # first Example Test false


while var > 0: conditi
print ('Current variable value :', var) on
var = var -1
if var == 5: True
break
print ("Good bye!") Bre True
ak?
Output: false
Current variable value : 10
Current variable value : 9 Exit loop
Current variable value : 8 Body of
Current variable value : 7 loop
Current variable value : 6
Good bye!
Example: While – loop - break
x=0
VI while x < 5 :
if(x==2):
break
x = x+1
print("\nx =",x)
print("This is statement 1 inside while loop ")
print("This is statement 2 inside while loop ")
print("This is statement 3 inside while loop ")
print("This is statement 4 inside while loop ")
else :
print("\nThis is statement in else part of while ")

print("\nThis is statement outside while loop ")


Result :
x=1 x=2
This is statement 1 inside while loop This is statement 1 inside while loop
This is statement 2 inside while loop This is statement 2 inside while loop
This is statement 3 inside while loop This is statement 3 inside while loop
This is statement 4 inside while loop This is statement 4 inside while loop

This is statement outside while loop


The range( ) function
There is inbuilt function in python called range( ) , which is used to generates a list
VI of integers. The range has one, two or three parameters. The last two parameters are
optional.

The general form of range( ) function is


range( start , end , step )
Default value of start is zero
Default value of step is one
• The ‘start’ is first beginning number in the sequence at which list starts
•The ‘end’ is the limit , ie last number in the sequence
•The ‘step’ is the difference between each number in the sequence.

Example:
range ( 0,n,1)
Where n is end or stop element , then last element should be n-1
i.e 0
1
2
n-1
The range( ) function

VI In python variable i will take the value from 1 to n-1 .


e.g : for i in range(10):
print(i)
There are 3 way to write range function
1. range(end)
2. Range(start , end)
3. Range(start , end , step)

Note: If you don’t give start , default value is zero


If you don’t give step , default value is one
Python for Loop Statements

VI
A statement that is executed sequentially and allow us to to
execute group of statements multiple times.
It has the ability to iterate over the items of any sequence, such
as a list or a string.
Syntax:
for variable in sequence:
statements(s)

Val – is variable which takes the value of item inside sequence of


n iteration
Note : If a sequence contains an expression list, it is evaluated
first. Then, the first item in the sequence is assigned to the
iterating variable iterating_var. Next, the statements block is
executed. Each item in the list is assigned to iterating_var, and
the statement(s) block is executed until the entire sequence is
Flow diagram of for statement
Flow Diagram:
VI
Example using for loop

VI 1.for character in 'hello':


print(character)

Output:
h
e
l
l
o
2. for i in range(10): # 0 to 9
print(“Hello world”)

Output:
hello world ( 10 times printed)
Example using for loop

VI L = [ “ sachin” , Rahul”, “ Saurabh” ]


for i in L :
print(i)

Output:
Sachin
Rahul
Saurabh
Example using for loop

VI # Table of 5 using for loop


Code:
for i in range(5,55,5): OR for i in range(5,51,5):
print(i) print(i)

Output:
5
10
15
20
25
30
35
40
45
50
Note : if last element is 51 to 55 then it print up to 50. if last element is less
than 51 then it print up to 45. if last element is greater than 55 then it print up
to 55.
Example using for loop

VI # print even number between 20 to 40 using for loop


Code:
for i in range(20,40,2):
print(i)
Output:
20
22
24
26
28
30
32
34
36
38
Example using for loop

VI Code:
for i in range(2):
print(i)
i=i+50
print(i)
Output:
0
50
1
51
Example using for loop

VI Code:
for i in range(10):
print(i)
i=i+50
print(i)
Output:
0
50
1
51
2
52
3
53



9
59
Example using for loop

VI # print pattern ****** using for loop


Code:
for i in range(10):
print('*****')
Output:
*****
*****
*****
*****
*****
*****
*****
*****
*****
*****
Example using for loop

VI Code:
for j in range(10):
for i in range(j+1):
print("*",end="")
print()
Output:
*
*
*
*
*
*
*
*
*
*
Example using for loop

VI # print pyramid like pattern using for loop


Code:
for i in range(11):
print( '*‘ *i )
Output:
*
**
***
****
*****
******
*******
********
*********
**********
Example using for loop

VI # print pyramid like pattern using for loop


Code:
for i in range(10):
print('*'*(10-i))
Output:
**********
*********
********
*******
******
*****
****
***
**
*
for loop – integer variable

VI Another use case for a for-loop is to iterate some integer variable in


increasing or decreasing order. Such a sequence of integer can be
created using the function
range(min_value, max_value):

Program:
for i in range(5,8):
print(i, i ** 2)
print(‘end of loop’)
Output:
5 25
6 36
7 49
end of loop

Note: Function range(min_value, max_value) generates a sequence with


numbers min_value, min_value + 1, ..., max_value - 1. The last number is
not included
for loop with range
There's a reduced form of range( ) - range(max_value), in which case
VI min_value is implicitly set to zero:
e.g.
for i in range(3):
print(i)
Output :
0
1
2
Range( ) can define an empty sequence, like range(-5) or range(7, 3). In this
case the for-block won't be executed:
To iterate over a decreasing sequence, we can use an extended form of range( )
with three arguments - range(start_value, end_value, step). When omitted,
the step is implicitly equal to 1. However, can be any non-zero value. The loop
always includes start_value and excludes end_value during iteration:
e.g. Output
for i in range(10, 0, -2): 10
print(i) 8
6
4
2
How to merge multiple print?

VI print(1, 2, 3)
print(4, 5, 6)

Output:
123
456

print(1, 2, 3,end=',')
print(4, 5, 6)

Output
1 2 3,4 5 6
Example using for loop

VI # print capital letters from A to Z using for loop


Code:
print(‘ The capital letters from A to Z is: ‘)
for i in range(65,91,1):
print(chr(i), end=‘ ‘)
Output:
The capital letters from A to Z is: A,B,C,……………Z

# To print numbers from 1 to 10 in reverse order


Code:
print(“ Numbers from 1 to 10 in Reverse order is: ”)
for i in range(10,0,-1):
print(i, end = ‘ ‘)
Output:
Numbers from 1 to 10 in Reverse order is:
10 9 8 7 ……1
for loop with range

VI By default, the function print( ) prints all its arguments separating them by a
space and the puts a newline symbol after it. This behavior can be changed
using keyword arguments sep (separator) and end.
e.g.
print(1, 2, 3) Output
print(4, 5, 6) 123
print(1, 2, 3, sep=', ', end='. ') 456
print(4, 5, 6, sep=', ', end='. ') 1, 2, 3. 4, 5, 6.
print( ) 123 -- 4 * 5 * 6.
print(1, 2, 3, sep=‘ ’, end=' -- ')
print(4, 5, 6, sep=' * ', end='.')
for loop with break

VI Problem: WAP using break statement to print first three letters in “string”

for val in "string":


if val=="i":
break
print(val)

Output:
s
t
r
for loop with continue

VI Problem: WAP using continue statement to print a “string”

for val in "string":


if val=="i":
continue
print(val)

Output:
s
t
r
n
g
for loop with continue

VI Problem: WAP using continue statement

for i in range (1,10):


if i== 5:
continue
print(i)
print(”loop terminate”)

Output:
1
2
3
4
6
7
8
9
Python - Numbers

VI Number data types store numeric values.


Python supports four different numerical types −
1.int (signed integers) − They are often called just integers or ints, are positive or
negative whole numbers with no decimal point.
2.long (long integers ) − Also called longs, they are integers of unlimited size, written
like integers and followed by an uppercase or lowercase L.
3.float (floating point real values) − Also called floats, they represent real numbers
and are written with a decimal point dividing the integer and fractional parts. Floats
may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x
102 = 250).
4.complex (complex numbers) − are of the form a + bJ, where a and b are floats and J
(or j) represents the square root of -1 (which is an imaginary number). The real part of
the number is a, and the imaginary part is b. Complex numbers are not used much in
Python programming.
Mathematical Functions

Function Returns ( Description )


VI
abs(x) The absolute value of x: the (positive) distance between x and zero.

ceil(x) The ceiling of x: the smallest integer not less than x.


cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3. Instead
use return (x>y)-(x<y).
exp(x) The exponential of x: ex
fabs(x) The absolute value of x.
floor(x) The floor of x: the largest integer not greater than x.
log(x) The natural logarithm of x, for x > 0.
log10(x) The base-10 logarithm of x for x > 0.
max(x1, The largest of its arguments: the value closest to positive infinity
x2,...)
min(x1, The smallest of its arguments: the value closest to negative infinity.
x2,...)
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts have
the same sign as x. The integer part is returned as a float
Mathematical Functions

Function Returns ( Description )


VI
pow(x, y) The value of x**y.

round(x x rounded to n digits from the decimal point. Python rounds away
[,n]) from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -
1.0.
sqrt(x) The square root of x for x > 0.
Mathematical Functions/ math module

VI
1.Python Number abs() : The method abs() returns absolute value of x - the
(positive) distance between x and zero.
Syntax:
Following is the syntax for abs() method −
abs( x )
Parameters
x − This is a numeric expression.
Return Value
This method returns absolute value of x.
Example:
print ("abs(-45) : ", abs(-45))
print ("abs(100.12) : ", abs(100.12))
print ("abs(119) : ", abs(119))
Output:
abs(-45) : 45
abs(100.12) : 100.12
abs(119) : 119
Mathematical Functions

Description
VI The fabs( ) method returns the absolute value of x. Although similar to the abs()
function, there are differences between the two functions.
They are −
•abs( ) is a built in function whereas fabs( ) is defined in math module.
•fabs( ) function works only on float and integer whereas abs( ) works with complex
number also.

import math # This will import math module

print ("math.fabs(-45.17) : ", math.fabs(-45.17))


print ("math.fabs(100.12) : ", math.fabs(100.12))
print ("math.fabs(100.72) : ", math.fabs(100.72))
print ("math.fabs(math.pi) : ", math.fabs(math.pi))

Output
math.fabs(-45.17) : 45.17
math.fabs(100.12) : 100.12
math.fabs(100.72) : 100.72
math.fabs(math.pi) : 3.141592653589793
Mathematical Functions
ceil() function :
VI Description
The method ceil() returns ceiling value of x - the smallest integer not
less than x.
Python has many auxiliary functions for calculations with floats.
They can be found in the math module. To use this module, we need to import it first
by writing the following instruction at the beginning of the program:
import math
Syntax
Following is the syntax for ceil() method −
import math
math.ceil( x )
Example:
import math
print("math.ceil(-45.17) : ", math.ceil(-45.17))
print("math.ceil(100.12) : ", math.ceil(100.12))
print("math.ceil(100.72) : ", math.ceil(100.72))
Output:
math.ceil(-45.17) : -45
math.ceil(100.12) : 101
math.ceil(100.72) : 101
exp()
Description:
VI The method exp() returns exponential of x: ex.
Syntax
Following is the syntax for exp() method −
import math
math.exp( x )
Example :
print("math.exp(2) : ", math.exp(2))
print ("math.exp(100.12) : ", math.exp(100.12))
Output:
math.exp(2) : 7.38905609893065
math.exp(100.12) : 3.0308436140742566e+43
floor()
Description
VI The method floor() returns floor of x - the largest integer not greater
than x.
Syntax
Following is the syntax for floor() method −
import math
math.floor( x )

Example:
import math
print ("math.floor(-45.17) : ", math.floor(-45.17))
print ("math.floor(100.12) : ", math.floor(100.12))

Output:
math.floor(-45.17) : -46
math.floor(100.12) : 100
log()
Description:
VI The method log( ) returns natural logarithm of x, for x > 0.
Syntax:
Following is the syntax for log() method −
import math
math.log( x )

Example:
import math
print ("math.log(1) : ", math.log(1))
print ("math.log(100.12) : ", math.log(100.12))

Output:
math.log(1) : 0.0
math.log(100.12) : 4.6063694665635735
sqrt()

VI Description:
The method sqrt() returns the square root of x for x > 0.
Syntax:
Following is the syntax for sqrt() method −
import math
math.sqrt( x )

Example:
import math
print ("math.sqrt(100) : ", math.sqrt(100))
print ("math.sqrt(7) : ", math.sqrt(7))

Output:
math.sqrt(100) : 10.0
math.sqrt(7) : 2.6457513110645907
pow()

VI This method returns value of xy.

Syntax:
math.pow(x,y)

Example:
import math
print ("math.pow(5, 2) : ", math.pow(5, 2))
print ("math.pow(100, 2) : ", math.pow(100, 2))

Output:
math.pow(5, 2) : 25.0
math.pow(100, 2) : 10000.0
Mathematical Functions

Output
VI print ("round(70.23456) : ", round(70.23456)) round(70.23456) : 70
print ("round(56.659,1) : ", round(56.659,1)) round(56.659,1) : 56.7
print ("round(80.264, 2) : ", round(80.264, 2)) round(80.264, 2) : 80.26
print ("round(100.000056, 3) : ", round(100.000056, 3)) round(100.000056, 3) : 100.0
print ("round(-100.000056, 3) : ", round(-100.000056, 3)) round(-100.000056, 3) : -100.0
Description

The sqrt( ) method returns the square root of x for x > 0.


Syntax
import math Output
math.sqrt( x ) math.sqrt(100) : 10.0
print ("math.sqrt(100) : ", math.sqrt(100)) math.sqrt(7) : 2.6457513110645907
print ("math.sqrt(7) : ", math.sqrt(7)) math.sqrt(math.pi) : 1.772453850905515
print ("math.sqrt(math.pi) : ", math.sqrt(math.pi))
Description
The randrange( ) method returns a randomly selected element from range(start, stop,
step).
Syntax
randrange ([start,] stop [,step])
Mathematical Functions – max( )
Description
VI The max( ) method returns the largest of its arguments i.e. the value closest to
positive infinity.
Syntax

max( x, y, z, .... ) # x,y,z are numeric expression

Output
print ("max(80, 100, 1000) : ", max(80, 100, 1000))
max(80, 100, 1000) : 1000
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
max(-20, 100, 400) : 400
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
max(-80, -20, -10) : -10
print ("max(0, 100, -400) : ", max(0, 100, -400))
max(0, 100, -400) : 100

Description
The method min( ) returns the smallest of its arguments i.e. the value closest to
negative infinity.
Random number function

VI import random # randomly select an odd number between 1-100

print ("randrange(1,100, 2) : ", random.randrange(1, 100, 2))


# randomly select a number between 0-99
print ("randrange(100) : ", random.randrange(100))

Output
randrange(1,100, 2) : 83
randrange(100) : 93

The seed( ) method initializes the basic random number generator. Call this function
before calling any other random module function.
Syntax
seed ([x], [y]) import random

random.seed()
print ("random number with default seed", random.random())
random.seed(10)
print ("random number with int seed",random.random())
random.seed("hello",2)
print ("random number with string seed", random.random())
Random number function

VI Description
The shuffle( ) method randomizes the items of a list in place.
Syntax
shuffle (lst,[random])

import random list = [20, 16, 10, 5];


random.shuffle(list) print ("Reshuffled list : ", list)
random.shuffle(list) print ("Reshuffled list : ", list)

Description
The uniform( ) method returns a random float r, such that x is less than or equal to r and
r is less than y.
Syntax
uniform(x, y)
Trigonometric Functions -sin()

Description
VI The method sin() returns the sine of x, in radians.
Syntax
Following is the syntax for sin() method −
math.sin(x)

Example:
import math
print ("sin(3) : ", math.sin(3))
print ("sin(-3) : ", math.sin(-3))
print ("sin(0) : ", math.sin(0))

Output:
sin(3) : 0.1411200080598672
sin(-3) : -0.1411200080598672
sin(0) : 0.0
cos()

VI Description:
The method cos( ) returns the cosine of x radians.
Syntax:
Following is the syntax for cos() method −
cos(x)

Example:
print ("cos(3) : ", math.cos(3))
print ("cos(-3) : ", math.cos(-3))
print ("cos(0) : ", math.cos(0))

Output:
cos(3) : -0.9899924966004454
cos(-3) : -0.9899924966004454
cos(0) : 1.0
tan()

VI Description:
The method tan() returns the tangent of x radians.
Syntax:
Following is the syntax for tan() method −
tan(x)

Example:
import math
print ("tan(3) : ", math.tan(3))
print ("tan(-3) : ", math.tan(-3))
print ("tan(0) : ", math.tan(0))

Output:
tan(3) : -0.1425465430742778
tan(-3) : 0.1425465430742778
tan(0) : 0.0
degrees() Method

VI Description
The method degrees() converts angle x from radians to degrees.
Syntax
Following is the syntax for degrees() method −
degrees(x)
Note: This method returns degree value of an angle.
Example:
print ("degrees(3) : ", math.degrees(3))
print ("degrees(-3) : ", math.degrees(-3))
print ("degrees(0) : ", math.degrees(0))
print ("degrees(math.pi) : ", math.degrees(math.pi))
print ("degrees(math.pi/2) : ", math.degrees(math.pi/2))
Output:
degrees(3) : 171.88733853924697
degrees(-3) : -171.88733853924697
degrees(0) : 0.0
degrees(math.pi) : 180.0
degrees(math.pi/2) : 90.0
radians() Method

VI Description
The method radians() converts angle x from degrees to radians.
Syntax
Following is the syntax for radians() method −
radians(x)
Note: This method returns radian value of an angle.
Example:
import math
print ("radians(3) : ", math.radians(3))
print ("radians(math.pi) : ", math.radians(math.pi))

Output:
radians(3) : 0.05235987755982989
radians(math.pi) : 0.05483113556160755
Random Number Functions

VI Random numbers are used for games, simulations, testing, security, and
privacy applications. Python includes following functions that are commonly
used.
Function Description
1.choice(seq) A random item from a list, tuple, or string.
2.randrange ([start,] stop [,step]) A randomly selected element from
range(start, stop, step)
3.random()A random float r, such that 0 is less than or equal to r and r is less
than 1
4.seed([x])Sets the integer starting value used in generating random numbers.
Call this function before calling any other random module function. Returns
None.
5.shuffle(lst)Randomizes the items of a list in place. Returns None.
6.uniform(x, y)A random float r, such that x is less than or equal to r and r is
less than y
Python Strings

VI String : Any program is composed of sequence of characters.


When a sequence of characters are grouped together , a string is
created.
 String in python are surrounded by either single quotation
marks, or double quotation marks.
'hello' is the same as "hello".
 Strings can be output to screen using the print function.

For example: print("hello").


 In many programming language , strings are treated as arrays of
characters but in python a string is an object of the str class.
 Like many other popular programming languages, strings in
Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single
character is simply a string with a length of 1. Square brackets
can be used to access elements of the string.
Python Strings- object

VI We can create a string using the str class as:


s1 = str( ) # create an empty string object
s2 = str(“Hello”) # create an string object for Hello

OR
An alternative way to create a string object is by assigning a string value to a
variable.
Example:
s1 = “ “ # create an empty string
s2 = “Hello” # Equivalent to s2 = str(“Hello”)
How to access character in a string?

VI Index[ ] operator:
As string is a sequence of characters . The characters in a string can be
accessed one at a time through the index operator.
The first character of the string is stored at the 0 th position and last character of
the string is stored at a position one less than that of the length of the string.

For the string Sammy Shark! the index breakdown looks like this:

As you can see, the first S starts at index 0, and the string ends at index
11 with the ! symbol. We also notice that the whitespace character
between Sammy and Shark also corresponds with its own index number.
In this case, the index number associated with the whitespace is 5.
The exclamation point (!) also has an index number associated with it.
Any other symbol or punctuation mark, such as *#$&.;?, is also a character
and would be associated with its own index number.
Example

VI Example:
>>> s1="python"
>>>s1[0] # Access the first element of the string
>>>s1[5] # Access the last element of the string
Accessing characters via Negative index

VI If we have a long string and we want to pinpoint an item towards the end, we
can also count backwards from the end of the string, starting at the index
number -1.
Example- Initialization

VI Directly write string name String = “hello”


Here index is always start from 0 to n-1 , where n is length of string .

Syntax:
String[index]
where index = index of any mathematical expression

Example:
string = “hello”
string[0] = h
string[1] = e
string[2] = l
string[3] = l
string[4] = o
Traversing string with for & while loop

VI A programmer can use the for loop to traverse all characters in a string.

Code:
Write a program to traverse all elements of a string using for loop
Example:
s =“ India”
for ch in s:
print(ch , end = “ ”)

Output:
India

Explanation: The string ‘India’ is assigned to variable s. The for loop is used to
print all the character of a string s. The statement ‘for ch in s:’ can read as ‘for
each character ch in s print ch’
Traversing string with for & while loop

VI A programmer can use the for loop to traverse all characters in a string.

Code:
Write a program to traverse every second character of a string using for loop
Example:
s =“ ILOVEPYTHONPROGRAMMING”
for ch in range(0,len(s),2): # Traverse each second character
print(s[ch] , end = “ ”)

Output:
I 0 E YH N R GAM N

Example:
for ch in range(1,len(s),2):
print(s[ch] , end = " ")
Output:
LVPTOPOR MIG
Traversing string with while loop

VI A programmer can use the while loop to traverse all characters in a string.

Example:
s =“ India”
Index = 0
While index< len(s):
print(s[index] , end = “ ”)
index = index+1

Output:
India
Slices: single character

VI A slice gives from the given string one character or some fragment:
substring or subsequence.
There are three forms of slices. The simplest form of the slice:
a single character slice S[i] gives ith character of the string.
We count characters starting from 0. That is, if
S = 'Hello',
S[0] == 'H', S[1] == 'e', S[2] == 'l',S[3] == 'l', S[4] == 'o'.
Note that in Python there is no separate type for characters of the
string. S[i] also has the type str, just as the source string.
Number i in S[i] is called an index.
If you specify a negative index, then it is counted from the end, starting with
the number -1.
That is, S[-1] == 'o', S[-2] == 'l', S[-3] == 'l', S[-4] == 'e', S[-5] == 'H'.
Let's summarize it in the table:
Strings operators- Accessing substring

VI String contains the slicing operator and the slicing with step size parameter is
used to obtain the subset of string.

String slicing operator[ start :end ]


The slicing operator returns a subset of a string called slice by specifying two
indices , start and end .
Syntax :
Name of variable of a string[ Start index : End index ]

Example :
s=Hello"
print(s[1:4]) # The s[1:4] returns a subset of string starting
from start index 1 to one index less than that
Output : of end parameter of slicing operation (4-1=3)
ell
Note : we can get the same substring using S[-4:-1]
we can mix positive and negative indexes in the same slice, for
example, S[1:-1] is a substring without the first and the last character of the
string
Strings operators- Accessing substring

VI For example :
if s == 'Hello'
the slice S[1:5] returns the string 'ello', and the result is the same even if the
second index is very large, like S[1:100].
Strings slice with step size

VI We learnt , how to select a portion of string. But how does a programmer select
every second character from a string ?
This can be done by using step size. In slicing first two parameters are start
and end. We need to add a third parameter as step size to select the character
from a string with step size.

Syntax:
Name of variable of a string[ Start _ index : End _ index: step_ size ]

Example:
s="IIT-MADRAS"
print(s[0:len(s):2])

Output:
ITMDA
Some more complex example of string slicing
For example : s = “ IIT-MADRAS”
VI 1. s="IIT-MADRAS"
print(s[: :])
output : IIT-MADRAS # print entire string
2. print(s[1:])
output: IT-MADRAS
3. print(s[:3])
output: IIT
4. print(s[:-1]) # start with index 0 and exclude last
output: IIT-MADRA character stored at index-1.
5. print(s[1:-1])
output : IT-MADRA
6. print( s[: : 2] ) or print ( s[ 0: : 2] )
output: ITMDA #alternate characters are printed
7. print(s[::-1]
output : SARDAM-TII # display the string in reverse order
8. print(s[-1:0:-1])
output : SARDAM-TI # Access the character from -1
9. print(s[1::2])
output: I-ARS
String character sequence

VI String character sequence is divided in to two categories


1. Mutable : mutable means changeable
2. Immutable : mutable means unchangeable

Note: strings are immutable sequence of characters.


Let us see what happens if we try to change the contents of the string.
Example :
str1="I Love Python"
str1[0]="U"
print(str1)

Output : TypeError: 'str' object does not support item assignment

Explanation : here we have assigned the string “I Love Python“ to str1. The
index [ ] operator is used to change the contents of the string. Finally it
show an error because the strings are immutable ( can not change the
existing string).
Solution - String character sequence

VI If you want to change the existing string, the best way is to create a new string
that is a variation of original string.

Example:
str1="I LOVE PYTHON"
str2="U"+str1[1:]
print(str2)

Output:
U LOVE PYTHON
How to concatenate and repetition of a string?

VI Two strings can be concatenated by using + operator


Example:
str1=“Hello"
str2=“python”
print(str1+str2)

Output:
Hellopython
Note: print(str1+2 ) – Not allowed , it gives error

we can also repeat a string n times multiplying it by integer


Example:
str1=“Hello“
print(str1*3)

Output: HelloHelloHello
Note : print( str1*str2) - Not allowed , it gives error
String methods/ String function

VI A method is a function that is bound to the object. When the method is


called, the method is applied to the object and does some computations
related to it.
The syntax of methods are invoked as
object t_ name. method _ name(arguments)
1. find Method: It determines if string str occurs in string, or in a
substring of string if starting index beg and ending index end are
given.
Syntax:
string_name.find(arguments)
Note: It returns Index if found and -1 otherwise.
Example : output : 1
s = 'Hello‘ 2
print(s.find('e')) -1
print(s.find('ll'))
print(s.find('L'))
String methods:

VI Similarly, the method rfind() returns the index of the last occurrence of the
substring.
Example:
s = 'abracadabra'
print(s.find('b'))
Output : 1
print(s.rfind('b'))
Output : 8
Split Method

VI  The method split() returns a list of all the words in the string ,
using str as the separator.
 Basically create a list with elements of given string separated by space.

Example:
str="welcome to python"
print(str. split( ))
Output : ['welcome', 'to', 'python']
string function capitalize( ), center( )
Output
VI Syntax
str.capitalize( ) : This is string example....wow!!!
str.capitalize( )

str = "this is string example....wow!!!"


print ("str.capitalize( ) : ", str.capitalize( ))

The method center( ) returns centered in a string of length width.


Syntax.
str.center(width, fillchar)

Parameters
width − This is the total width of the string.
fillchar − This is the filler character.

b="hello"
print(b.center(11,"x"))

Output # hello is at center , left and right hand


xxxhelloxxx side of hello it filled with character x
center( )
VI Example:
b="hello welcome to python programming"
print(b.center(11,"x"))

Output :
hello welcome to python programming

Note: here actual width of a string b is greater than 11. Hence it will print
hello welcome to python programming string.
Function find( )
Description
VI The find( ) method determines if the string str occurs in string, or in a substring of
string if the starting index beg and ending index end are given.
Syntax
str.find(str, beg = 0 end = len(string))
Parameters
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of the string.
e.g.
b="hello welcome to python programming"
print(b.find("o",0,len(b)))

Output: 4
It return the index value of first occurrence of “o”
Function split

VI Description
The split( ) method returns a list of all the words in the string, using str as the separator
(splits on all whitespace if left unspecified), optionally limiting the number of splits to
num.
Syntax
str.split(str=" ", num = string.count(str)).
Parameters
str − This is any delimeter, by default it is space.
num − this is number of lines to be made

e.g.
str = "this is string example....wow!!!"
print (str.split( ))
print (str.split( 'i',1)) Output
['this', 'is', 'string', 'example....wow!!!']
print (str.split('w'))
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
String Formatting Operator

VI One of Python's coolest features is the string format operator %. This operator is
unique to strings and makes up for the pack of having functions from C's printf( )
family.
e.g.
print ("My name is %s and weight is %d kg!" % ('Zara', 21))

Output
My name is Zara and weight is 21 kg!

Most complex format: python3 added a new string method called format( ) method.
Instead of %s we can use {0}, {1} and so on
Syntax: template.format(p0,p1,…..)
e.g.
print ("My name is {0} and weight is {1} kg!“.format ('Zara', 21))
Output
My name is Zara and weight is 21 kg!
Format Symbol & Conversion

VI
%c
 character
%s
 string conversion via str() prior to formatting
%i
 signed decimal integer
%d
 signed decimal integer
%u
 unsigned decimal integer
%o
 octal integer
%x
 hexadecimal integer (lowercase letters)
Format Symbol & Conversion

VI %X
 hexadecimal integer (UPPERcase letters)

%e
 exponential notation (with lowercase 'e')

%E
 exponential notation (with UPPERcase 'E')

%f
 floating point real number

%g
 the shorter of %f and %e

%G
 the shorter of %f and %E
Function Index

VI Description

The index( ) method determines if the string str occurs in string or in a


substring of string, if the starting index beg and ending index end are given.
Syntax

str.index(str, beg = 0 end = len(string))


Parameters
•str − This specifies the string to be searched.
•beg − This is the starting index, by default its 0.
•end − This is the ending index, by default its equal to the length of the string.

e.g. Output
str1 = "this is string example....wow!!!“ 15
str2 = "exam"; 15
print (str1.index(str2)) Traceback (most recent call last):
print (str1.index(str2, 10))
print (str1.index(str2, 40))
Function islower( ),len( )
Description
VI The islower( ) method checks whether all the case-based characters (letters) of the string
are lowercase.
Syntax
str.islower( )

e.g. Output
str = "THIS is string example....wow!!!" False
print (str.islower( )) True
str = "this is string example....wow!!!“
print (str.islower( ))

Description
The len( ) method returns the length of the string.
Syntax
len( str )
Output
e.g. Length of the string: 32
str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))
Function lower( )
Description
VI The method lower() returns a copy of the string in which all case-based characters have
been lowercased.

Syntax
str.lower( )

Return Value
This method returns a copy of the string in which all case-based characters have been
lowercased.

e.g.
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.lower( ))

Output
this is string example....wow!!!
Function replace( )
Description
VI The replace( ) method returns a copy of the string in which the occurrences of old have
been replaced with new, optionally restricting the number of replacements to max.
Syntax
str.replace(old, new, max)
Parameters

•old − This is old substring to be replaced.


•new − This is new substring, which would replace old substring.
•max − If this optional argument max is given, only the first count occurrences are
replaced.

e.g.
str = "this is string example....wow!!! this is really string“
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
Output
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
Function : count()
Description
VI This method counts the number of occurrences of one string within another
string.
Syntax
s.count(substring)
Note : Only non-overlapping occurrences are taken into account

e.g.
print('Abracadabra'.count('a'))
print(('aaaaaaaaaa').count('aa'))

Output
4
5
list

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

 There are certain things you can do with all the sequence types. These operations
include indexing, slicing, adding, multiplying, and checking for membership. In
addition, Python has built-in functions for finding the length of a sequence and for
finding its largest and smallest elements.

 There are certain things you can do with all the sequence types. These operations
include indexing, slicing, adding, multiplying, and checking for membership. In
addition, Python has built-in functions for finding the length of a sequence and for
finding its largest and smallest elements.
list

VI
Python Lists
• The list is the most versatile data type available in Python, which can be written as
a list of comma-separated values (items) between square brackets. Important thing
about a list is that the items in a list need not be of the same type.
• Creating a list is as simple as putting different comma-separated values between
square brackets.
• e.g.

list1 = ['physics', 'chemistry', 1997, 2000]


list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])

Output
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists

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

seq = [ 10,20,30,40 ]
print( seq.append ( 50 )
Output : [ 10,20,30,40,50 ]
2. Reassign the element
list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : ", list[2])
list[2] = 2001
Print ( list )

Output:
Value available at index 2 : 1997
list = ['physics', 'chemistry', 2001, 2000 ]
Delete List Elements
To remove a list element, you can use either the del statement if you know exactly
VI which element(s) you are deleting. You can use the remove() method if you do not
know exactly which items to delete.
list = ['physics', 'chemistry', 1997, 2000]
print (list)
del list[2]
print ("After deleting value at index 2 : ", list)

Output
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000]

Basic List Operations

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
List Slicing
The slicing operator returns a subset of a list called slice by specifying two arguments
VI start, end .
Syntax :
Name of list[start index : End index]

Example:
L1 = [ 10,20,30,40,50]
L1[ 1:4]

Output :
[20,30,40 ]
List Slicing with step size
We learnt how to select a portion of a list. In this , we will explore how to select every
VI second or third element of a list using step size. Hence we need to add a third
parameter a step size .
Syntax :
Name of list[start index : End index: step size]

Example:
mylist=["Hello",1,"Monkey",2,"Dog",3,"Donkey" ]
newlist=mylist[0:6:2] or newlist=mylist[0: len(mylist) :2]
print(newlist)

Output :
['Hello', 'Monkey', 'Dog']

Example:
mylist=["python",450,"c",300,"c++",670 ]
newlist=mylist[0:6:3]
print(newlist)
Output :
['python', 300]
Python inbuilt functions for Lists
len( ) Method :
VI Description
The method len() returns the number of elements in the list.
Syntax:
len(list)
Example
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)

Output:
first list length : 3
Second list length : 2
Python inbuilt functions for Lists
max( ) Method
VI Description
The method max returns the elements from the list with maximum value.
Syntax
max(list)
Example:
list1, list2 = [‘123’, 'xyz', 'zara', 'abc'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))

Output:
Max value element : zara
Max value element : 700
Example:
list=['a','ab']
print(max(list))
Output:
ab
Example:
list=['a','100']
print(max(list))
Output: a
Python inbuilt functions for Lists
min() Method
VI Description
The method min returns the elements from the list with minimum value.
Syntax
min(list)
Example:
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print "Min value element : ", min(list1)
print "Min value element : ", min(list2)

Output:
Min value element : 123
Min value element : 200
Python inbuilt functions for Lists
append() Method
VI Description
The method append() appends a passed obj into the existing list.
Syntax
list. append(obj)

Example:
list = [123, 'xyz', 'zara', 'abc']
list. append( 2009 )
print("Updated List : ", list)

Output:
Updated List : [123, 'xyz', 'zara', 'abc', 2009]
Python inbuilt functions for Lists
extend() Method
VI Description
The method extend() appends a passed obj into the existing list.
Syntax
list. extend(seq)

Example:
List1 = [123, 'xyz', 'zara', 'abc', 123]
List2 = [2009, ‘sara']
List1.extend(List2)
print("Extended List : ", List1)

Output:
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, ‘sara']
Python inbuilt functions for Lists
index() Method
VI Description
The method index() returns the lowest index in list or which appear first in the list.
Syntax
list.index(obj)
Example:
List = [123, 'xyz', 'zara', 'abc'];
print ("Index for xyz : ", List.index( 'xyz' ))
print ("Index for zara : ", List.index( 'zara' ))

Output:
Index for xyz : 1
Index for zara : 2

Example :
seq = [1,2,3,4,5 ]
print(“Index for 4:” , seq. index(4))

Output: 3
Python inbuilt functions for Lists
insert() Method
VI Description
The method insert() inserts object or element at particular index position
Syntax
list. insert(index, obj)
Where , index − This is the Index where the object or element need to be inserted.
obj − This is the Object or element to be inserted into the given list

Example:
aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009) # insert element 2009 at index 3
print ("Final List : ", aList)
Output:
Final List : [123, 'xyz', 'zara', 2009, 'abc']
Python inbuilt functions for Lists
pop( ) Method
VI Description
The method pop( ) removes and returns last object or element from the list.
Syntax
list.pop(obj)
Example:
aList = [123, 'xyz', 'zara', 'abc']
print("A List : ", aList.pop( ))
print("B List : ", aList.pop(2))

Output:
A List : abc
B List : zara
Python inbuilt functions for Lists
remove( ) Method
VI Description
The method remove( ) removes the first occurrence of given value from the given list.

Syntax
list. remove(obj )
Example:
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.remove('xyz');
print("List : ", aList)
aList.remove('abc');
print("List : ", aList)

Output:
List : [123, 'zara', 'abc', 'xyz']
List : [123, 'zara', 'xyz']
Python inbuilt functions for Lists
reverse( ) Method
VI Description
The method reverse( ) reverses objects or element of list.
Syntax
list. reverse( )

Example:
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.reverse();
print ("List : ", aList)

Output:
List : ['xyz', 'abc', 'zara', 'xyz', 123]
Python inbuilt functions for Lists
sort( ) Method
VI Description
The method sort() sorts objects or element of list in ascending order.
Syntax
list.sort( ) # No arguments required

Example:
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.sort();
print("List : ", aList)

Output:
List : [123, 'abc', 'xyz', 'xyz', 'zara']

Example:
seq = [ 1,2,3,1,4,1,5]
print( seq.sort( ) )

Output: [ 1,1,1,2,3,4,5]
Python inbuilt functions for Lists
sort( ) Method
VI Description
The method sort() sorts objects or element of list in ascending order.
Syntax
list.sort( ) # No arguments required

Example:
aList = [‘123’, 'xyz', 'zara', 'abc', 'xyz'];
aList.sort();
print("List : ", aList)

Output:
List : [123, 'abc', 'xyz', 'xyz', 'zara']

Example:
seq = [ 1,2,3,1,4,1,5]
print( seq.sort( ) )

Output: [ 1,1,1,2,3,4,5]
List Comprehensions
List comprehension is used to create a new list from existing sequences.
VI Syntax:
[<expression> for < element >in < sequence > if < condition > ]

It is read as “ Compute the expression for each element in the sequence, if the
condition is true”

Example:
Create a list to store five different numbers such as 10,20,30,40 and 50.using the
for loop, add number 5 to the existing elements of the list.
without list comprehension :
list[10,20,30,40,50 ]
Print(list) With list comprehension :
Output: list=[10,20,30,40,50]
[10,20,30,40,50 ] list=[x+5 for x in list]
for i in range(0,len(list)): print(list)
list[i] = list[i]+5 Output:
print(list) [15, 25, 35, 45, 55]
Output:
[15,25,35,45,55]
List Comprehensions

VI Case 1. without list comprehension Case 2. with list comprehension


Example: Example:
list[10,20,30,40,50 ] list[10,20,30,40,50 ]
Print(list) list=[x+10 for x in list]
Output: print(list)
[10,20,30,40,50 ] Output:
[20,30,40,50,60]
for i in range(0,len(list)):
list[i] = list[i]+10
print(list)
Output:
[20,30,40,50,60]
List Comprehensions
Example:
VI square = [i**2 for i in range(1,6)]
print(square)

Output : [1, 4, 9, 16, 25]


List Comprehensions
With reference to above example we can say that list comprehension contains :
VI 1. An input sequence
2. A variable referring the input sequence
3. An optional expression
4. An output expression or output variable.

Example :
list[10,20,30,40,50]
list=[x+10 for x in list ]

An output An input sequence


variable

A variable referring an
input sequence
Some problems statement
1. Python Program to Calculate the Average of Numbers in a Given List
VI Problem Description
The program takes the elements of the list one by one and displays the average of the
elements of the list.
Problem Solution
1. Take the number of elements to be stored in the list as input.
2. Use a for loop to input elements into the list.
3. Calculate the total sum of elements in the list.
4. Divide the sum by total number of elements in the list.
5. Exit.
Program/Source Code
Here is source code of the Python Program to Calculate the Average of Numbers in a
Given List. The program output is also shown below.
n=int(input("Enter the number of elements to be inserted: "))
a=[ ]
for i in range(0,n):
elem=int(input("Enter element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2)) # rounds the average up to 2
decimal places.
Some problems statement
2. Python Program to Find the Largest Number in a List
VI Problem Description
The program takes a list and prints the largest number in the list.
Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Sort the list in ascending order.
4. Print the last element of the list.
5. Exit.
Code:
a=[ ]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Some problems statement
3. Python Program to Find the smallest Number in a List
VI Problem Description
The program takes a list and prints the smallest number in the list.
Code:
a=[ ]
n=int(input("Enter number of elements:"))
for i in range(0,n):
b=int(input("Enter element:"))
a.append(b)
a.sort(reverse=True)
print("Largest element is:",a[n-1])
Some problems statement
4. Python Program to Put Even and Odd elements in a List into Two Different Lists
VI Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if statement to
check if the element is even or odd.
4. If the element is even, append it to a separate list and if it is odd, append it to a
different one.
5. Display the elements in both the lists.
6. Exit.
Code:
a=[ ]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[ ] else:
odd=[ ] odd.append(j)
for j in a: print("The even list",even)
if(j%2==0): print("The odd list",odd)
even.append(j)
Some problems statement
5. WAP to check whether enter string is palindrome or not
VI
Code:
string=input("Enter the string")
revstr=string[::-1]
if string==revstr:
print("string is palindrome")
else:
print("string is not palindrome")

input : madam
Output: madam
Some problems statement
1.Write a program to create a list with elements 1,2,3,4,5.Display even elements of
VI list using list compression.

2. Write a program to create a list ‘A’ to generate sequence of a number (from 1 to


10),list ‘B’ to generate cubes of a number (from 1 to 10) and list ‘C’ with those
elements that are even and present in list ‘A’

3. Write the values of ‘a’ for the given code.


a=[1,2,3,4,5,6,7,8,9]
a[::2]=10,20,30,40,50
print(a)

Output: [10, 2, 20, 4, 30, 6, 40, 8, 50]


Tuple
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
VI The main difference between the tuples and the lists is that the tuples cannot be changed
unlike lists. Tuples use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally,


you can put these comma-separated values between parentheses also.

tup1 = ('physics', 'chemistry', 1997, 2000)


tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"

 The empty tuple is written as two parentheses containing nothing

tup1 = ( );
To write a tuple containing a single value you have to include a comma, even though
there is only one value −
tup1 = (50,)
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.
Accessing Values in Tuples and Updating Tuples
To access values in tuple, use the square brackets for slicing along with the index or
VI indices to obtain the value available at that index.

tup1 = ('physics', 'chemistry', 1997, 2000) Output


tup2 = (1, 2, 3, 4, 5, 6, 7 ) tup1[0]: physics
print ("tup1[0]: ", tup1[0]) tup2[1:5]: (2, 3, 4, 5)
print ("tup2[1:5]: ", tup2[1:5])

Tuples are immutable, which means you cannot update or change the values of tuple
elements. You are able to take portions of the existing tuples to create new tuples

tup1 = (12, 34.56)


tup2 = ('abc', 'xyz') # Following action is not valid for tuples
# tup1[0] = 100; # So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)

Output
(12, 34.56, 'abc', 'xyz')
Delete Tuple, Indexing and Slicing
Removing individual tuple elements is not possible. There is, of course, nothing wrong
VI with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement.
tup = ('physics', 'chemistry', 1997, 2000);
print (tup) del tup;
print ("After deleting tup : ")
print (tup)

T=('C++', 'Java', 'Python')

Python Expression Results Description


T[2] 'Python' Offsets start at zero
T[-2] 'Java' Negative: count from the
right
T[1:] ('Java', 'Python') Slicing fetches sections
Tuple functions

VI Sr.No Function & Description


.

1 len(tuple)Gives the total length of the tuple.

2 max(tuple)Returns item from the tuple with max value.

3 min(tuple)Returns item from the tuple with min value.


Exercise on List

VI l1=['abc',[(1,2),([3],4)],5]
print(l1[1])
print(l1[1][1][0])
print(l1[1][1][0][0])

Python Program to Find the Largest Number in a List.


Python Program to Find the Second Largest Number in a List.
Python Program to Put Even and Odd elements in a List into Two Different Lists.
Function
A function is a block of organized, reusable code that is used to perform a single,
VI related action .
As you already know, Python gives you many built-in functions like print(), etc. but
you can also create your own functions. These functions are called user-defined
functions.

simple rules to define a function in Python :


1. Every function should start with def keywords
2. Every function should have a name ( not equal to keyword)
3.parameters/ arguments included between parentheses
4. Every function name with or without arguments should end with (: )
5. The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax
def < functionname> ( < parameters >):

return [expression]
Function
1.Example:
VI def fun( ) : # function definition
print( “ I am learning python”)
fun ( ) # calling function

Output: I am learning python

2.Example:
def print_hello( ):
print('Hello!')
print_hello( )
print('1234567')
print_hello( )

output :
Hello!
1234567
Hello!

Note: The first two lines define the function. In the last three lines we call the
function twice.
Function
A programmer wants to find out the sum of numbers starting from 1 to 25 , 50
VI to 75 and 90 to 100 without function.
Code:
sum= 0
for i in range ( 1, 26 ):
sum = sum +i
print (“sum of integers from 1to 25 is:”, sum)

sum= 0
for i in range ( 50, 76 ):
sum = sum +i
print (“sum of integers from 50 to 76 is:”, sum)

sum= 0
for i in range ( 90, 101):
sum = sum +i
print (“sum of integers from 90 to 101 is:”, sum)

Output: sum of integers from 1to 25 is: 325


sum of integers from 50 to 75 is: 1625
sum of integers from 90 to 100 is: 1045
Function
A programmer wants to find out the sum of numbers starting from 1 to 25 , 50
VI to 75 and 90 to 100 with function.
Code:
def sum ( x, y ):
s=0
for i in range ( x, y+1 )
s = s+ i
print (‘ sum of integers from, ‘x’ to , ‘y’ is , s)
sum ( 1,25 )
sum ( 50, 75)
sum ( 90,100)

Output: sum of integers from 1to 25 is: 325


sum of integers from 50 to 75 is: 1625
sum of integers from 90 to 100 is: 1045
Function

VI
Example : Example:
x = 10 x = 10
y=20 y=20
z=30 z=30

def add (a,b,c) : def add (a,b,c):


s = a+b+c s = a+b+c
return s return
print(add ( x,y,z)) print(add ( x,y,z))

Output: 60 Output : None


Function
Example : write a program to find the maximum of two numbers
VI
Code:
def printMax ( num1, num2 ):
print (“ num1 = “ , num1)
print (“ num2 = “ , num1)
if num1 > num2 :
print ( “ The number”, num1, “ is greater than”, num2)
elif num2 > num1:
print ( “ The number”, num2, “ is greater than”, num1)
else:
print ( “ Both number”, num1, “ and”, num2, “ are equal”)
printMax ( 20, 10 )

Output:
num1 = 20
num2 = 10
The number 20 is greater than 10
Function
Example : write a program to find factorial of numbers
VI
Code:
def calc_ factorial ( num ):
fact = 1
print (“ Entered number is :”, num)
for i in range ( 1, num+1 ):
fact = fact* i
print ( “ factorial of number “ , num, “ is = “ ,fact )
number = int ( input ( “ Enter the number” ))
calc_ factorial( number)

Output:

Entered number = 5
Entered number is : 5
factorial of number 5 is = 120
Function
Recall that in mathematics the factorial of a number n is defined as n! = 1 ⋅ 2 ⋅ ... ⋅
VI n (as the product of all integer numbers from 1 to n). For example, 5! = 1 ⋅ 2 ⋅ 3 ⋅ 4 ⋅ 5
= 120. It is clear that factorial is easy to calculate, using a for loop. Imagine that we
need in our program to calculate the factorial of various numbers several times (or in
different places of code). Of course, you can write the calculation of the factorial once
and then using Copy-Paste to insert it wherever you need it:
Example:
# compute 3!
res = 1
for i in range(1, 4):
res *= i
print(res)
Output:
6

Functions are the code sections which are isolated from the rest of the program and
executed only when called. You've already met the function sqrt(), len() and print().
They all have something in common: they can take parameters (zero, one, or several of
them), and they can return a value (although they may not return). For example, the
function sqrt() accepts one parameter and returns a value (the square root of the given
number). The print() function can take various number of arguments and returns
nothing.
Function
Now we want to show you how to write a function called factorial() which takes a
VI single parameter — the number, and returns a value — the factorial of that number.
Example:

def factorial(n):
res = 1
for i in range(1, n + 1):
res *= i
return res
print(factorial(3))

Output:
6
Function
Here's the function max( ) that accepts two numbers and returns the maximum of them
VI (actually, this function has already become the part of Python syntax).
Example:
def max(a, b):
if a > b:
return a
else:
return b
print(max(3, 5))
print(max(5, 3))
print(max(int(input()), int(input())))

Output:
5
5
Function
Now you can write a function max3() that takes three numbers and returns the
VI maximum of them.
def max(a, b):
if a > b:
return a
else:
return b

def max3(a, b, c):


return max(max(a, b), c)

print(max3(3, 5, 4))

Output:
5
Pass by Reference vs Value
All parameters (arguments) in the Python language are passed by reference. It means if
VI you change what a parameter refers to within a function, the change also reflects back
in the calling function.

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function“
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)

Output
Values inside the function before change: [10, 20, 30]
Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
Function arguments

VI You can call a function by using the following types of formal arguments −
•Required arguments.
•Keyword arguments.
•Default arguments.
•Variable-length arguments.
• Required arguments.
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the
function definition.

# Function definition is here Output


def printme( str ): it gives a syntax error
"This prints a passed string into this function"
print (str) To call the function printme(),
# Now you can call printme function you definitely need to pass one
printme( ) argument, otherwise it gives a
syntax error .
Function arguments
• Keyword Arguments
VI Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.

Note that the order of parameters does not matter.

# Function definition is here


Output
def printinfo( name, age ): Name: miki
"This prints a passed info into this function" Age 50
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age = 50, name = "miki" )
Function arguments – Keyword arguments

VI # Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name) Output
print ("Age ", age) Name: 50
return Age miki
# Now you can call printinfo function
printinfo( age = "miki", name = 50 )

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function" Output
print ("Name: ", name) Name: 50
print ("Age ", age) Age miki
return
# Now you can call printinfo function
printinfo(age = "miki", name = “50”)
Function arguments – Keyword arguments

VI # Function definition is here


def printinfo( name):
"This prints a passed info into this function"
print ("Name: ", name) Output
print ("Age ", age) TypeError: printinfo() got
return an unexpected keyword
# Now you can call printinfo function argument 'age'
printinfo( age = 50 , name = "miki")
Function arguments
• Default Argument
VI A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument.
Output
# Function definition is here Name: miki
def printinfo( name, age = 35 ): Age 50
Name: miki
"This prints a passed info into this function“ Age 35
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age = 50, name = "miki" )
printinfo( name = "miki" )
Function arguments- Default argument

VI def printinfo( name, age = 35 ):


"This prints a passed info into this function“
print ("Name: ", name) Output
print ("Age ", age) Name: miki
Age 50
return
Name: miki
# Now you can call printinfo function Age 67
printinfo( age = 50, name = "miki" )
printinfo( name = "miki“, age=67 )

def printinfo( name, age = 35 ):


"This prints a passed info into this function“ Output
Name: miki
print ("Name: ", name) Age 35
print ("Age ", age) Name: miki
return Age 67
printinfo( name = "miki")
printinfo( name = "miki“, age=67 )
Function arguments- Default argument

VI
Example:
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Output
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Variable-length Arguments

VI You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and are not
named in the function definition, unlike required and default arguments. An asterisk (*)
is placed before the variable name that holds the values of all non keyword variable
arguments.

def printinfo( arg1, *vartuple ):


"This prints a variable passed arguments"
Output:
print ("Output is: ") Output is:
print (arg1) 10
for var in vartuple: Output is:
print (var) 70
return 60
50
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
Variable-length Arguments

VI
def printinfo( *vartuple ):
"This prints a variable passed arguments" Output:
print ("Output is: ") Output is:
10
for var in vartuple:
Output is:
print (var) 70
return 60
# Now you can call printinfo function 50
printinfo( 10 )
printinfo( 70, 60, 50 )
Return Values

VI The return statement is used to return a value from the function.

Example:
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Output
15
25
45
The return Statement

VI  You can return a value from a function as follows −


Example :
# Function definition is here
def sum( arg1, arg2 ): # Add both the parameters and return them."
total = arg1 + arg2
print( "Inside the function : ", total)
return total
# Now you can call sum function
total = sum( 10, 20 )
print ("Outside the function : ", total)

Output:
Inside the function : 30
Outside the function : 30
Return Values

VI Example:
def minimum(a,b):
if a<b:
return a
Output
elif b<a:
85
return b
else:
return " Both the number are equal"
print(minimum(100,85))

def minimum(a,b):
if a < b:
return a
elif b < a: Output:
return b Both the number are equal
else:
return " Both the number are equal"
print(minimum(100,100))
Python Lambda / The Anonymous Functions

VI A lambda function is a small anonymous function.


A lambda function can take any number of arguments, but can only have one
expression.
Syntax: The syntax of lambda functions contains only a single statement

lambda arguments : expression

Note: The expression is executed and the result is returned:


Example
A lambda function that adds 10 to the number passed in as an argument, and
print the result:

x = lambda a: a + 10
print(x(5))

Output: 15
Python Lambda / The Anonymous Functions

VI Lambda functions can take any number of arguments:

Example:
A lambda function that multiplies argument a with argument b and print the
result:

x = lambda a, b: a * b
print(x(5, 6))

Output: 30
Why Use Lambda Functions?

VI The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that argument
will be multiplied with an unknown number:

def myfunc(n):
return lambda a : a * n

Use that function definition to make a function that always doubles the
number you send in:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))

Output: 30
Why Use Lambda Functions?

VI use the same function definition to make a function that always triples the
number you send in:
Example
def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))
Output: 33
Why Use Lambda Functions?

VI use the same function definition to make both functions, in the same program:
Example:
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

Output:
22
33
The Anonymous Functions/ Lambda function

VI These functions are called anonymous because they are not


declared in the standard manner by using the def keyword. You can
use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just
one value in the form of an expression. They cannot contain
commands or multiple expressions.
An anonymous function cannot be a direct call to print because
lambda requires an expression
Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those in
the global namespace.
Although it appears that lambda's are a one-line version of a
function, they are not equivalent to inline statements in C or C++,
whose purpose is by passing function stack allocation during
invocation for performance reasons.
The Anonymous Functions

VI Example:
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))

Output:
Value of total : 30
Value of total : 40
Scope of Variables

VI All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier.
There are two basic scopes of variables in Python −
1.Global variables
2. Local variables
Global vs. Local variables

VI Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
This means that local variables can be accessed only inside the function in which
they are declared, whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared
inside it are brought into scope.
Example:
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 +
arg2; # Here total is local variable.
print ("Inside the function local total : ", total return total)
# Now you can call sum function
sum( 10, 20 )
(print "Outside the function global total : ", total)

Output:
Inside the function local total : 30
Outside the function global total : 0
Arguments
We can pass values to functions.
VI Example:
def print_ hello(n):
print('Hello ' * n)
print()
print_ hello(3)
print_ hello(5)
times = 2
print_ hello(times)

output:
Hello Hello Hello

Hello Hello Hello Hello Hello

Hello Hello

Note : When we call the print _ hello function with the value 3, that value gets stored
in the variable n. We can then refer to that variable n in our function’s code.
Arguments
You can pass more than one value to a function
VI Example:
def multiple_print(string, n):
print(string * n)
print()
multiple_print('Hello', 5)
multiple_print('A', 10)

Output:
HelloHelloHelloHelloHello

AAAAAAAAAA
Returning values
We can write functions that perform calculations and return a result.
VI Example 1:
Here is a simple function that converts temperatures from Celsius to Fahrenheit.

def convert (t):


return t* 9/5+32
print (convert(20))

Output :
68.0

Note: The return statement is used to send the result of a function’s calculations
back to the caller.
Notice that the function itself does not do any printing. The printing is done outside of
the function.
That way, we can do math with the result, like below.
print(convert(20)+5)
If we had just printed the result in the function instead of returning it, the result would
have been printed to the screen and forgotten about, and we would never be able to do
anything with it
Default arguments and keyword arguments
You can specify a default value for an argument. This makes it optional, and if the
VI caller decides not to use it, then it takes the default value.
Example:
def multiple _ print(string, n=1):
print(string * n)
print()
multiple _ print('Hello', 5)
multiple _ print('Hello')

Output:
HelloHelloHelloHelloHello

Hello

Note: Default arguments need to come at the end of the function definition, after all of
the non-default arguments.

You might also like