PS Material
PS Material
data_type array_name[rows][columns];
Here, x is a two-dimensional (2D) array. The array can hold 12 elements. You can think
the array as a table with 3 rows and each row has 4 columns.
Initialization of a 2D array
There are many different ways to initialize two-dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
1
FYBCA-SEM2-204 - Programming Skills
//traversing 2D array
for(i=0;i<4;i++) // rows
{
for(j=0;j<3;j++) // cols
{
printf("arr[%d] [%d] = %d \n",i , j, arr[i][j]);
} //end of j
}//end of i
getch(); return 0;
}
OUTPUT:
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
int main()
{
int temperature[CITY][WEEK];
Output:
2
FYBCA-SEM2-204 - Programming Skills
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26
Displaying values:
City 1, Day 1= 33
City 1, Day 2= 34
City 1, Day 3= 35
City 1, Day 4= 33
City 1, Day 5= 32
City 1, Day 6= 31
City 1, Day 7= 30
City 2, Day 1= 23
City 2, Day 2= 22
City 2, Day 3= 21
City 2, Day 4= 24
City 2, Day 5= 22
City 2, Day 6= 25
City 2, Day 7= 26
3
FYBCA-SEM2-204 - Programming Skills
Output:
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
Matrix addition in C language to add two matrices, i.e., compute their sum and print it. A
user inputs their orders (number of rows and columns) and the matrices. For example, if
the order is 2, 2, i.e., two rows and two columns and the matrices are:
First matrix:
12
34
Second matrix:
45
-1 5
The output is:
57
29
1. Two-Dimensional numeric Array operations: Addition of two Matrix
/*Addition of two matrix in C */
#include<stdio.h>
#include<conio.h>
int main()
{
int a[3][3],b[3][3],sum[3][3],i,j;
clrscr();
4
FYBCA-SEM2-204 - Programming Skills
scanf("%d",&a[i][j]);
}
}
printf("Enter Matrix B Elements: ");
for(i=0;i<3;i++) // rows
{
for(j=0;j<3;j++) //cols
{
printf("\n Enter Array element B[%d][%d] :",i,j);
scanf("%d",&b[i][j]);
}
}
printf("\n Matrix A : \n");
printf("~~~~~~~~~~~~~~~~~~~\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(" %d ",a[i][j]);
}
printf("\n");
}
int main()
{
int a[3][3],b[3][3],sub[3][3],i,j;
clrscr();
5
FYBCA-SEM2-204 - Programming Skills
6
FYBCA-SEM2-204 - Programming Skills
// Taking input until 1st matrix columns is not equal to 2nd matrix row
while(c1 != r2)
{
printf("Error!!!! Enter rows and columns again.\n");
printf("Enter rows and columns for the first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns for the second matrix: ");
scanf("%d %d", &r2, &c2);
}
printf("\nEnter elements for First Matrix: \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
7
FYBCA-SEM2-204 - Programming Skills
printf("Enter m1[%d][%d] : ", i, j);
scanf("%d", &m1[i][j]);
}
}
printf("\nEnter elements for Second Matrix: \n");
for(i = 0; i < r2;i++)
{
for(j = 0; j < c2; j++)
{
printf("Enter m2[%d][%d] : ", i, j);
scanf("%d", &m2[i][j]);
}
}
for (i = 0; i < r1;i++) // first matrix row
{
for (j = 0; j < c2; j++) // second matrix column
{
mul[i][j] = 0;
for (k = 0; k < r2; k++)
{
mul[i][j] = mul[i][j] + ( m1[i][k] * m2[k][j] );
}
}
}
printf("\n First Matrix : \n");
for(i=0;i < r1;i++)
{
for(j=0;j < c1;j++)
{
printf("%d\t", m1[i][j]);
}
printf("\n");
}
printf("\n Second Matrix:\n");
for(i=0;i < r2;i++)
{
for(j=0;j < c2;j++)
{
printf("%d\t", m2[i][j]);
}
printf("\n");
}
printf("\nMultiplication of Matrices : \n");
for(i=0;i < r1;i++)
{
for(j=0;j < c2;j++)
{
printf("%d\t", mul[i][j]);
}
printf("\n");
}
getch();
return 0;
}
8
FYBCA-SEM2-204 - Programming Skills
9
FYBCA-SEM2-204 - Programming Skills
for(j=0;j<3;j++)
{
printf("%d\t",a[j][i]);
}
printf("\n");
}
getch(); return 0;
}
The size of a two dimensional array is equal to the multiplication of number of rows and
the number of columns present in the array. We do need to map two dimensional array to
the one dimensional array in order to store them in the memory.
A 3 X 3 two dimensional array is shown in the following image. However, this array needs
to be mapped to a one dimensional array in order to store it into the memory.
A two dimensional Array A is the collection of 'm X n' elements. Programming language
stores the two dimensional array in one dimensional memory in either of two ways -
There are two main techniques of storing 2D array elements into memory
1. Row Major ordering
In row major ordering, all the rows of the 2D array are stored into the memory
contiguously. Considering the array shown in the above image, its memory allocation
according to row major order is shown as follows.
first, the 1st row of the array is stored into the memory completely, then the 2nd row of
the array is stored into the memory completely and so on till the last row.
10
FYBCA-SEM2-204 - Programming Skills
First row of the array occupies the first set of memory locations reserved for the array;
Second row occupies the next set, and so forth.
To determine element address A[i,j]:
first, the 1st column of the array is stored into the memory completely, then the
2nd row of the array is stored into the memory completely and so on till the last column
of the array.
Order elements of first column stored linearly and then comes elements of next column.
To determine element address A[i,j]:
Location ( A[ i,j ] ) = Base Address + ( M x ( j - 1 ) ) + ( i - 1 )
For example :
Given an array [1…6,1…8] of integers. Calculate address element A[5,7], where
BA=300.
Solution:- I = 5 , J = 7, M= 6 , N= 8
= 300 + (6 x 6) + 4
= 300 + 36 + 4
= 340
11
FYBCA-SEM2-204 - Programming Skills
The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the character
array containing the string is one more than the number of characters in the word
"Hello."
Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the '\0' at the end of the string when it initializes the
array. Let us try to print the above mentioned string –
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
OUTPUT:
Greeting message: Hello
The order of the subscripts is kept in mind during declaration. The first subscript [5]
represents the number of Strings that we want our array to contain and the second
12
FYBCA-SEM2-204 - Programming Skills
subscript [10] represents the length of each String. This is static memory allocation. We
are giving 5*10=50 memory locations for the array elements to be stored in the array.
The areas marked in green shows the memory locations that are reserved for the array
but are not used by the string. Each character occupies 1 byte of storage from the
memory.
13
FYBCA-SEM2-204 - Programming Skills
Example2: Lexicographic order is the way of ordering words based on the alphabetical
order of their component letters. It is also known as lexical order, dictionary order, and
alphabetical order. It is similar to the way we search for any word in the dictionary. We
start our search by simply searching for the first letter of the word. Then we try to find
the second letter and so on. The words in the dictionary are arranged in lexicographic
order.
/* Write a program to sort elements in lexicographical order in C language
(dictionary order). */
#include<stdio.h>
14
FYBCA-SEM2-204 - Programming Skills
#include<string.h>
#include<conio.h>
int main()
{
char str[10][50],temp[50];
int i,j; clrscr();
printf("Enter 10 Words:\n");
for(i=0;i<10;i++)
{
printf("\n Enter String %d : ",i+1);
scanf("%s[^\n]",str[i]);
}
for(i=0;i<9;i++)
{
for(j=i+1;j<10;j++)
{
if( strcmp(str[i],str[j]) > 0 )
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf("\n In Lexicographical order: \n");
for(i=0;i<10;i++)
puts(str[i]);
getch();
return 0;
}
15
FYBCA-SEM2-204 - Programming Skills
#include<stdio.h>
#include<conio.h>
int main()
{
char str1[100], str2[50];
int i, j; clrscr();
Output:
printf("Enter first string: "); Enter first string: PROGRAMMING
gets(str1); Enter second string: IS FUN!!!!
After Concatenation first string
printf("Enter second string: "); becomes : PROGRAMMING IS FUN!!!!
gets(str2);
Example5: Write a C program to Find the length of the string without using
string manipulation library functions.
#include<stdio.h>
#include<conio.h>
int main() OUTPUT:
{
Enter string: sdj international college
char str[200];
length of entered string is=25
int i; clrscr();
printf("Enter string: ");
scanf("%[^\n]",str);
for(i=0;str[i]!='\0';i++);
printf("length of entered string is=%d",i);
getch(); return 0;
}
16
FYBCA-SEM2-204 - Programming Skills
The above program may fulfil our requirement of storing the information of an entity
student. However, the program is very complex, and the complexity increase with the
amount of the input. The elements of each of the array are stored contiguously, but all
the arrays may not be stored contiguously in the memory. C provides you with an
additional and simpler approach where you can use a special data structure, i.e.,
structure, in which, you can group all the information of different data type regarding an
entity.
17
FYBCA-SEM2-204 - Programming Skills
What is Structure?
Structure in c is a user-defined data type that enables us to store the collection of different
data types. Each element of a structure is called a member. Structures can simulate the
use of classes and templates as it can store different information. The struct keyword is
used to define the structure.
Let's see the syntax to define the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Here, struct is the keyword; employee is the name of the structure; id, name,
and salary are the members or fields of the structure.
Let's understand it by the diagram given below:
18
FYBCA-SEM2-204 - Programming Skills
Points to remember while defining a Structure
1. Key Word struct is required for defining structure.
2. Structure_name can be any valid identifier.
3. Set of variables will be declared inside curly braces “{ }” is known as structure body.
4. Different types of variable or array or structure can be declared inside structure
body.
5. Only declaration is allowed inside structure body, we cannot initialize variable inside
structure body.
6. The closing curly brace in the structure type declaration must be followed by a
semicolon (;)
7. Defining structure will not declare any variable it acts as a template which means
defining structure will not allocate any memory to the variables it is just represents
information (set of variables).
8. Structure name will be used for creating instance of a structure (declaring a variable
of type structure).
9. Structure Definition is mostly written before starting of main function which can be
used globally. (Globally means structure variables can be created anywhere in the
program either in main function or User Defined Function).
1st way:
Let's see the example to declare the structure variable by struct keyword. It should be
declared within the main function.
struct employee
{
int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure. Here,
e1 and e2 can be treated in the same way as the objects in C++ and Java.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
struct employee
{
int id;
char name[50];
float salary;
}e1,e2;
19
FYBCA-SEM2-204 - Programming Skills
Which approach is good?
1. If number of variable are not fixed, use the 1st approach. It provides you the
flexibility to declare the structure variable many times.
2. If number of variable are fixed, use 2nd approach. It saves your code to declare a
variable in main() function.
Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at compile
time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
OR
struct Patient p1;
/* example of typedef */
#include<stdio.h>
#include<conio.h>
void main()
{
typedef int LENGTH;
LENGTH l, w, h;
l=5,w=10,h=45;
clrscr();
printf("\n The value of Length is %d",l);
printf("\n The value of Width is %d",w);
printf("\n The value of Height is %d",h);
getch();
}
Using typedef with structures
Syntax:
typedef struct Structure_name Structure_variable
Example:
typedef struct student status;
When we use “typedef” keyword before struct <tag_name> like above, after that we
can simply use type definition “status” in the C program to declare structure variable.
Now, structure variable declaration will be, “status record”.
20
FYBCA-SEM2-204 - Programming Skills
This is equal to “struct student record”. Type definition for “struct student” is
status. i.e. status = “struct student”
Structure declaration using typedef in c:
typedef struct student
{
int mark [2];
char name [10];
float average;
} status;
To declare structure variable, we can use the below statements.
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
Let's see the code to access the id member of p1 variable by . (member) operator.
p1.id
21
FYBCA-SEM2-204 - Programming Skills
{
int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
e1.id=101; //store first employee information
strcpy(e1.name, "Bhumika Patel"); //copying string into char array
printf( "employee 1 id : %d\n", e1.id); //printing first employee information
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
OUTPUT :
employee 1 id : 101
employee 1 name : Bhumika Patel
22
FYBCA-SEM2-204 - Programming Skills
Defining Union
Like structure, Union in c language is a user-defined data type that is used to store
the different type of elements.
At once, only one member of the union can occupy the memory. In other words, we
can say that the size of the union in any instance is equal to the size of its largest
element.
23
FYBCA-SEM2-204 - Programming Skills
}e1; //declaring e1 variable for union
int main( )
{
e1.id=101; //store first employee information
strcpy(e1.name, "Bhumika Patel"); //copying string into char array
printf( "employee 1 id : %d\n", e1.id); //printing first employee information
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 1869508435
employee 1 name : Bhumika Patel
Note: As you can see, id gets garbage value because name has large memory
size. So only name will have actual value.
24
FYBCA-SEM2-204 - Programming Skills
4. Array elements are referred by array Structure elements are referred by its
index. variable name using period sign with
structure variable.
4. It is difficult to represent complex It is easy to represent complex and
related data using array. related data using structure.
5. Array does not have any special “struct” keyword is used in structure
keyword to declare it instead it declaration.
used [] bracket to define array size
along with data type.
6. Syntax: Sytanx :
data type arr_name [size]; struct struct_name
{
Type member1 ;
Type member2 ;
};
A function is a block of statements that performs a specific task. Suppose you are building
an application in C language and in one of your program, you need to perform a same task
more than once. In such case you have two options –
a) Use the same set of statements every time you want to perform the task
b) Create a function to perform that task, and just call it every time you need to perform
that task.
Using option (b) is a good practice and a good programmer always uses functions while
writing codes in C.
Uses of C functions:
1. C functions are used to avoid rewriting same logic/code again and again in a
program.
2. There is no limit in calling C functions to make use of same functionality wherever
required.
3. We can call functions any number of times in a program and from any place in a
program.
4. A large C program can easily be tracked when it is divided into functions.
25
FYBCA-SEM2-204 - Programming Skills
5. The core concept of C functions are, re-usability, dividing a big task into small pieces
to achieve the functionality and to improve understand ability of very large C
programs.
Types of functions
1. Built-in (Library) Functions: The system provided these functions and stored in
the library. Therefore it is also called Library Functions. e.g. scanf(), printf(),
strcpy(), strlwr(), strcmp(), strlen(), strcat() etc. To use these functions, you just
need to include the appropriate C header files.
2. User Defined Functions: These functions are defined by the user at the time of
writing the program.
void functionName()
And, the compiler starts executing the codes inside functionName().
The control of the program jumps back to the main() function once code inside the
function definition is executed.
26
FYBCA-SEM2-204 - Programming Skills
In the above example, int addNumbers(int a, int b); is the function prototype which
provides the following information to the compiler:
1) name of the function is addNumbers()
2) return type of the function is int
3) two arguments of type int are passed to the function
Note: The function prototype is not needed if the user-defined function is defined before
the main() function.
2. Calling a function
Control of the program is transferred to the user-defined function by calling it.
Syntax of function call:
functionName(argument1, argument2, ...);
In the above example, the function call is made using addNumbers(n1, n2); statement
inside the main() function.
3. Function definition
Function definition contains the block of code to perform a specific task. In our example,
adding two numbers and returning it.
Syntax of function definition:
returnType functionName(datatype1 argument1, datatype2 argument2, ...)
{
//body of the function
}
When a function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a function.
27
FYBCA-SEM2-204 - Programming Skills
Example1: Creating a user defined function addnumbers()
#include <stdio.h>
int addnumbers(int num1, int num2); // Function declaration or prototype
int main()
{
int var1, var2,sum; clrscr();
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);
sum = addnumbers (var1, var2); // function calling
printf("Output: %d", sum); getch();
return 0;
}
int addnumbers (int num1, int num2) // Function definition
{
int result;
result = num1+num2; // Arguments are used here
return result;
}
Output:
Enter number 1: 100
Enter number 2: 120
Output: 220
Return Statement
The return statement terminates the
execution of a function and returns a
value to the calling function. The
program control is transferred to the
calling function after the return
statement.
Example2: Creating a void user defined function that doesn’t return anything
#include <stdio.h>
/* function return type is void and it doesn't have parameters*/
void introduction()
{
printf("Hi I am Function \n");
printf("U can call me any number of time.\n");
printf("How are you?");
}
int main()
28
FYBCA-SEM2-204 - Programming Skills
{
introduction(); /*calling function*/
return 0;
}
Output:
Hi I am Function
U can call me any number of time.
How are you?
/* function declaration */
int max(int num1, int num2); // Formal parameters in function call
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret; clrscr();
/* calling a function to get max value */
ret = max(a, b); // Actual parameters in function call
printf( "Max value is : %d\n", ret);
getch(); return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
29
FYBCA-SEM2-204 - Programming Skills
return result;
}
area = cal_area(r);
printf( "Area of circle is : %f \n", area );
getch(); return 0;
}
float pi()
{
const float pi=3.14;
return pi;
}
float cal_area(float rad)
{ /* local variable declaration */
float result;
result = pi() * rad * rad ; // calling function from other function
return result;
}
These 4 programs below check whether the integer entered by the user is an even
number or not.
The output of all these programs below is the same, and we have created a user-defined
function in each example. However, the approach we have taken in each example is
different.
1: No arguments passed and no return value
2: No arguments passed but a return value
3: Argument passed but no return value
4: Argument passed and a return value
30
FYBCA-SEM2-204 - Programming Skills
31
FYBCA-SEM2-204 - Programming Skills
32
FYBCA-SEM2-204 - Programming Skills
33
FYBCA-SEM2-204 - Programming Skills
Advantages of Recursion
1) Recursion is more elegant and requires few variables which make program clean.
2) Recursion can be used to replace complex nesting code by dividing the problem into
same problem of its sub-type.
Disadvantages of Recursion
1) In other hand, it is hard to think the logic of a recursive function. It is also difficult to
debug the code containing recursion.
34
FYBCA-SEM2-204 - Programming Skills
Unit-1-Practical Problems
Multidimensional Array
1. Write a Menu base C program with following options.
1. Addition of two Matrices.
2. Subtraction of two Matrices.
3. Multiplication of two Matrices.
4. Transpose of Single Matrix.
5. Exit.
2. Write C program to count total duplicate elements in an array.
3. Write C program to check matrix is an identity matrix example.
4. Write C program to find sum of each column in a matrix.
5. Write C program to find sum of each row in a matrix.
6. Write C program to check two matrices are equal or not.
7. Write C program to find lower triangle matrix.
8. Write C program to find upper triangle matrix.
9. Write C program to find sum of each row and column of a matrix.
10 20 30 60
40 50 60 150
70 80 90 240
120 150 180
User defined Function
1. Write C Program to find area of rectangle using User defined Function.
2. Write C Program to find perimeter of rectangle using User defined Function.
3. Write C program to find area of a triangle using User defined Function.
4. Write C Program to find diameter, circumference and area of circle using User defined
Function.
5. Write C program to convert centimeter to meter and kilometer using User defined
Function.
6. Write C program to convert temperature from degree Celsius to Fahrenheit using
UDF.
7. Write C Program to calculate simple interest using User defined Function.
8. Write C Program to find power of a number using User defined Function.( without
pow())
9. Write C Program to find cube using function using User defined Function.
10. Write C program to check the given string is palindrome or not using UDF.
11. Write C Program to convert decimal number to binary number using the UDF.
12. Write C Program to get largest element of an array using the UDF.
13. Write C Program to find maximum and minimum element in array using UDF.
14. Write C program to sort numeric array in ascending or descending order using UDF.
15. Write C program to search element in an array using User define Function.
16. Write C program Menu base Calculator using UDF.
17. Write Menu base C Program with following option using UDF.
1. To check given number is Prime or not
2. To check given number is Armstrong or not.
3. To check given number Perfect or not.
4. Exit
18. Write C Program to find Sum of Series 1²+2²+3²+…..+n² Using Recursion in C.
35
Chapter 2: Python Fundamentals
Python Program
Structure
Blocks and
Comments Expressions Statements Functions Indentation
Comments
• Comments are the additional readable information to get better understanding about the
source code.
• Comments in Python are the non-executable statements.
• Comments are of 2 types:
o 1)Single Line Comments: which begin with a hash symbol (#).
o E.g. #This is a sample python program
o 2)Multiline Comments: which begins with ‘’’ and ends with ‘’’(3 single quotes)
o E.g. ‘’’ This is a sample python program1
Page 1
Chapter 2: Python Fundamentals
Expression:
• An expression is any legal combination of symbols that represents a value.
• An expression represents something which python evaluates and which produces a value.
• E.g. 10, x + 5
Statements:
• A statement is a programming instruction that does something i.e. some action takes place.
• A statement executes and may or may not results in a value.
• E.g. print(x + 2), y = x + 5, x = 10
Functions:
• A function is a code that has a name and it can be reused (executed again) by specifying its
name in the program, where needed.
• A function begin with ‘def’ statement
• E.g. goinggood( )
Page 2
Chapter 2: Python Fundamentals
def foo():
print("Hi")
if True:
print("true")
else:
print("false")
print("Done")
Variables:
• Variables are containers for storing data values.
Rules for Python Variable:
• A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
• 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).
Page 3
Chapter 2: Python Fundamentals
Creating Variables
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example:
x=4 # x is of type int
z = "Sally" # x is now of type str
y=’Alice’
print(x)
Note: String variables can be declared either by using single or double quotes.
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example:
x, y, z = "Orange", "Banana", "Cherry" Output:
print(x) Orange
print(y) Banana
print(z) Cherry
Page 4
Chapter 2: Python Fundamentals
x=5 Output:
print(type(x)) <class 'int'>
Other Examples:
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) Complex
x = bool(5) bool
Python Casting
• There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data types,
including its primitive types.
• Casting in python is therefore done using functions as follows:
• int() – an integer number from an integer literal, a float literal (by removing all decimals), or a
string literal (providing the string represents a whole number)
• float() - a float number from an integer literal, a float literal or a string literal (providing the string
represents a float or an integer)
• str() - a string from a wide variety of data types, including strings, integer literals and float literals
Example:
Page 5
Chapter 2: Python Fundamentals
int()
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
float()
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
str()
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Example:
def my_function():
print("Hello from a function")
Calling a Function
• To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
Arguments
• Information can be passed into functions as arguments.
Page 6
Chapter 2: Python Fundamentals
• Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
• The following example has a function with one argument (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:
Example:
def my_function(fname): Output:
print(“ Welcome ” + fname ) Welcome Jay
Welcome Parth
my_function("Jay") Welcome Dhruvi
my_function("Parth")
my_function("Dhruvi")
Number of Arguments
• By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you must call the function with 2 arguments, not more, and
not less.
Example
(This function expects 2 arguments, and gets 2 arguments:)
def my_function(fname, lname): Output:
print(fname + " " + lname) Alice Evan
Page 7
Chapter 2: Python Fundamentals
print(my_function(3)) 45
print(my_function(5))
print(my_function(9))
Global Variables
• Variables that are created outside of a function are known as global variables.
• Global variables can be used by everyone, both inside of functions and outside.
Example:
x = "awesome" #Global Variable Output:
Python is awesome
def myfunc():
print("Python is " + x)# Printing global Variable value
Note: If you create a variable with the same name inside a function, this variable will be local, and can
only be used inside the function. The global variable with the same name will remain as it was, global
and with the original value.
Example:
x = "awesome" #global variable Output:
Python is fantastic
def myfunc(): Python is awesome
x = "fantastic"
print("Python is " + x) #local variable
print("Python is " + x)
Example
Page 8
Chapter 2: Python Fundamentals
• To change the value of a global variable inside a function, refer to the variable by using the
global keyword:
x = "awesome" Output:
Python is fantastic
def myfunc():
global x
x = "fantastic"
print("Python is " + x)
Page 9
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
1
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
As shown in Python, the slice operator [] is used to access the individual characters of
the string. However, we can use the : (colon) operator in Python to access the substring
from the given string. Consider the following example.
2
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost character, which
is indicated as -1. The second rightmost index indicates -2, and so on. Consider the
following image.
3
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
However, in example 1, the string str can be assigned completely to a new content as
specified in the following example.
str = "HELLO"
print(str)
str = "hello"
print(str)
OUTPUT:
HELLO
hello
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either
side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of the
same string.
[] It is known as slice operator. It is used to access the sub-strings of a
particular string.
[:] It is known as range slice operator. It is used to access the characters from
the specified range.
in It is known as membership operator. It returns if a particular sub-string is
present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns
true if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where
we need to print the actual meaning of escape characters such as
"C://python". To define any string as a raw string, the character r or R is
followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers
used in C programming like %d or %f to map their values in python. We will
discuss how formatting is done in python.
4
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Consider the following example to understand the real use of Python operators.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1) # prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python39') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python39
The string str : Hello
Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the
given statement can be written in single quotes or double quotes but it will raise the
SyntaxError as it contains both single and double-quotes.
Consider the following example to understand the real use of Python operators.
str = "They said, "Hello what's going on?""
print(str)
Output:
SyntaxError: invalid syntax
We can use the triple quotes to accomplish this problem but Python provides the escape
sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by
a special character and it interpreted differently. The single quotes inside the string must
be escaped. We can apply the same as in the double quotes.
Example
# using triple quotes
print('''They said, "What's there?"''')
5
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Output:
Python1 Python2 Python3
2. \\ Backslash print("\\")
Output:
\
3. \' Single Quotes print('\'')
Output:
'
4. \\'' Double Quotes print("\"")
Output:
"
5. \a ASCII Bell print("\a")
6. \b ASCII Backspace(BS) print("Hello \b World")
Output:
Hello World
7. \f ASCII Formfeed print("Hello \f World!")
Hello World!
8. \n ASCII Linefeed print("Hello \n World!")
Output:
Hello
World!
9. \r ASCII Carriege print("Hello \r World!")
Return(CR) Output:
World!
10. \t ASCII Horizontal Tab print("Hello \t World!")
Output: Hello World!
11. \v ASCII Vertical Tab print("Hello \v World!")
Output:
Hello
World!
12. \ooo Character with octal value print("\110\145\154\154\157")
Output: Hello
13 \xHH Character with hex value. print("\x48\x65\x6c\x6c\x6f")
Output: Hello
6
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string
... My value is %s"%(Integer,Float,String))
Output:
Hi I am Integer ... My value is 10
Hi I am float ... My value is 1.290000
Hi I am string ... My value is Mihir
3.1.3 String Methods: (center, count, join, len, max, min, replace, lower, upper,
replace, split)
No Method Description
1 format(value) It returns a formatted version of S, using the passed
value.
Eg: #named indexes:
txt1 = "My name is {fname}, I'm
{age}".format(fname = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)
print(txt1)
print(txt2)
print(txt3)
2 center(width ,fillchar) It returns a space padded string with the original
string centred with equal number of left and right
spaces.
Eg: str = "Hello Javatpoint"
# Calling function
str2 = str.center(20,'#')
# Displaying result
print("Old value:", str)
print("New value:", str2)
3 string.count(value, start, It returns the number of times a specified value
end) appears in the string.
value: Required. A String. The string to value to
search for
start: Optional. An Integer. The position to start the
search. Default is 0
end: Optional. An Integer. The position to end the
search. Default is the end of the string
Eg1: txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)
Eg2: txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple", 10, 24)
print(x)
4 join(seq) It merges the strings representation of the given
sequence.
Eg : str = "->" # string
list = {'Java','C#','Python'} # iterable
str2 = str.join(list)
print(str2)
5 len(string) It returns the length of a string.
Eg: x = len("Hello")
print(x)
7
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
6 max() It returns the item with the highest value, or the item
with the highest value in an iterable.
If the values are strings, an alphabetically comparison
is done.
Eg: x = max("Mike", "John", "Vicky")
print(x)
7 min() It returns the item with the lowest value, or the item
with the lowest value in an iterable.
If the values are strings, an alphabetically comparison
is done.
Eg: x = min("Bhumi", "John", "Vicky")
print(x)
8 replace(old,new[,count]) It replaces the old sequence of characters with the
new sequence. The max characters are replaced if max
is given.
Eg1: txt = "one one was a race horse, two two was
one too."
x = txt.replace("one", "three")
print(x)
Eg2: txt = "one one was a race horse, two two was
one too."
x = txt.replace("one", "three", 2)
print(x)
9 upper() It converts all the characters of a string to Upper Case.
Eg: txt = "Hello my friends"
x = txt.upper()
print(x)
10 lower() It converts all the characters of a string to Lower case.
Eg1: txt = "Hello my FRIENDS"
x = txt.lower()
print(x)
11 split(separator, Splits the string according to the delimiter str. The
maxsplit) string splits according to the space if the delimiter is
not provided. It returns the list of substring
concatenated with the delimiter.
separator :Optional. Specifies the separator to use
when splitting the string. By default any whitespace is
a separator
maxsplit :Optional. Specifies how many splits to do.
Default value is -1, which is "all occurrences"
eg1: txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
Eg2: txt = "apple#banana#cherry#orange"
# setting the maxsplit parameter to 1, will return a list
with 2 elements!
x = txt.split("#", 1)
print(x)
8
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
3.2 Operators:
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built
in a specific programming language. Python provides a variety of operators, which are
described as follows.
9
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
3.2.5 Identity and member operators (is, is not, in, not in)
Membership Operators
Python membership operators are used to check the membership of value inside a
Python data structure. If the value is present in the data structure, then the resulting
value is true otherwise it returns false.
Operator Description
in It is evaluated to be true if the first operand is found in the second operand
(list, tuple, or dictionary).
not in It is evaluated to be true if the first operand is not found in the second
operand (list, tuple, or dictionary).
Identity Operators
The identity operators are used to decide whether an element certain class or type.
Operator Description
is It is evaluated to be true if the reference present at both sides point to the
same object.
is not It is evaluated to be true if the reference present at both sides do not point
to the same object.
10
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Operator Precedence
The precedence of the operators is essential to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in Python is
given below.
Operator Description
exponent operator is given priority over all the others
**
used in the expression.
~+- negation, unary plus, and minus.
multiplication, divide, modules, reminder, and floor
* / % //
division.
+- Binary plus, and minus
>> << Left shift. and right shift
& Binary and(Bitwise)
^| Binary xor, and or (Bitwise)
Comparison operators (less than, less than equal to,
<= < > >=
greater than, greater then equal to).
<> == != Equality operators.
= %= /=
//= -=
Assignment operators
+=
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators
11
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
UNIT-4: Python conditional and iterative statements
4.1 if statement, if..elif statement, if..elif…else statements, nested if
Decision making is the most important aspect of almost all the programming languages.
As the name implies, decision making allows us to run a particular block of code for a
particular decision. Here, the decisions are made on the validity of the particular
conditions. Condition checking is the backbone of decision making.
statement
s 1
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
if num%2 == 0:
print("Number is even")
s 2
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Example 1: Program to check whether a person is eligible to vote or not.
age = int (input("Enter your age? "))
if age >= 18:
print("You are eligible to vote !!")
else:
print("Sorry ! you have to wait !!")
s 3
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Example 1 Example of
number = int(input("Enter the number : "))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Example2: Python Program to take in the marks of 5 subjects and display the
grade
rno=input("Enter Student Roll Number :")
sname=input("Enter Student Name :")
sub1=int(input("Enter marks of HTML subject: "))
sub2=int(input("Enter marks of ET & IT subject: "))
sub3=int(input("Enter marks of os subject: "))
sub4=int(input("Enter marks of PS subject: "))
sub5=int(input("Enter marks of RDBMS subject: "))
s 4
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Python Nested if statements
We can have if...elif...else statement inside another if...elif...else statement. This is
called nesting in computer programming. Any number of these statements can be nested
inside one another. Indentation is the only way to figure out the level of nesting. They
can get confusing, so they must be avoided unless necessary.
Python Nested if Example
'''In this program, we input a number check if the number is positive or
Negative or zero and display an appropriate message
This time we use nested if statement '''
Advantages of loops
There are the following advantages of loops in Python.
1. It provides code re-usability.
2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked
lists).
There are the following loop statements in Python.
Loop Description
Statement
while loop The while loop is to be used in the scenario where we don't know the
number of iterations in advance. The block of statements is executed in the
while loop until the condition specified in the while loop is satisfied. It is
also called a pre-tested loop.
for loop The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. The for loop is also called as a pre-tested loop. It
is better to use for loop if the number of iteration is known in advance.
s 5
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Example
i=1
number = int(input("Enter the number:"))
while i <= 10:
print("%d X %d = %d \n"%(number, i, number * i))
i = i+1
s 6
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Example2: nested while loop to find the prime numbers from 2 to 100
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
s 7
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
i += 1
continue
print('Current Letter :', str1[i])
i += 1
3. Pass Statement - The pass statement is used to declare the empty loop. It is also
used to define empty class, function, and control statement. In Python programming, the
pass statement is a null statement. The difference between a comment and a pass
statement in Python is that while the interpreter ignores a comment entirely, pass is not
ignored. However, nothing happens when the pass is executed. It results in no operation
(NOP).
Syntax of pass
pass
We generally use it as a placeholder.
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in
the future. They cannot have an empty body. The interpreter would give an error. So, we use the
pass statement to construct a body that does nothing.
Suppose we have a loop, and we do not want to execute right this moment, but we will execute in
the future. Here we can use the pass. Consider the following example.
Example of pass
# pass is just a placeholder for we will add functionality later.
values = {'P', 'y', 't', 'h','o','n'}
for val in values:
pass
4.2.2 for loop, range, break, continue, pass and else with for loop, nested for loop.
for loop: The for loop in Python is used to iterate the statements or a part of the
program several times. It is frequently used to traverse the data structures like list,
tuple, or dictionary.The syntax of for loop in python is given below.
for iterating_var in sequence:
statement(s)
s 8
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
s 9
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Example-3: Program to print even number using step size in range().
n = int(input("Enter the number "))
for i in range(2,n,2):
print(i)
s 10
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
print("for loop is exhausted");
print("The loop is broken due to break statement...came out of the loop")
In the above example, the loop is broken due to the break statement; therefore, the else
statement will not be executed. The statement present immediate next to else block will
be executed.
4.3 List: creating list, indexing, accessing list members, range in list, List
methods (append, clear, copy, count, index, insert, pop, remove, reverse, sort).
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python
consists of six data-types that are capable to store the sequences, but the most common
and reliable type is the list.
A list can be defined as a collection of values or items of different types. The items in the
list are separated with the comma (,) and enclosed with the square brackets [].
A list can be define as below:
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
print(type(L1))
print(type(L2))
#If we try to print the type of L1, L2 using type() function then it will come out to be a list.
OUTPUT
<class 'list'>
<class 'list'>
Characteristics of Lists
The list has the following characteristics:
1. The lists are ordered.
2. The element of the list can access by index.
3. The lists are the mutable type.
4. The lists are mutable types.
5. A list can store the number of various elements.
s 11
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Both lists have consisted of the same elements, but the second list changed the index
position of the 5th element that violates the order of lists. When compare both lists it
returns the false.
The list example in detail
emp = ["John", 102, "USA"]
Dep1 = ["CS",10]
Dep2 = ["IT",11]
HOD_CS = [10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data...")
print("Name : %s, ID: %d, Country: %s" %(emp[0],emp[1],emp[2]))
print("printing departments...")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s" %
(Dep1[0],Dep1[1],Dep2[0],Dep2[1]))
print("HOD Details.....")
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
print("\n \n",type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
We can get the sub-list of the list using the following syntax.
list_varible[start:stop:step]
1. The start denotes the starting index position of the list.
2. The stop denotes the last index position of the list.
3. The step is used to skip the nth element within a start:stop
s 12
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Consider the following example:
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
OUTPUT:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
Unlike other languages, Python provides the flexibility to use the negative indexing also.
The negative indices are counted from the right. The last element (rightmost) of the list
has the index -1; its adjacent left element is present at the index -2 and so on until the
left-most elements are encountered.
Let's have a look at the following example where we will use negative indexing
to access the elements of the list.
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
OUTPUT:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
We can use the index operator [] to access an item in a list. In Python, indices start at 0.
So, a list having 5 elements will have an index from 0 to 4.
Trying to access indexes other than these will raise an IndexError. The index must be an
integer. We can't use float or other types, this will result in TypeError.
Nested lists are accessed using nested indexing.
s 13
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
# List indexing
my_list = ['p', 'r', 'o', 'b', 'e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
print(n_list[0][1])
print(n_list[1][3])
Output:
p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which
can be iterated as follows.
list = ["John", "David", "James", "Jonathan"]
for i in list:
print(i)
OUTPUT:
John
David
James
Jonathan
Check if Item Exists
To determine if a specified item is present in a list use the in keyword:
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
s 14
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
# Correcting mistake values in a list
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] = 1
print(odd)
output:
[range(10, 20)]
As we can see in the output, the result is not exactly what we were expecting because
Python does not unpack the result of the range() function.
Code #1: We can use argument-unpacking operator i.e. *.
# Create a list in a range of 10-20
My_list = [*range(10, 21, 1)]
output:
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
As we can see in the output, the argument-unpacking operator has successfully
unpacked the result of the range function.
s 15
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
List methods (append, clear, copy, count, index, insert, pop, remove,
reverse, sort).
1. Adding elements to the list
Python provides append() function which is used to add an element to the list. However,
the append() function can only add value to the end of the list.
The syntax of the append() method is:
list.append(item)
append() Parameters
The method takes a single argument
item - an item to be added at the end of the list
The item can be numbers, strings, dictionaries, another list, and so on.
s 16
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
3. Python List copy()
The copy() method returns a shallow copy of the list.
A list can be copied using the = operator. For example,
old_list = [1, 2, 3]
new_list = old_list
The problem with copying lists in this way is that if you modify new_list, old_list is also
modified. It is because the new list is referencing or pointing to the same old_list object.
old_list = [1, 2, 3]
new_list = old_list
copy() parameters
The copy() method doesn't take any parameters.
# copying a list
new_list = my_list.copy()
count() Parameters
The count() method takes a single argument:
element - the element to be counted
s 17
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
# print count
print('The count of i is:', count)
# count element 'p'
count = vowels.count('p')
# print count
print('The count of p is:', count)
Output:
The count of i is: 2
The count of p is: 0
s 18
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
insert() Parameters
The insert() method takes two parameters:
index - the index where the element needs to be inserted
element - this is the element to be inserted in the list
Notes:
If index is 0, the element is inserted at the beginning of the list.
If index is 3, the element is inserted after the 3rd element. Its position will be 4th.
pop() parameters
The pop() method takes a single argument (index).
The argument passed to the method is optional. If not passed, the default index -1 is
passed as an argument (index of the last item).
If the index passed to the method is not in range, it throws IndexError: pop index out of
range exception.
s 19
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
remove() Parameters
The remove() method takes a single element as an argument and removes it from the
list.
If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception.
Return Value from remove()
The remove() doesn't return any value (returns None).
Example 1: Remove element from the list
animals = ['cat', 'dog', 'rabbit', 'guinea pig'] # animals list
animals.remove('rabbit') # 'rabbit' is removed
print('Updated animals list: ', animals) # Updated animals List
Output:
Updated animals list: ['cat', 'dog', 'guinea pig']
Example 2: Deleting element that doesn't exist
animals = ['cat', 'dog', 'rabbit', 'guinea pig'] # animals list
animals.remove('fish') # Deleting 'fish' element
print('Updated animals list: ', animals) # Updated animals List
Output:
Traceback (most recent call last):
File "....... ", line 5, in <module>
animal.remove('fish')
ValueError: list.remove(x): x not in list
Here, we are getting an error because the animals list doesn't contain 'fish'.
NOTE:
If you need to delete elements based on the index (like the fourth element), you can
use the pop() method.
Also, you can use the Python del statement to remove items from the list.
Example 3: Consider the following example to understand this concept.
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
OUTPUT:
printing original list:
01234
printing the list after the removal of first element...
0134
s 20
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
Note: The simplest difference between sort() and sorted() is: sort() changes the list
directly and doesn't return any value, while sorted() doesn't change the list and returns
the sorted list.
sort() Parameters
By default, sort() doesn't require any extra parameters. However, it has two optional
parameters:
1. reverse - If True, the sorted list is reversed (or sorted in Descending order)
2. key - function that serves as a key for the sort comparison
Output:
Sorted list: ['a', 'e', 'i', 'o', 'u']
s 21
A.Y-2020-2021
FYBCA-SEM2-204 - Programming Skills
11. Python List extend()
The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the
end of the list.
The syntax of the extend() method is:
list1.extend(iterable)
Here, all the elements of iterable are added to the end of list1.
extend() Parameters
As mentioned, the extend() method takes an iterable such as list, tuple, string etc.
Return Value from extend()
The extend() method modifies the original list. It doesn't return any value.
s 22
UNIT-5: Numpy and Pandas
5.2 Introduction to Numpy and Pandas :
5.2.1 Overview of numpy
5.2.1.1 Numpy methods (Mean, Median, Mode, Standard Deviation and Variance)
5.2.1.2 Implementation of Numpy methods on numeric dataset created
using list.
5.2.2 Pandas Dataframe:
5.2.2.1 Creating dataframe using list
5.2.2.2 Creating dataframe using dict of equal length list
5.2.2.3 Reading data using csv file (read_csv())
5.2.2.4 Retrieving rows and columns from dataframe using index
5.2.2.5 Retrieving rows and columns using loc and iloc functions.
NumPy
NumPy stands for numeric python which is a python package for the computation and processing of
the multidimensional and single dimensional array elements.
Travis Oliphant created NumPy package in 2005 by adding the features of one module Numeric into
another module Numarray.
It is an extension module of Python which is mostly written in C. It provides various functions which
are capable of performing the numeric computations with a high speed.
NumPy provides various powerful data structures, implementing multi-dimensional arrays and
matrices. These data structures are used for the optimal computations regarding arrays and matrices.
NumPy provides a convenient and efficient way to handle the vast amount of data. NumPy is also very
convenient with Matrix multiplication and data reshaping. NumPy is fast which makes it reasonable to
work with a large set of data.
There are the following advantages of using NumPy for data analysis.
4. It is capable of performing Fourier Transform and reshaping the data stored in multidimensional
arrays.
5. NumPy provides the in-built functions for linear algebra and random number generation.
Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as the replacement to MATLAB
as Python is more complete and easier programming language than MATLAB
Numpy array and List
In Python we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50 times faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that make working
with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very important.
We can initialize numpy arrays from nested Python lists, and access elements using square brackets:
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
Check Number of Dimensions
NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions
the array have.
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Higher Dimensional Arrays
When the array is created, you can define the number of dimensions by using the ndmin argument.
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)
In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element that is the
vector, the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim has 1 element that is
3D array and 1st dim has 1 element that is a 4D array.
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers.
The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving
the size of the array along each dimension.
import numpy as np
a = np.array([1, 2, 3]) # Create a rank 1 array
print(type(a)) # Prints "<class 'numpy.ndarray'>"
print(a.shape) # Prints "(3,)"
print(a[0], a[1], a[2]) # Prints "1 2 3"
a[0] = 5 # Change an element of the array
print(a) # Prints "[5, 2, 3]"
b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
print(b.shape) # Prints "(2, 3)"
print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4"
import numpy as np
a = np.zeros((2,2)) # Create an array of all zeros
print(a) # Prints "[[ 0. 0.][ 0. 0.]]"
b = np.ones((1,2)) # Create an array of all ones
print(b) # Prints "[[ 1. 1.]]"
c = np.full((2,2), 7) # Create a constant array
print(c) # Prints "[[ 7. 7.][ 7. 7.]]"
d = np.eye(2) # Create a 2x2 identity matrix
print(d) # Prints "[[ 1. 0.][ 0. 1.]]"
e = np.random.random((2,2)) # Create an array filled with randomvalues
print(e)
Array indexing
Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you
must specify a slice for each dimension of the array:
import numpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
b = a[:2, 1:3]
# A slice of an array is a view into the same data, so modifying it
# will modify the original array.
print(a[0, 1]) # Prints "2"
b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]
print(a[0, 1]) # Prints "77"
Integer array indexing:
When you index into numpy arrays using slicing, the resulting array view will always be a subarray of
the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the
data from another array. Here is an example:
import numpy as np
a = np.array([[1,2], [3, 4], [5, 6]])
print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"
print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # Prints "[1 4 5]"
print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
print(np.array([a[0, 1], a[0, 1]])) # Prints "[2 2]"
Datatypes
Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric
datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an
array, but functions that construct arrays usually also include an optional argument to explicitly specify
the datatype. Here is an example:
import numpy as np
x = np.array([1, 2]) # Let numpy choose the datatype
print(x.dtype) # Prints "int64"
x = np.array([1.0, 2.0]) # Let numpy choose the datatype
print(x.dtype) # Prints "float64"
x = np.array([1, 2], dtype=np.int64) # Force a particular datatype
print(x.dtype) # Prints "int64"
Array math
Basic mathematical functions operate elementwise on arrays, and are available both as operator
overloads and as functions in the numpy module:
import numpy as np
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
print(x + y)
print(np.add(x, y))
print(x - y)
print(np.subtract(x, y))
print(x * y)
print(np.multiply(x, y))
print(x / y)
print(np.divide(x, y))
print(np.sqrt(x))
Numpy provides many useful functions for performing computations on arrays; one of the most useful
is sum :
import numpyas np
x =np.array([[1,2],[3,4]])
12
34
print(np.sum(x)) # Compute sum of all elements; prints "10"
print(np.sum(x, axis=0)) # Compute sum of each column; prints "[4 6]"
print(np.sum(x, axis=1)) # Compute sum of each row; prints "[3 7]"
numpy.median
Objective:
o Compute the median along the specified axis.
o Returns the median of the array elements.
Syntax:
numpy.median(a, axis=None, out=None, overwrite_input=False, keepdims=False)[source]
keepdims – It is a boolean and optional. It enables to make the dimensions of the output the same as the input.
We can set keepdims = True to make the dimensions of the output the same as the dimensions of the input.
By default it is set to keepdims = False, meaning that the output of np.array will not necessarily have the same
dimensions as the input.
Returns:
median :ndarray
It returns an array holding the result. If the input contains integers or floats smaller than float64, then
the output data-type is np.float64.
Otherwise, the data-type of the output is the same as that of the input.
If out is specified, that array is returned instead.
Examples
import numpy as np
a = np.array([[10, 7, 4], [3, 2, 1]])
print("The array is",a)
print("The median is ",np.median(a))
print("The medain with axis 0(Row-wise)",np.median(a, axis=0))
print("The medain with axis 1(Col-wise)",np.median(a, axis=1))
m = np.median(a, axis=0)
print(m)
out = np.zeros_like(m)
print("The medainwith out is",np.median(a, axis=0, out=m))
b=a.copy()
print("The median with axis=1",np.median(b, axis=1, overwrite_input=True))
assert not np.all(a==b)
b = a.copy()
print("The median with axis=None",np.median(b, axis=None, overwrite_input=True))
assert not np.all(a==b)
numpy.mean
Objective:
Syntax:
Parameters:
a : Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
Axis: None or int or tuple of ints,( optional) : Axis or axes along which the means are computed. The default
is None, means to compute the mean of the flattened array.
Dtype data-type, (optional) : Type to use in computing the mean. For integer inputs, the default is float64; for
floating point inputs, it is the same as the input dtype.
Out ndarray, (optional) : Alternate output array in which to place the result. The default is None; if provided, it
must have the same shape as the expected output, but the type will be cast if necessary. See Output type
determination for more details.
Keepdims bool, (optional) : It is a boolean and optional. It enables to make the dimensions of the output the
same as the input. We can set keepdims = True to make the dimensions of the output the same as the
dimensions of the input.
By default it is set to keepdims = False, meaning that the output of np.array will not necessarily have the same
dimensions as the input.
wherearray_like of bool, optional
Elements to include in the mean
Returns:
mndarray
If out=None, returns a new array containing the mean values, otherwise a reference to the
output array is returned.
Notes
The arithmetic mean is the sum of the elements along the axis divided by the number of
elements.
Note that for floating-point input, the mean is computed using the same precision the input
has. Depending on the input data, this can cause the results to be inaccurate, especially
for float32 (see example below). Specifying a higher-precision accumulator using
the dtype keyword can alleviate this issue.
By default, float16 results are computed using float32 intermediates for extra precision.
Examples
a =np.array([[1,2],[3,4]])
np.mean(a) #output : 2.5
np.mean(a, axis=0) #output: array([2., 3.])
np.mean(a, axis=1) # output: array([1.5, 3.5])
a =np.zeros((2,512*512),dtype=np.float32)
a[0,:]=1.0
a[1,:]=0.1
np.mean(a)
O/p:
0.54999924
np.mean(a,dtype=np.float64)
0.55000000074505806 # may vary
Specifying a where argument:
import numpy as np
a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
np.mean(a)
np.mean(a, where=[[False], [False], [True]])
numpy.std
Objective:
Syntax:
Parameters:
a array_like: Calculate the standard deviation of these values.
axis: None or int or tuple of ints, optional : Axis or axes along which the standard deviation is computed. The
default is to compute the standard deviation of the flattened array.
dtype: dtype, optional: Type to use in computing the standard deviation. For arrays of integer type the default
is float64, for arrays of float types it is the same as the array type.
out: ndarray, optional: Alternative output array in which to place the result. It must have the same shape as the
expected output but the type (of the calculated values) will be cast if necessary.
ddof : int, optional : Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements. By default ddof is zero.
keepdims: bool, optional: It is a boolean and optional. It enables to make the dimensions of the output the same
as the input. We can set keepdims = True to make the dimensions of the output the same as the dimensions of
the input.
By default it is set to keepdims = False, meaning that the output of np.array will not necessarily have the same
dimensions as the input.
where: array_like of bool, optional: Elements to include in the standard deviation.
Returns:
standard_deviationndarray, see dtype parameter above.
If out is None, return a new array containing the standard deviation, otherwise return a reference to
the output array.
Notes
The standard deviation is the square root of the average of the squared deviations from the
mean, i.e., std = sqrt(mean(x)), where x = abs(a - a.mean())**2.
Examples
a =np.array([[1,2],[3,4]])
np.std(a) # Output: 1.1180339887498949 # may vary
np.std(a, axis=0) # Ouput: array([1., 1.])
np.std(a, axis=1) # Output: array([0.5, 0.5])
a =np.zeros((2,512*512),dtype=np.float32)
a[0,:]=1.0
a[1,:]=0.1
np.std(a) # Output: 0.45000005
a =np.array([[14,8,11,10],[7,9,10,11],[10,15,5,10]])
np.std(a) #Output: 2.614064523559687 # may vary
np.std(a, where=[[True],[True],[False]]) #Output: 2.0
numpy.var
Objective:
o Compute the variance along the specified axis.
o Returns the variance of the array elements, a measure of the spread of a distribution.
The variance is computed for the flattened array by default, otherwise over the specified
axis.
Syntax:
numpy.var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no valu
e>)
Parameters:
a :array_like: Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.
axis : None or int or tuple of ints, optional: Axis or axes along which the variance is computed. The default is to
compute the variance of the flattened array. If this is a tuple of ints, a variance is performed over multiple axes,
instead of a single axis or all the axes as before.
dtype: data-type, optional: Type to use in computing the variance. For arrays of integer type the default
is float64; for arrays of float types it is the same as the array type.
out : ndarray, optional : Alternate output array in which to place the result. It must have the same shape as the
expected output, but the type is cast if necessary.
ddof : int, optional : “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof,
where N represents the number of elements. By default ddof is zero.
keepdims : bool, optional: It is a boolean and optional. It enables to make the dimensions of the output the
same as the input. We can set keepdims = True to make the dimensions of the output the same as the
dimensions of the input.
By default it is set to keepdims = False, meaning that the output of np.array will not necessarily have the same
dimensions as the input.
where : array_like of bool, optional : Elements to include in the variance.
Returns:
variance ndarray
If out=None, returns a new array containing the variance; otherwise, a reference to the output array is
returned.
Notes
The variance is the average of the squared deviations from the mean, i.e., var = mean(x),
where x = abs(a - a.mean())**2.
The mean is typically calculated as x.sum() / N, where N = len(x). If, however, ddof is specified,
the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an
unbiased estimator of the variance of a hypothetical infinite population. ddof=0 provides a
maximum likelihood estimate of the variance for normally distributed variables.
Examples
a =np.array([[1,2],[3,4]])
np.var(a) # Output: 1.25
np.var(a, axis=0) #Output :array([1., 1.])
np.var(a, axis=1) # Output : array([0.25, 0.25])
a =np.array([[14,8,11,10],[7,9,10,11],[10,15,5,10]])
np.var(a) #Output: 6.833333333333333 # may vary
np.var(a, where=[[True],[True],[False]]) #Output: 4.0
Mode:
Mode refers to the most repeating element in the array. We can find the mode from the NumPy array
by using the following methods.
Method 1:
Using scipy.stats package
Let us see the syntax of the mode() function
Syntax :
variable = stats.mode(array_variable)
Note : To apply mode we need to create an array. In python, we can create an array using numpy
package. So first we need to create an array using numpy package and apply mode() function on that
array. Let us see examples for better understanding.
Example 1:
ModeResult(mode=array([2]), count=array([3]))
Example 2:
Like NumPy module, the statistics module also contains statistical functions like mean , median ,
mode….etc . So let us see an example of a mode using the statistics module.
Example :
import statistics as st
import numpy as np
# create an 1 d array
arr1 = np.array([9, 8, 7, 6, 6, 6, 6, 5, 5, 4,
3, 2, 1, 1, 1, 1, 1, 1])
The most common way to create a Dataframe in Pandas is by loading the datasets from existing storage; storage
can be SQL Database, CSV file, and Excel file. Pandas DataFrame can be created from the lists, dictionary, and
from a list of dictionary etc. Dataframe can be created in different ways here are some ways by which we create
a dataframe:
• To create DataFrame from dict of narray/list, all the narray must be of same length.
• If index is passed then the length index should be equal to the length of arrays.
• If no index is passed, then by default, index will be range(n) where n is the array length.
Create pandas dataframe from lists using dictionary:
• Creating pandas data-frame from lists using dictionary can be achieved in different ways.
• We can create pandas dataframe from lists using dictionary using pandas DataFrame.
• With this method in Pandas we can transform a dictionary of list to a dataframe.
Parameters:
filepath_or_buffer: It is the location of the file which is to be retrieved using this function. It accepts any string
path or URL of the file.
sep: It stands for separator, default is ‘, ‘ as in CSV(comma separated values).
header: It accepts int, a list of int, row numbers to use as the column names, and the start of the data. If no
names are passed, i.e., header=None, then, it will display the first column as 0, the second as 1, and so on.
usecols: It is used to retrieve only selected columns from the CSV file.
nrows: It means a number of rows to be displayed from the dataset.
index_col: If None, there are no index numbers displayed along with records.
skiprows: Skips passed rows in the new data frame.
Read CSV File using Pandas read_csv
Before using this function, we must import the Pandas library, we will load the CSV file using Pandas.
In this example, we will manipulate our existing CSV file and then add some special characters to see
how the sep parameter works.
Without sep parameter:
Here, we are specifying only 2 columns,i.e.[“name”, “class”] to load and we use the header 0 as its
default header.
Using index_col in read_csv()
• This is to allow you to set which columns to be used as the index of the dataframe.
• The default value is None, and pandas will add a new column start from 0 to specify the index
column.
• It can be set as a column name or column index, which will be used as the index column.
Row Selection:
• Pandas provide a unique method to retrieve rows from a Data frame.
• DataFrame.loc [] method is used to retrieve rows from Pandas DataFrame.
• Rows can also be selected by passing integer location to an iloc[] function.
Indexing and Selecting Data
• Indexing in pandas means simply selecting particular rows and columns of data from a DataFrame.
• Indexing could mean selecting all the rows and some of the columns, some of the rows and all of the
columns, or some of each of the rows and columns.
• Indexing can also be known as Subset Selection.
Indexing a Dataframe using indexing operator [] :
• Indexing operator is used to refer to the square brackets following an object. The .loc and .iloc indexers
also use the indexing operator to make selections.
• In this indexing operator to refer to df[].
In order to select a single column, we simply put the name of the column in-between the brackets
• This function selects data by the label of the rows and columns.
• The df.loc indexer selects data in a different way than just the indexing operator.
• It can select subsets of rows or columns.
• It can also simultaneously select subsets of rows and columns.
• loc() can accept the boolean data
• Many operations can be performed using the loc() method like;
Selecting data according to some conditions
In order to select a single row using .loc[], we put a single row label in a .loc function.
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("D:\demo.csv", index_col ="Name")
# retrieving row by loc method
first = data.loc["Sheetal"]
second = data.loc["Arpita"]
print(first, "\n\n\n", second)
Output:
As shown in the output image, two series were returned since there was only one parameter both of the times.
• The iloc() function is an indexed-based selecting method which means that we have to pass an integer
index in the method to select a specific row/column.
• This function allows us to retrieve rows and columns by position.
• This method does not include the last element of the range passed in it unlike loc().
• In order to do that, we’ll need to specify the positions of the rows that we want, and the positions of the
columns that we want as well.
• The df.iloc indexer is very similar to df.loc but only uses integer locations to make its selections.
In order to select a single row using .iloc[], we can pass a single integer to .iloc[] function.
Selecting rows using integer indices