0% found this document useful (0 votes)
5 views93 pages

Computer Programing

The document provides an overview of computer programming, focusing on the C programming language and its various types, including low-level, middle-level, and high-level languages. It discusses programming concepts such as variables, data types, and tokens, as well as the applications of C in software development. Additionally, it includes examples of C code and explains the significance of programming in various fields like agriculture, education, and business.

Uploaded by

info.gajagame
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views93 pages

Computer Programing

The document provides an overview of computer programming, focusing on the C programming language and its various types, including low-level, middle-level, and high-level languages. It discusses programming concepts such as variables, data types, and tokens, as well as the applications of C in software development. Additionally, it includes examples of C code and explains the significance of programming in various fields like agriculture, education, and business.

Uploaded by

info.gajagame
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Subject Title: COMPUTER PROGRAMMING

Subject Code: CP36401T


═══════════════════════════════════════════════════════

1.0 Programming in C
2.0 Introduction to Python Programming

NOTES:

3
1.1. Introduction to Computer programming
Computer programming is the process of designing and developing various computer
programs to complete specific tasks in either application or software or within the computers. The
process constitutes many tasks, like analyzing the problem, generating an algorithm to solve it, and
then examining the output generated. Computer programming is creating a series of programs to
resolve a problem in a computer.

1.2. Introduction to C programming language

The whole procedure of writing computer programs is called Computing Programming. The
programming also has another name called "coding" and the person who writes the code is referred
as the "Programmer" or "Coder". Programming is inputting instructions to the computer or machines
that describe how to carry out a task. Programmers use various programming languages to code the
different parts of the system, like software, hardware, and applications in computers and digital
devices, which helps us use them for many tasks. There are various programming languages to write
programs which include: C, C++, Java, Python, Javascript, PHP,Ruby, R, etc.

Types of Programming Languages :

Low-Level Programming Languages

Low-level programming languages again consists of machine-level languages and assembly-


level languages.

• Machine Language - Machine language comes under the category of low-level


programming language that is built up of 0's and 1's. Some high-level languages are
compiled into machine-level languages, so the computer understands the code.
• Assembly Language - Assembly language also comes under the category of low-level
programming language that is compiled by an assembler. Translation of human-written code
is converted into machine code by these assemblers only.

Middle-Level Programming Languages

Middle-level programming languages are the programming languages that have


characteristics of both low-level and high-level languages.

C Language - The c programming language acts as a mediator between hardware and


programming layer. C is easy to understand and flexible. It is a compiled language and does not use
objects and classes. Compilers and editors use C to design their applications.

High-Level Programming Languages


• Procedural Languages - Procedural languages are also programming languages in which the
written code will pass through many procedures, and the computer executes the program.
The language helps to track errors easily and allows code reusability.

NOTES:

4
It evolved from structured programming languages, and the programs are broken up
into functions or routines here.
Examples of procedural languages are FORTRAN, COBOL, SQL, and GO.
• Object-Oriented languages - The object-oriented programming languages which use objects
and classes to write code. The usage of objects and classes makes it to solve real-world
problems. The main advantage of object-oriented languages is they are simple to use and
faster in execution. They follow a bottom-up approach and hence callow to change the code
easily. The most well-known object-oriented programming languages are Java, R, Ruby,
Python, C#, JavaScript and Perl.

Declarative Languages

A declarative language is a programming language where the programmers concentrate on


the goal or result of the program. They need to pay attention to achieve a goal. These languages
check the relationship among the statements and use deduction, induction, and abduction to give the
output. An example for a declarative language is "PROLOG," which is similar to SQL(Structured
Query Language) and works by evaluating logical statements.

Scripting Languages

Scripting languages are the programming languages in which the code is interpreted(program
executes without converting into machine language ) without compilation. Interpretation means the
very line of code is read and executed. Still, in complied languages, the code is first translated into a
low-level code called machine code, then executed to give the program's output. Scripting languages
are used for smaller tasks like file manipulation and designing operating system utilities. Examples
of Scripting languages are Pearl, PHP, and JavaScript.

Display Languages

Display languages are the languages that are used for displaying content on web pages. The
mostly used display languages are HTML, XML, and PHP.

• HTML is a Hypertext Markup Language used for designing websites and web pages. Tim
Berners-Lee developed it. It consists of anchor tags to place URLs of other sites so that we
can redirect to other pages.
• XML - It is Extensible Markup Language used for transporting data between different web
pages. In XML, there are no predefined tags, and users can define their tags and every tag
opened should be closed.
• PHP - Hypertext Preprocessor is a server-side scripting language for designing dynamic web
pages. PHP is open-source which can be used by anyone by simply installing the console to
write programs. We can combine the code written in HTML, CSS, and JavaScript by using
PHP.

NOTES:

5
Document Formatting Languages

Document Formatting Languages are the programming languages that help manage the
printed text and graphics of a particular page in a document. The language may come under various
groups like text formatting, page description language, or markup language. Examples of Document
Formatting Languages are TeX, PostScript, and SGML.

Functional Languages

Functional languages are programming languages in which the bigger functions are divided
into smaller functions to solve complex problems. Examples of functional languages are Java and
Haskell.

Computer Programming and its uses

Computer programs solve many problems and create something innovative in various fields
like agriculture, education, entertainment, etc.

• Graphics are used in developing cartoons and adding realistic effects to movies
using programming languages.
• Computers are used to build various techniques in medical tests to detect diseases
using artificial intelligence and deep learning techniques.
• Used to develop mobile and android applications.
• Used Word and Excel to accomplish tasks with efficiency.
• Computer programming is also useful in business and marketing, where people
in business use applications and tools to interact with customers.
• Programming helps to carry out government functions where people can access
services more effectively, designing news portals to provide information about
the government's tasks and building websites to provide government services
online.
• Programming helps in every point of our lives, from using smartphones to
watching movies online. Everything is possible because of coding itself.

Writing the word “How are you” using a C Program :

#include <stdio.h>
int main() {
/* your first programming in C language */
printf(“How are you \n”);
return 0;
}
Output :
your first programming in C language

NOTES:

6
Application of C programming in Development:

• Language Compilers
• Operating Systems
• Text Editors
• Assemblers
• Network Drivers
• Print Spoolers
• Modern Programs
• Language Interpreters
• Databases
• Utilities

The C language is imperative, procedural, and general-purpose in nature, developed by


Dennis M. Ritchie in 1972 at the Bell Telephone for developing the UNIX OS. As of now, the C
language is one of the most widely used computer languages along with Java, which is mostly used
among modern programmers.
• Prerequisites of using the C Language
Before we proceed ahead with the understanding and learning of the C language, we
must have a basic grasp of the terminologies of computer programming. If we understand the
basics of any computer programming language, then we will be able to effectively understand
the C language.
• Variables in C
Variable is basically nothing but the name of a memory location that we use for
storing data. We can change the value of a variable in C or any other language, and we can
also reuse it multiple times. We use symbols in variables for representing the memory
location- so that it becomes easily identifiable by any user.
• Use of the Variables in C
Variables are the storage areas in a code that the program can easily manipulate.
Every variable in C language has some specific type- that determines the layout and the size
of the memory of the variable, the range of values that the memory can hold, and the set of
operations that one can perform on that variable.
The name of a variable can be a composition of digits, letters, and also underscore characters.
The name of the character must begin with either an underscore or a letter. In the case of C,
the lowercase and uppercase letters are distinct. It is because C is case-sensitive in nature.
Let us look at some more ways in which we name a variable.
• Rules for Naming a Variable in C
We give a variable a meaningful name when we create it. Here are the rules that we
must follow when naming it:
1. The name of the variable must not begin with a digit.
2. A variable name can consist of digits, alphabets, and even special symbols such as an
underscore ( _ ).
3. A variable name must not have any keywords, for instance, float, int, etc.
4. There must be no spaces or blanks in the variable name.
5. The C language treats lowercase and uppercase very differently, as it is case sensitive.
Usually, we keep the name of the variable in the lower case.

NOTES:

7
Example of Variable:

int var1;

int my_var1;

• Data type of the Variable:

Data type define the type of data that we can store in any variable. If we do not provide
the variable with a data type, the C compiler will ultimately generate a syntax error or a
compile-time error.
The data Types present in the C language are float, int, double, char, long int, short
int, etc., along with other modifiers.

Type of Name Description Uses


Variable
char Character It is a type of integer. It is We use them in the form of single
typically one byte (single alphabets, such as X, r, B, f, k, etc., or for
octet). the ASCII character sets.
Int Integer It is the most natural size ofWe use this for storing the whole
an integer used in the numbers, such as 4, 300, 8000, etc.
machine.
float Floating- It is a floating-point value We use these for indicating the real
Point that is single precision. number values or decimal points, such as
20.8, 18.56, etc.
double Double It is a floating-point value These are very large-sized numeric values
that is double precision. that aren’t really allowed in any data type
that is a floating-point or an integer.
Void Void It represents that there is anWe use it to represent the absence of
absence of type. value. Thus, the use of this data type is to
define various functions.

Examples :

// int type variable in C


int marks = 45;
// char type variable in C
char status = ‘G’;
// double type variable in C
double long = 28.338612;
// float type variable in C
float percentage = 82.5;
Once a user defines a given variable with any data type, then they will not be able to change
the data type of that given variable in any case.
int p, q, r; defines as well as declares the variables p, q, and r. It instructs the compiler to
create three variables named p, q, and r of the type int

NOTES:

8
Classification of Variables in C
The variables can be of the following basic types, based on the name and the type of the variable:
• Global Variable: A variable that gets declared outside a block or a function is known as a
global variable. Any function in a program is capable of changing the value of a global
variable. It means that the global variable will be available to all the functions in the code.
Because the global variable in c is available to all the functions, we have to declare it at the
beginning of a block..
Example,
int value=30; // a global variable
void function1(){
int a=20; // a local variable
}
• Local Variable: A local variable is a type of variable that we declare inside a block or a
function, unlike the global variable. Thus, we also have to declare a local variable in c at
the beginning of a given block.
Example,
void function1(){
int x=10; // a local variable
}
A user also has to initialize this local variable in a code before we use it in the program.
• Automatic Variable: Every variable that gets declared inside a block (in the C language)
is by default automatic in nature. One can declare any given automatic variable explicitly
using the keyword auto.
Example,
void main(){
int a=80; // a local variable (it is also automatic variable)
auto int b=50; // an automatic variable
}
• Static Variable: The static variable in c is a variable that a user declares using
the static keyword. This variable retains the given value between various function calls.
Example, void function1(){
int a=10; // A local variable
static int b=10; // A static variable
a=a+1;
b=b+1;
printf(“%d,%d”,a,b);
}
If we call this given function multiple times, then the local variable will print this very same
value for every function call. For example, 11, 11, 11, and so on after this. The static variable,
on the other hand, will print the value that is incremented in each and every function call. For
example, 11, 12, 13, and so on.
• External Variable: A user will be capable of sharing a variable in multiple numbers of
source files in C if they use an external variable. If we want to declare an external variable,
then we need to use the keyword extern.
Syntax, extern int a=10;// external variable (also a global variable)

NOTES:

9
An escape sequence is a sequence of characters used in formatting the output and are
not displayed while printing text on to the screen, each having its own specific function.
All the escape sequences in C are represented by 2 or more characters, one
compulsorily being backslash (\) and the other any character present in the C character set.
Here is a table which illustrates the use of escape sequences in C:
1. \n (New line) – We use it to shift the cursor control to the new line
2. \t (Horizontal tab) – We use it to shift the cursor to a couple of spaces to the right in
the same line.
3. \a (Audible bell) – A beep is generated indicating the execution of the program to
alert the user.
4. \r (Carriage Return) – We use it to position the cursor to the beginning of the current
line.
5. \\ (Backslash) – We use it to display the backslash character.
6. \’ (Apostrophe or single quotation mark) – We use it to display the single-quotation
mark.
7. \” (Double quotation mark)- We use it to display the double-quotation mark.
8. \0 (Null character) – We use it to represent the termination of the string.
9. \? (Question mark) – We use it to display the question mark. (?)
10. \nnn (Octal number)- We use it to represent an octal number.
11. \xhh (Hexadecimal number) – We use it to represent a hexadecimal number.
12. \v (Vertical tab)
13. \b (Backspace)
14. \e (Escape character)
15. \f (Form Feed page break)

Tokens in C language are the smallest possible unit of a program, that conveys a specific
meaning to the compiler. It is the building blocks of a programming language.

Different Types of Tokens in C

1. Keywords in C
2. Identifiers in C
3. Strings in C
4. Operators in C
5. Constant in C
6. Special Characters in C
1. Keywords in C

Keywords in C language are the pre-defined & reserved words, each having its own
significance and hence has a specific function associated with it. We can’t simply use keywords for
assigning variable names, as it would connote a totally different meaning altogether and would be
erroneous. There are a total of 32 keywords offered in C.

NOTES:

10
Auto break case
Continue do default
Double else enum
For if goto
Int long register
Signed static sizeof
Struct switch typedef
Void while volatile
Key takeaway: All the keywords in C are lowercase in nature.
Apart from the above-listed keywords, there are certain supplementary words that cannot be
used as variable names. They are listed in alphabetical order as follows:
1. asm
2. bool
3. catch
4. class
5. const_cast
6. delete
7. dynamic_cast
8. explicit
9. export
10. false
11. friend
12. inline
13. mutable
14. namespace
15. new
16. operator
17. private
18. protected
19. public
20. reinterpret_cast
21. static_cast
22. template
23. this
24. throw
25. true
26. try
27. typeid
28. typename
29. using
30. virtual
31. wchar_t

NOTES:

11
2. Identifiers in C

The C programmer has the provision to give names of his own choice to variables, arrays,
and functions. These are called identifiers in C. The user may use the combination of different
character sets available in the C language to name an identifier but, there are certain rules to be
abided by the user on his part when naming identifiers.

Rules for Identifiers in C –


1. First character: The first character of the identifier should necessarily begin with
either an alphabet or an underscore. It cannot begin with a digit.
2. No special characters: C does not support the use of special characters while naming
an identifier. For instance, special characters like comma or punctuation marks can’t
be used.
3. No keywords: The use of keywords as identifiers is strictly prohibited, as they are
reserved words which we have already discussed.
4. No white space: White spaces include blank spaces, newline, carriage return, and
horizontal tab, which can’t be used.
5. Word limit: The identifier name can have an arbitrarily long sequence that should not
exceed 31 characters, otherwise, it would be insignificant.
6. Case sensitive: Uppercase and lowercase characters are treated differently.

3. Constants in C

Often referred to as literals, constants, as the name itself suggests, are fixed values i.e. they
cannot change their value during program run once they are defined.

Syntax of Constant in C Programming-


const data_type variable_name = value;
Various Types of Constants in C Language-

1. Integer constants: These are of the integer data type. For example, const int value =
400;
2. Floating constants: These are of the float data type. For example, const float pi =
3.14;
3. Character constants: These are of the character data type. For example, const char
gender = ‘f’;
4. String constants: These are also of the character data type, but differ in the
declaration. For example, const char name[] = ‘‘DataFlair’’;
5. Octal constants: The number system which consists only 8 digits, from 0 to 7 is
called the octal number system. The constant octal values can be declared as, const int
oct = 040; (It is the octal equivalent of the digit “32” in the decimal number system.)
6. Hexadecimal constants: The number system which consists of 16 digits, from 0 to 9
and alphabets ‘a’ to ‘f’ is called hexadecimal number system. The constant
hexadecimal values can be declared as, const int hex = 0x40; (It is the hexadecimal
equivalent of the digit 64 in the decimal number system.)

NOTES:

12
4. Strings in C

Just like characters, strings are used to store letters and digits. Strings in C are referred to
as an array of characters. It is enclosed within double quotes, unlike characters which are stored
within single quotes. The termination of a string is represented by the null character that is ‘\0’. The
size of a string is the number of individual characters it has.
In C, a string can be declared in the following ways:

char name[30] = ‘’DataFlair”; // The compiler reserves 30 bytes of memory

char name[] = “DataFlair”; // The compiler reserves the required amount of memory
char name[30] = { ‘D’ , ’a’ , ’t’ , ’a’ , ’F’ , ’l , ’a’ , ’i’ , ’r’ , ’\0’ }; // How a string is represented as
a set of characters.

5. Special Symbols of C
Apart from letters and digits, there are some special characters in C, which will help you to
manipulate or perform data operations. Each special symbol has a specific meaning to the C
compiler.
1. [ ] – Square brackets – The opening and closing brackets of an array indicate single
and multidimensional subscripts.
2. () – Simple brackets – Used to represent function declaration and calls, used in print
statements.
3. { } – Curly braces – Denote the start and end of a particular fragment of code which
may be functions or loops or conditional statements.
4. , – Comma – Separate more than one statements, like in the declaration of different
variable names in C.
5. # – Hash / Pound / Preprocessor – A preprocessor directive, utilize for denoting the
use of a header file.
6. * – Asterisk – To declare pointers, used as an operand for multiplication.
7. ~ – Tilde – As a destructor to free memory.
8. . – Period/dot – To access a member of a structure.
6. Operators in C
Operators in C are tools or symbols, which are used to perform a specific operation on data.
Operations are performed on operands. Operators can be classified into three broad categories,
according to the number of operands used. Which are as follows:
i. Unary: It involves the use of one a single operand. For instance, ’!’ is a unary operator which
operates on a single variable, say ‘c’ as !c which denotes its negation or complement.
ii. Binary: It involves the use of 2 operands. They are further classified as:
• Arithmetic
• Relational
• Logical
• Assignment
• Bitwise
• Conditional
iii. Ternary: It involves the use of 3 operands. For instance, ?: Is used in place of if-else
conditions.

NOTES:

13
1.3. Operators and Expressions
Operators in C :
The operators are types of symbols that inform a compiler for performing some specific
logical or mathematical functions. The operators serve as the foundations of the programming
languages. Thus, the overall functionalities of the C programming language remain incomplete if we
do not use operators. In simpler words, the operators are symbols that help users perform specific
operations and computations- both logical and mathematical on the operands. Thus, the operators
operate on the available operands in a program.

Use of Operators in C
The operators basically serve as symbols that operate on any value or variable. We use it for
performing various operations- such as logical, arithmetic, relational, and many more. A programmer
must use various operators for performing certain types of mathematical operations. Thus, the
primary purpose of the operators is to perform various logical and mathematical calculations.
The programming languages like C come with some built-in functions that are rich in nature. The
use of these operators is vast. These operators act as very powerful and useful features of all the
programming languages, and the functionality of these languages is pretty much useless without
these. These make it very easy for programmers to write the code very easily and efficiently.

Types of Operators in C
Various types of operators are available in the C language that helps a programmer in
performing different types of operations. We can handle different operations in a program using
these types of operators:
• Relational Operators
• Arithmetic Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Misc Operators

Relational Operator : We use the relational operators in c when we would like to compare the
values available for two given operands. Here is a table that states all the relational operators
available in the C language, along with their individual functions.

Function of Operator Operator Example


To check if two operands are equal to each other. == 5 == 3 would return to
0
and 4 == 4 would
return to 1
To check if two operands are unequal to each other. != 8 != 5 would return to
1
6 != 6 would return to
0

NOTES:

14
To check if the operand value on the left is comparatively > 5 > 8 would return to
greater than that of the operand value on the right. 0
9 > 7 would return to
1
To check if the operand value on the left is comparatively < 2 < 0 would return to
smaller than that of the operand value on the right. 0
4 < 8 would return to
1
To check if the operand value on the left is equal to or >= 1 >= 5 would return to
comparatively greater than that of the operand value on the be 0
right. 4 >= 2 would return to
be 1
9 >= 9 would return to
be 1
To check if the operand value on the left is equal to or <= 3 <= 6 would return to
comparatively smaller than that of the operand value on the be 1
right. 7 <= 3 would return to
be 0
2 <= 2 would return to
be 1
Note – Here, we get 1 as output when the condition is true, and 0 as output when the condition is
false.
Arithmetic Operators
The arithmetic operators in C language help a user perform the mathematical operations as
well as the arithmetic operations in a program, such as subtraction (-), addition (+), division (/),
multiplication (*), the remainder of division (%), decrement (–), increment (++).
The arithmetic operators are of two major types:
• Binary Operators – It works using two of the operators, such as -, +, /, *.
• Unary Operators In C – It works by making use of just a single operand (value),
such as — and ++.
• Also, Explore Ternary Operator in C.
Binary Operators
Here is a table that states all the binary arithmetic operators available in the C language,
along with their individual functions. If P = 50 and Q = 25, then:

Function of Operator Operator Example


To subtract the value of the second operator from the first one. – P – Q = 25
To add the value of the second operator with the first one. + P + Q = 75
To divide the value of the numerator with the value of the / P/Q=2
denominator.
To multiply the value of the second operator with the first one. * P * Q = 1250

NOTES:

15
Unary Operators

Here is a table that states all the unary arithmetic operators available in the C language,
along with their individual functions. These are increment and decrement operators. If P = 50 and
Q = 25, then:

Function of Operator Operator Example


To increase the value of the integer/ operator by 1. Decrement Operator P — = 49
and Q — = 24
To decrease the value of the integer/ operator by 1. Increment Operator P ++ = 51
and Q ++ = 26

Prefix and Postfix Increment/ Decrement Operators


The decrement operators and increment operators are of two major types:
Prefix – When we use the operator before the available variable in a program as a prefix, it is known
as a prefix operator. In a prefix increment operator, the program first adds 1 and then assigns the
resultant value to the variable. While in a prefix decrement operator, the program first subtracts 1
and then assigns the resultant value to the variable. For example, ++a and –a.

Postfix – When we use the operator after the available variable in a program as a postfix, it is known
as a postfix operator. In a postfix increment operator, the program first assigns the value to the
variable, then adds 1, and then assigns the resultant value. While in a postfix decrement operator, the
program first assigns the value to the variable, then subtracts 1, and then assigns the resultant value.
For example, a++ and a–.
Here is a table that states all the prefix and postfix unary arithmetic operators available in the
C language, along with their individual functions. These are increment and decrement operators.

Type of Operator Sample Operator Description/ Explanation


Expression
Prefix Increment ++p p increases by a value of 1, then the program uses
Operator the value of p.
Postfix Increment p++ The program uses the current value of p and
Operator increases the value of p by 1.
Prefix Decrement –p p decreases by a value of 1, then the program uses
Operator the value of p.
Postfix Decrement p– The program uses the current value of p and
Operator decreases the value of p by 1.

Logical Operators
The logical operators in c help a user determine if the results would be true or false. Here
is a table that states all the logical operators available in the C language, along with their
individual functions. If P = 1 and Q = 0, then:

NOTES:

16
Name of Operator Description of Operator Example
Operator
Logical NOT ! We use this operator for reversing the available !(P && Q) turns
logical state of the operand. In case the condition out to be true.
turns out to be true, then this operator will make the
value false.
Logical OR || The given condition turns out to be true if any of the (P || Q) turns out
operands happen to be non-zero. to be true.
Logical AND && The given condition turns out to be true if only both (P && Q) turns
the operands happen to be non-zero. out to be false.

Assignment Operators
We use the assignment operators in c for assigning any value to the given variable. Here is a
table that states all the logical operators available in the C language, along with their individual
functions.

Function of Operator Operator Example


To assign the values from the right operand to the left operand. = p=q
To add the value of the right operand with the value of the left += p += q is similar to that
operand. After that, assign the resultant value to the left one. of p = p=q
To subtract the value of the right operand from the value of the -= p -= q is similar to that
left operand. After that, assign the resultant value to the left of p = p-q
one.
To multiply the value of the right operand with the value of the *= p *= q is similar to that
left operand. After that, assign the resultant value to the left of p = p*q
one.
To divide the value of the right operand with the value of the /= p /= q is similar to that
left operand. After that, assign the resultant value to the left of p = p/q
one.
To calculate the modulus of the values of the right operand and %= p %= q is similar to
the left operand. After that, assign the resultant value to the left that of p = p%q
one.

Bitwise Operators
We use bitwise operators in c for performing the operations of bit-level on various
operands. It first converts the operators to bit-level, and after that, it performs various calculations.
The Bitwise operators basically work on the bits, and we perform bit-by-bit operations
using them. Here is the truth table for the ^, &, and | here:
a B a&b a|b a^b
1 1 1 1 0
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
If we assume that P = 60 and Q = 13 using the binary format, then it will appear as follows:

NOTES:

17
P = 0011 1100
Q = 0000 1101
—————–
P ^ Q = 0011 0001
P | Q = 0011 1101
P & Q = 0000 1100
~ P = 1100 0011
Here is a table that states all the bitwise operators available in the C language, along with
their individual functions. If we assume that the value of variable P = 60 and variable Q = 13,
then:
Name of Operator Description of Operator Example
Operator
Binary AND & This operator copies the bits to the result(P & Q) = 12,
only if they exist in both of the The binary value is
operands. 0000 1100
Binary OR | This operator copies the bits only if they (P | Q) = 61,
exist in either of the operands. The binary value is
0011 1101
Binary XOR ^ This operator copies the bits only if they (P ^ Q) = 49,
are set in one of the operands but not in The binary value is
both of them. 0011 0001
Binary One’s ~ This operator is unary. Also, it performs (~P ) = ~(60),
Complement the effect of ‘flipping’ the available bits. The binary value is
-0111101
Binary Left Shift << It shifts the value of the left operand to P << 2 = 240,
the left on the basis of the number of bitsThe binary value is
that the right operand specifies. 1111 0000
Binary Right Shift >> It shifts the value of the left operand to P >> 2 = 15,
the right on the basis of the number of The binary value is
bits that the right operand specifies. 0000 1111
Misc Operators
Apart from all the operators that we have discussed above, the C programming language
uses a few other crucial operators, that include operators, (such as ? : and sizeof). Here is a table
that states all the misc operators available in the C language, along with their individual
functions.

Description of Operator Operator Example


To return the actual size of any Size of() If z is an integer, then the size of(z) will return to
given variable. be 4.
To return the address of any given & For instance, &z; would return the actual address
variable. for any given variable.
Pointer to any variable. * *z;
Conditional Expression. ?: When the Condition is true ? then the value X :
In any other case, the value Y

NOTES:

18
Precedence of Operators in C
The precedence of the operators in C language helps in determining the preference in which
the operators must be evaluated in a program. Some operators display higher precedence as
compared to the others in the program. For instance, the precedence of the multiplication operator
here is much higher than that of the addition operator. Explore, Operator Precedence and
Associativity in C to know more.
Let us consider an example where a = 5 + 2 * 7; so here, the variable a gets assigned with the
value 19 and not 70. It is because the precedence of the multiplication operator (*) is higher than that
of the addition operator (+). Thus, the program would first multiply 2 with 7, produce 14, and then
add it with 5 to get 19 as the final result.
The table below displays the operators according to their precedence. The ones with higher
precedence appear at the very top, and the ones with lower precedence appear at the very bottom. In
any given expression, the evaluation of the operators with higher precedence occurs first.
Type of Operator Associativity Category
() [] -> . ++ – – Left to right Postfix
– + ! ~ – – ++ (type)* & sizeof Right to left The Unary Operator
/*% Left to right The Multiplicative Operator
–+ Left to right The Additive Operator
>> << Left to right The Shift Operator
< > >= <= Left to right The Relational Operator
!= == Left to right The Equality Operator
& Left to right Bitwise AND
^ Left to right Bitwise XOR
| Left to right Bitwise OR
&& Left to right Logical AND
|| Left to right Logical OR
?: Right to left Conditional
= -= += /= *= %=>>= &= <<= |= ^= Right to left Assignment
, Left to right Comma

1.4. Control Statements

C has four categories of control structures :


1. Sequential
2. Selection
3. Iteration
4. Encapsulation

1. Sequential : A sequential structure is one in which instructions are executed in


sequence. For example :
i = i + 1;
j = j + 1;

NOTES:

19
2. Selection : In the selection structure the sequence of the instruction is determined
by using the result of the condition. We can use if and switch statements for
example :
if (a > b)
i = i + 1;
else
j = j + 1;
if the condition is true then the statement i = i + 1 is executed otherwise j = j + 1
is executed.

3. Iteration : Here the statements are repeatedly executed. This structure forms
program loops. The number of iteration depends upon value of particular variables.
for ( i = 0; i<5 ; i++ )
{
j = j + 1;
}
The statement j = j + 1 is executed 5 times and the value of i changes from
0 to 1,2,3, and 4.

4. Encapsulation : in encapsulation the other component structures are included.


Example we can include an if statement in a for loop or a for loop in an if
statement.
The control statements used in the C language help a user to specify a program control’s
flow. In simpler words, the control statements help users specify the order of execution of the
instructions present in a program. These make it possible for the program to make certain decisions,
perform various tasks repeatedly, or even jump from any one section of the code to a different
section.

The C language provides support for the following set of statements in its program:

1. If Statements
2. Switch Statement
3. Conditional Operator Statement
4. Goto Statement
5. Loop Statements

1. The If Statements
This type of statement would enable a programmer to choose various instruction sets on the
basis of the available condition. The instruction sets will only get executed when the evaluation of
the condition turns out to be true. In case the evaluation of the condition is false, there will be an
execution of a different instruction set. These are also known as decision control statements. These
are of the following types:

NOTES:

20
• Simple else or Null else
• Else if ladder
• Nested if
• If… else

1.1. The If… Else Statement

When we use the if… else statement, there occurs an execution of two different types of
statements in a program. First, if the available condition in the program is true, then there will be
an execution of the first statement. The execution of the second condition will only occur if the
condition available to us is false.

The syntax for this statement is as follows:

If (condition 1)

Statement 1 (s1);

else

Statement 2 (s2)

Statement

Example:
height=int(input(“Please enter your height: “))

if height>=160:

qualified=True

else:

qualified=False

print(“Qualification status: “,qualification)

NOTES:

21
1.2. The Nested If Statement

In this case, the condition available in the next if statement (the second statement) will only
get evaluated if the evaluation of the condition available in the first statement turns out to be true.
This occurs throughout the program that has a nested statement.

The syntax for this statement is as follows:


If (condition 1)
{
If (condition 2)
{
Statement 1 (s1);
}
Else
{
Statement 2 (s2)
}
}

Example:
if age>0:
print(“The candidate is a baby”)
if age<4:
print(“The candidate is a toddler”)
else if age<18:
print(“The candidate is not an adult”)
else if age<50:
print(“The candidate is an adult”)
else:
print(“No input of candidate”)

NOTES:

22
1.3. The Else If Ladder

In this statement, the execution of an array of instructions occurs only when the available
condition is correct. The verification of the next condition occurs when this first condition is
incorrect. In case all of the specifications fail even after the verification, then there will be an
execution of the default block statements. The remainder of the program’s ladder is shown below.

The syntax for this statement is as follows:

If (condition 1)

Statement 1 (s1);

Else if (condition 2)

Statement 2 (s2);

else if (condition 3)

Statement 3 (s3)

Else

Statement 4 (s4)

Statement (s);

NOTES:

23
Example:

if scores>=85:

result=’A+’

else if scores>=65:

result=’B+’

else if scores>=45:

result=’C+’

else:

result=”FAIL”

print(“Result: “,result)

1.4. The Simple Else or Null Else

This condition occurs when a programmer can skip or execute a set of various instructions
on the basis of the condition value. We select a one-way, simple statement. When the available
condition gets evaluated as true, then a set of various statements will be carried out. In case the
condition is false, then the control here will proceed ahead in the program with the declaration
mentioned below, after the program’s if declaration.

The syntax for this statement is as follows:

If (condition1)

Statement 1 (s1);

Statement 2 (s2);

NOTES:

24
2. The Switch Statements
The C language offers its users with a selection statement in various ways in case a
program becomes difficult to read with an increased number of conditions. A switch statement is a
multi-way type of selection statement that would resolve this issue. The switch declaration comes
into play when more than three alternatives (conditions) exist in a program. This command then
switches between all the available blocks on the basis of the expression value. Then, each block
has a corresponding value with it.

The syntax for this statement is as follows:

Switch (expression_A)

Label case_A:

Statement A (sA);

Break;

Label case_B:

Statement B (sB);

Break;

Label case_C;

Statement C (sC);

Break;

….

Label case_Z:

Statement Z (sZ);

Break;

Default:

Statement_1 (s1);

Break;

NOTES:

25
Every block is shown here with the use of the case keyword. As a matter of fact, the case
keyword is also followed by the block label. Note that the break statement and default block
statement are very optional in the case of the switch statement.

3. The Conditional Operator Statements

The C language also comes with a very unusual operator for its programmers – the
conditional operator.

The syntax of the conditional operator statements is as follows:

(condition 1)? expression_1: expression_2

Here, the execution of the expression_1 will only occur when the given condition is valid.
In case this statement is incorrect, then the execution of the expression_2 will occur.

Example:

#include <stdio.h>

int main() {

int b;

int a = 2;

b = (a >= 6) ? 6 : a;/* Here, it is equivalent to: if (a >= 5) b = 5; else b = x; */

printf(“b =%d “,b);

return 0;}

The output obtained here would be:

b=2

NOTES:

26
4. The Goto Statement

The Goto statement is especially known in the case of jumping control statements. We
mainly use the goto statement when we want to transfer a program’s control from any one block to
another. Also, we use the goto keyword for the declaration of the goto statement.

The syntax of the goto statement is as follows:

goto name_of_label;

name_of_label;

In the syntax given above, we have used the goto as a keyword for transferring the control
of the program to the name_of_label. Here, the name_of_label refers to a variable’s name. Thus, in
simpler words, the goto here will ultimately transfer the program’s control to the name_of_label.
Thus, there will occur an execution of all those statements that are followed by the name_of_label.

5. The Loop Statements

A programmer in C might want to repeat any set of instructions or certain statements in the
program to meet the necessary requirements. In such instances, it becomes difficult to rewrite and
repeat everything. And that is exactly where we would like to create loops using the looping
declarations. Loop control statements help in such types of situations in C. We have the following
types of loops in C:

• Do While Loop
• While Loop
• For Loop

Practice Problems on Control Statements in C

1. What would be the output obtained out of the program mentioned below:

#include<stdio.h>

int main()

NOTES:

27
int var1=1;

int var2=2;

if(var1<var2)

printf(“The value of var1 is smaller than that of the value of var2”);

return 0;

A. The value of var2 is smaller than that of the value of var1

B. The value of var1 is smaller than that of the value of var2

C. Compile time error will be obtained as a result

D. Garbage value will be obtained as a result

Answer – B. The value of var1 is smaller than that of the value of var2

2. What would be the output obtained out of the program mentioned below?

int a = 50;

a =a+ 1;

if (a == 51) {

printf(“Congratulations on your success today!”);}

A. a= 51>50

Congratulations on your success today!

NOTES:

28
B. a= 50<51

Congratulations on your success today!

C. Congratulations on your success today!

D. Compile time error will be obtained as a result

Answer – C. Congratulations on your success today!

3. What would be the output obtained out of the program mentioned below?

#include<stdio.h>

int main()

int val=109;

if(val<100)

printf(“The available value of the variable is less than 100”);

else

printf(“The available value of the variable is greater than 100”);

return 0;

NOTES:

29
A. The available value of the variable is less than 100

B. The available value of the variable is greater than 100

C. Garbage value will be obtained as a result

D. Compile time error will be obtained as a result

Answer – A. The available value of the variable is less than 100

1.5. Arrays
An array is a group of similar elements or data items of the same type collected at
contiguous memory locations. In simple words, we can say that in computer programming, arrays
are generally used to organize the same type of data.

Array for Integral value:

Array for Character value:

Representation of an Array:

Arrays can be represented in several ways, depending on the different languages. To make
you understand, we can take one example of the C language. The picture below shows the
representation of the array.

NOTES:

30
Arrays always store the same type of values. In the above example:

• int is a type of data value.


• Data items stored in an array are known as elements.
• The location or placing of each element has an index value.
Important: Array can store only the same type of data items. From the below example you can see
how it works:

• In the array a, we have stored all integral values (same type)


• In the array b, we have stored all char values (same type)
• In the array c, there is integral, float, char all types of values and this is not something an
array can store so, option 3 is wrong because an array cannot store different types of
values.

Declaration Syntax of Array:

VariableType VariableName[Sequence of Elements];

Example 1: For integral value

int A[10];

Here 10 means, this array A can have 10 integer elements.

2 5 8 44 21 11 7 9 3 1

Example 2: For character value

char B[10];

This array B can have 10 character elements.

f D A b n J l s e y

NOTES:

31
Initialization of an Array:
If an array is described inside a function, the elements will have garbage value. And in case
an array is static or global, its elements will be initialized automatically to 0.

We can say that we can simply initialize elements of an array at the time of declaration and
for that, we have to use the proper syntax:

Syntax: datatype Array_Name[size] = { value1, value2, value3, ….. valueN };

Types of Arrays:

There are two types of arrays:

• One-Dimensional Arrays
• Multi-Dimensional Arrays

One -Dimensional Arrays


A one-dimensional array is a kind of linear array. It involves single sub-scripting. The []
(brackets) is used for the subscript of the array and to declare and access the elements from the
array.

Syntax: DataType ArrayName [size];

For example: int a[10];

Multi-Dimensional Arrays

In multi-dimensional arrays, we have two categories:

• Two-Dimensional Arrays
• Three-Dimensional Arrays

1. Two-Dimensional Arrays
An array involving two subscripts [] [] is known as a two-dimensional array. They are also
known as the array of the array. Two-dimensional arrays are divided into rows and columns and
are able to handle the data of the table.

Syntax: DataType ArrayName[row_size][column_size];

For Example: int arr[5][5];

NOTES:

32
2. Three-Dimensional Arrays

When we require to create two or more tables of the elements to declare the array elements,
then in such a situation we use three-dimensional arrays.

Syntax: DataType ArrayName[size1][size2][size3];

For Example: int a[5][5][5];

Advantages of Array

• It is a better version of storing the data of the same size and same type.
• It enables us to collect the number of elements in it.
• Arrays have a safer cache positioning that improves performance.
• Arrays can represent multiple data items of the same type using a single name.

Disadvantages Of Array:

• In an array, it is essential to identify the number of elements to be stored.


• It is a static structure. It means that in an array, the memory size is fixed.
• When it comes to insertion and deletion, it is a bit difficult because the elements are stored
sequentially and the shifting operation is expensive.

1.6. Functions

All the programming languages contain functions. Library functions in C are also inbuilt
functions in C language. These inbuilt functions are located in some common location, and it is
known as the library. All the functions are used to execute a particular operation. These library
functions are generally preferred to obtain the predefined output. Also, the actions of these
functions are present in their header files.
Library Functions in Different Header Files
Here in this table-picture, there are some header files with their meanings.
Header file Description
stdio.h This is standard input/output header file in which Input/Output functions are
declared
conio.h This is console input/output header file
string.h All string related functions are defined in this header file
stdlib.h This header file contains general functions used in C programs
math.h All maths related functions are defined in this header file
time.h This header file contains time and clock related functions

NOTES:

33
ctype.h All character handling functions are defined in this header file
stdarg.h Variable argument functions are declared in this header file
signal.h Signal handling functions are declared in this file
setjmp.h It includes all jump functions
locale.h It includes locale functions
errno.h Error handling functions are given in this file
assert.h It includes diagnostics functions

Advantages of Using C library Functions

1. The Execution: One of the most significant reasons for utilising the library functions is that these
functions are easy-to-use, and have gone through strict testing.
2. The Functions to Boost the Performance: The standard library functions are very popular. And,
that is the reason developers are trying their best to polish them. During this process, they come up
with an efficient code almost every time to boost the performance.
3. Can Save a Lot of Time: The best part is you don’t need to create basic functions, like calculating
the square root and more, because we already have these. So, the conclusion is, we can save a lot of
time here.
4. These Functions are Convenient: The best quality of an application is that it should work every
time and everywhere. These library functions assist you in this particular phenomenon.

FUNCTION IN C :
We refer to a function as a group of various statements that perform a task together. Any C
program that we use has one function at least, that is main(). Then the programs can define multiple
additional functions in a code.

Use of the Function in C


One can easily divide a C program code into several separate functions. How we divide our
available code according to different available functions is totally up to us. But the division should
occur logically in such a way that every function is capable of performing a specific task.
The declaration of function informs the compiler about the name of the function, parameters, and
return type. In other words, the function definition helps in providing the actual body of any function
that we want in a program/ code.
We can also refer to functions as a sub-routine, a method, or a procedure in a program. The
standard library in C language provides its users with various built-in functions that the concerned
programs can call. For example, we can use the strcat() function for concentrating two strings, copy
the location of one memory to another location of memory using the memcpy() function, and many
more.

Advantages of Using Functions in C Programming


The functions in the C programming language offer the following advantages to us:
• When we make use of the functions, then we can easily avoid the rewriting of the
same code/ logic time and again multiple times in any program.

NOTES:

34
• The calling of C functions may appear as many numbers of times as we want in any
program. And we can do so from any place in the program that is given to us.
• We can perform the tracking of a large C program pretty easily if we divide it into
various functions.
• One of the primary achievements of the C functions is reusability.
• However, remember that the function calling always acts as an overhead in the case
of a C program.

Defining a Function in C
The function definition, in general, holds this form in the C programming language:
return_type name_of_function( parameter list ) {
function body
}
The function definition in the C programming language contains a function body and a function
header. Let us take a look at all the parts that a function consists of:
• Function Name − It denotes the actual name of any function that we are using in
the given code. The name and parameter of a function constitute a function signature in
the code together.
• Function Body − It consists of a collection of all the statements. These provide a
definition of what the function will do in the code.
• Parameters − It is just like a placeholder. Whenever we invoke a function, we pass
a value to the available parameter. We refer to this value as an argument or an actual
parameter. We refer to the parameter list as the number, order, and type of the function
in the code. The parameters may be optional. It means that any function in a code may
consist of no parameters at all.
• Return Type − We may get a value in return for a function. The term return type
refers to the data type of the returns that we get from the functions (function returns).
Some of the functions are also capable of performing any desired operation without
getting a value in return for it. In any such case, the keyword used for the return_type
will be void.

Syntax of Function Aspects of Function


return_type name_of_function (argument list) {function body;} Function definition
name_of_function (argument_list) Function call
return_type name_of_function (argument list); Function declaration

Function Syntax
Here is the syntax that we use to create a function in the C programming language:
return_type name_of_function(data_type parameter…){
// executable code in c
}
Example
Here, we have given a source code below for the function max(). The max() function takes
two of the parameters- namely val1 and val2. It then returns the maximum value that is present
between both of them. Let us take a look:

NOTES:

35
/* the function returns the max in between two values */
int max(int val1, int val2) {
/* declaration of local variable */
int result;
if (val1 > val2)
result = val1;
else
result = val2;
return result;
}

Types of Functions
The C programming language has functions that are of the following types:
• User-defined Functions – These are the types of functions that we can create
using the C programmer so that we can make use of it multiple times. This function
reduces the complexity of any big program- and thus, optimizes the given code.
• Library Functions – These are the functions whose declaration occurs in the
header files of C, such as floor(), ceil(), outs(), gets(), printf(), scanf(), etc.

Return Value
Any function in the C programming may not return its value from any function. In case we
don’t need to return the value that is available in any function, we can make use of the void in the
form of a return type. Let us look at an example of the C function that does not perform the return
of a value from the available function.
Let us look at an example of a C function that has no return value:
void chocolate(){
printf(“chocolate c”);
}
In case we want to return a value from an available function, we must make use of any of
the data types, such as char, long, int, etc. Thus, the return type depends totally on the value that
needs to return from the available function. We will look at an example of a C function that will
return an int value from the given function.
Example of a C function with int return value,
int get(){
return 20;
}
In the example mentioned above, we are trying to return the value 20, and the data type, in
this case, is int. If we are willing to return to the value of the floating-point (example, 64.5, 7,9,
27.61, etc.), then we must make use of the float in the form of the method’s return type.
float get(){
return 83.7;
}
Here, we have to call a function so that we get the function’s value.

NOTES:

36
Function Calling – Different Aspects
The functions available in a code may accept an argument or may not accept it at all. Thus, it may
return any of the values or may not do so. On the basis of these facts, the function calls have the
following four aspects:
• A function that has no arguments and has no return value.
• A function that has no arguments but has a return value.
• A function that has arguments but has no return value.
• A function that has arguments and also has a return value.
Example of a function that has no arguments and has no return value,
#include<stdio.h>
void printName();
void main ()
{
printf(“Bye “);
printName();
}
void printName()
{
printf(“Kiddo”);
}
The output generated from this program would be:
Bye Kiddo
Example of a function that has no arguments but has a return value,
#include<stdio.h>
int sum();
void main()
{
printf(“By calculating the area of the square given\n”);
float area = square();
printf(“The area of the given square will be: %f\n”,area);
}
int square()
{
float side;
printf(“The length of the side of square in meters will be: “);
scanf(“%f”,&side);
return side * side;
}
The output generated from this program would be:
By calculating the area of the square given
The length of the side of the square in meters will be: 10
The area of the given square will be: 100.000000
Example of a function that has arguments but has no return value,
#include<stdio.h>
void sum(int, int);
void main()

NOTES:

37
{
int x,y,result;
printf(“\nCalculation of the sum of two values:”);
printf(“\nEntering of two values:”);
scanf(“%d %d”,&x,&y);
sum(x,y);
}
void sum(int x, int y)
{
printf(“\nThe sum of the two values is %d”,x+y);
}
The output generated from this program would be:
Calculation of the sum of two values:
Entering of two values 58
62
The sum of the two values is 120
Example of a function that has arguments and also has a return value,
#include<stdio.h>
int sum(int, int);
void main()
{
int x,y,result;
printf(“\nThe calculation of the sum of two values:”);
printf(“\nThe entering of two values:”);
scanf(“%d %d”,&x,&y);
result = sum(x,y);
printf(“\nThe sum is : %d”,result);
}
int sum(int x, int y)
{
return x+y;
}
The output generated from this program would be:
The calculation of the sum of two values:
The entering of two values: 49
51
The sum is: 100
Declaration of Function
The function definition basically tells a compiler about the name of the function and how
one can call this function. Then we can define the actual body of this function separately.
There are these following parts that exist in a function declaration:
return_type name_of_function( parameter list );
For the defined function above that is max(), the function declaration will occur in the following
way:
int max(int val1, int val2);

NOTES:

38
The parameter names are not that important in the case of function declaration- we only
require their type. Thus, the declaration mentioned below is also going to be valid:
int max(int, int);
We only require the declaration of the function when we define that function in a source
file while we still call that function in a separate file. In any such case, we have to declare that
function at the very top of the file that calls that function.
Calling of a Function
When we create a function in C programming, we basically provide that function with a
definition of what it has to do. But to use this function, we need to call this function for performing
its defined task.
When a function gets called by a program, the called function will get the program control
transferred to it. The called function will be performing a defined task. Once we execute the return
statement or when it reaches the closing brace of the function-ending, it is bound to return the
program control to the main program.
For calling a function, we simply have to pass the parameters required for it, along with the name
of the function. Here, if the function happens to return a value, then we can easily keep the returned
value stored with us.
For example −
#include <stdio.h>
/* declaration of function */
int max(int val1, int val2);
int main () {
/* definition of local variable */
int x = 400;
int y = 500;
int ret;
/* function calling for getting a max value */
ret = max(x, y);
printf( “The max value is : %d\n”, ret );
return 0;
}
/* function returns the max in between two values */
int max(int val1, int val2) {
/* declaration of local variable */
int result;
if (val1 > val2)
result = val1;
else
result = val2;
return result;
}
Output
In this case, we have kept the function max() with the function main(). After that, we have
performed the compilation of the source code. Running of the final executable would be producing
the result that follows:
The max value is: 500

NOTES:

39
Function Arguments

When a function needs to use the arguments, it has to declare those variables that happen to
accept the arguments’ values. Such variables are known as the given function’s formal parameters.
The formal parameters behave just like any other local variables inside our given function. These
parameters get created when they enter into a function. After that, it gets destroyed when it exits.
During the calling of a function, there will be two ways in which we can perform the passing of
these arguments to a given function:

Type of Call Description of Call Type


Call By The Call by Reference method creates a copy of the address of the given argument
Reference into the parameter that is formal in nature. Inside this function, the use of address
helps in accessing the actual argument that comes in use in this call. It means that
the changes that appear on the parameter are bound to affect the given argument.
Call By Value The Call by Value method creates a copy of the actual value of the given argument
in the parameter of the function that is formal in nature. Here, the changes that
appear on the parameter (that exists inside the function) create no effect whatsoever
on the available argument.
The C programming, by default, is the Call by Value for passing the arguments. Generally,
it means that we cannot make use of the code that exists within a function for altering the
arguments that help in calling the function.

1.7 Structure and Union :

What is a Structure in C?
Structures are the user-defined data type, which allow us to collect the group of different
data types. Here, all the individual components or elements of structures are known as a member.

Syntax to Define the Structure in C

NOTES:

40
Example of Structure in C
You can understand the structure in C with the help of the example below:
struct student name
{ int rollnumber;
char name[20];
Float percentage;
};
Here struct Student is keeping the information of a student which consists of three data
fields, roll number, name, and percentage. These fields are known as structure elements or
members.
These elements can be of different data types. For example, here roll number is int type, the name
is char type, etc.
Memory Allocation In Structure in C

How to Declare Variables of a Structure?


We can declare the variables in two ways, the syntax is given below:
struct struct_name var_name;
Or
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

} var_name;
How to Access Data Members of a Structure Using a Struct Variable?
var_name.member1_name;
Var_name.member2_name;
For Example:
struct Employee
{
char name[20];
int age;
char department[15];
//F for female and M for male
char gender;
};
struct Employee e1, e2; //declaring variables of struct Employee
In this above code, we have declared the variables separately. We can also declare the
variables within the definition of structure.

NOTES:

41
For Example:
struct Employee
{
char name[20];
int age;
char department[15];
//F for female and M for male
char gender;
}E1, E2;
Detailed Example of Structure in C
#include <stdio.h>
/* Created a structure here. The name of the structure is
* EmployeeData.
*/
struct EmployeeData{
char *emp_name;
int emp_id;
int emp_age;
};
int main()
{
/* employee is the variable of structure EmployeeData*/
struct EmployeeData employee;
/*Assigning the values of each struct member here*/
employee.emp_name = “John”;
employee.emp_id = 1234;
employee.emp_age = 40;
/* Displaying the values of struct members */
printf(“Employee Name is: %s”, employee.emp_name);
printf(“\nEmployee Id is: %d”, employee.emp_id);
printf(“\nEmployee Age is: %d”, employee.emp_age);
return 0;
}
Output of the Above Code:
Employee Name is: John
Employee Id is: 1234
Employee Age is: 40

Union :

Unions are the user defined data type. They are conceptually similar to structures. The
syntax to define a union is also similar to that of a structure. The only difference is in terms of
storage. In a structure, each member has its own storage location, whereas all members of a union
use a single shared memory location, which is equal to the size of its largest data member.

NOTES:

42
How to Define a Union?
Syntax:
union student
{
char name[50];
int roll number;
};
How to Create a Union Variable?
When a union is represented, it makes a user-defined type. Nevertheless, in this condition, no
memory is assigned. To assign the memory, we ought to build variables.
Let’s see how we can construct variables:
union student
{
char name[50];
int roll number;
};
int main()
{
union student stu1, stu2, *stu3;
return 0;
}
There is one more aspect of creating a union variable:
union student
{
char name[50];
int roll number;
} stu1, stu2, *stu3;
Accessing a Member in Union
Example – Full Program:
#include <stdio.h>
Union School{
float percentage;
int studentNo;
} j;
int main() {
[Link] = 12.3;
// when [Link] No is assigned a value,

NOTES:

43
// [Link] will no longer hold 12.3
[Link] = 100;
printf(“Percentage = %.1f\n”, [Link]);
printf(“Number of students= %d”, [Link]);
return 0;
}
Output of the Above Code:
Percentage= 0.0
Number of Students= 100

1.8 Pointers
The pointers in C language refer to the variables that hold the addresses of different variables
of similar data types. We use pointers to access the memory of the said variable and then manipulate
their addresses in a program. The pointers are very distinctive features in C- it provides the language
with flexibility and power.
What are Pointers in C?
The pointers perform the function of storing the addresses of other variables in the program.
These variables could be of any type- char, int, function, array, or other pointers. The pointer sizes
depend on their architecture. But, keep in mind that the size of a pointer in the 32-bit architecture is
2 bytes.
Let us look at an example where we define a pointer storing an integer’s address in a program.
int x = 10;
int* p = &x;
Here, the variable p is of pointer type, and it is pointing towards the address of the x variable, which
is of the integer type.
How Do We Use Pointers in C?
Consider that we are declaring a variable “a” of int type, and it will store a value of zero.
int a = 0
Now, a is equal to zero.

Declaration of a Pointer
Just like the variables, we also have to declare the pointers in C before we use them in any
program. We can name these pointers anything that we like, as long as they abide by the naming
rules of the C language. Normally, the declaration of a pointer would take a form like this: data_type
* name_of_pointer_variable;
Note that here,
• The data_type refers to this pointer’s base type in the variable of C. It indicates which
type of variable is the pointer pointing to in the code.
• The asterisk ( * ) is used to declare a pointer. It is an indirection operator, and it is
the same asterisk that we use in multiplication.
We can declare pointers in the C language with the use of the asterisk symbol ( * ). It is also called
the indirection pointer, as we use it for dereferencing any pointer. Here is how we use it:
int *q; // a pointer q for int data type
char *x; // a pointer x for char data type

NOTES:

44
The Initialization of a Pointer
Once we declare a pointer, we then initialise it just like the standard variables using an
address of the variable. In case we don’t initialise the pointers in any C program and start using it
directly, the results can be pretty unpredictable and potentially disastrous.
We use the & (ampersand) operator to get the variable’s address in the program. We place the &
just before that variable’s name whose address we require. Here is the syntax that we use for the
initialisation of a pointer,
Syntax of Pointer Initialization
pointer = &variable;
Let us look at an example of how we can use pointers for printing the addresses along with the
value.

As we can assess in the figure shown above, the pointer variable is storing the digit
variable’s address, named fff4. This digit variable’s value is equal to 100. But aaa3 is the pointer
variable’s address (variable r).
Here, we can print the r pointer variable’s value using the indirection pointer ( * ). We will look at
an example for the same, as explained in the figure mentioned above.
#include<stdio.h>
int main(){
int digit=100;
int *r;
r=&digit; // for storing the address of the digit variable in the program
printf(“The address of the variable r is equal to %x \n”,r); // pointer r contains the digit variable’s
address, and thus, printing the variable r gives us the address of the digit.
printf(“The value of the variable r is equal to %d \n”,*r); // We are using * to dereference the
pointer, and thus, printing *r, would give the value that is stored at that address which is contained
by r.
return 0;
}
The output of the code mentioned above would be like this:
The address of the variable r is equal to fff4
The value of the variable r is equal to 100
Use of Pointers in C
Here is a summary of how we use the following operators for the pointers in any program:
Operator Name Uses and Meaning of Operator
* Asterisk Declares a pointer in a program.
Returns the referenced variable’s value.
& Ampersand Returns a variable’s address

NOTES:

45
The Pointer to an Array
Here is an example to illustrate the same,
int arr [20];
int *q [20] = &arr; // The q variable of the pointer type is pointing towards the integer array’s
address or the address of arr.

The Pointer to a Function


Here is an example to illustrate the same,
void display (int);
void(*q)(int) = &show; // The q pointer is pointing towards the function’s address in the program

The Pointer to a Structure


Here is an example to illustrate the same,
struct str {
int x;
float y;
}ref;
struct str *q = &ref;

Types of Pointers
There are various types of pointers that we can use in the C language. Let us take a look at
the most important ones.
The Null Pointer
The null pointer has a value of 0. To create a null pointer in C, we assign the pointer with a
null value during its declaration in the program. This type of method is especially useful when the
pointer has no address assigned to it. Let us take a look at a program that illustrates how we use the
null pointer:
#include <stdio.h>
int main()
{
int *a = NULL; // the null pointer declaration
printf(“Value of the variable a in the program is equal to :\n%x”,a);
return 0;
}
The output obtained out of the program mentioned above will be:
Value of the variable a in the program is equal to: 0

The Void Pointer


The void pointer is also known as the generic pointer in the C language. This pointer has
no standard data type, and we create it with the use of the keyword void. The void pointer is
generally used for the storage of any variable’s address. Let us take a look at a program that
illustrates how we use the void pointer in a C program:
#include <stdio.h>

NOTES:

46
int main()
{
void *q = NULL; // the void pointer of the program
printf(“Size of the void pointer in the program is equal to : %d\n”,sizeof(q));
return 0;
}
The output obtained out of the program mentioned above will be:
Size of the void pointer in the program is equal to : 4

The Wild Pointer


We can call a pointer a wild pointer if we haven’t initialized it with anything. Such wild
pointers are not very efficient in a program, as they may ultimately point towards some memory
location that is unknown to us. It will ultimately lead to some problems in the program, and then, it
will crash. Thus, you must be very careful when using wild pointers in a program. Let us take a
look at a program that illustrates how we use the wild pointer in a C program:
#include <stdio.h>
int main()
{
int *w; // the wild pointer in the program
printf(“\n%d”,*w);
return 0;
}
The output obtained out of the program mentioned above will be a compile-time error.
Here are a few more types of pointers that you can find in the C programs:
• Near pointer
• Complex pointer
• Huge pointer
• Far pointer
• Dangling pointer

Accessing Pointers- Indirectly and Directly


There are basically two ways in which a program can access a variable content and then
manipulate it:
• Direct Access: In this case, we use the variable name in the program directly.
• Indirect Access: In this case, we use some pointers to the variables in the program.
Let us take a look at a program to understand this better. Consider the below program:
#include <stdio.h>
/* Declaration and initialization of an int variable in the program */
int variable = 1;
/* Declaration of the pointer to the int variable */
int *ptr;
int main( void )
{
/* Initialization of ptr to the point to the variable */
ptr = &variable;
/* Accessing var indirectly and directly */

NOTES:

47
printf(“\nThe direct access of the variable would be = %d”, variable);
printf(“\nThe indirect access of the variable would be = %d”, *ptr);
/* Displaying of the address of the variable in both the ways */
printf(“\n\nOutput of the address of the variable would be = %d”, &variable);
printf(“\nOutput of the address of the variable would be = %d\n”, ptr);
/*changing of the content of the variable through the ptr pointer in the program*/
*ptr=48;
printf(“\nThe indirect access of the variable would be = %d”, *ptr);
return 0;
}
The compilation of this program devoid of errors would generate an output like this:
The direct access of the variable would be = 1
The indirect access of the variable would be = 1
Output of the address of the variable would be = 4202496
Output of the address of the variable would be = 4202496
The indirect access of the variable would be = 48

Pros of using Pointers in C


• Pointers make it easy for us to access locations of memory.
• They provide an efficient way in which we can access the elements present in the
structure of an array.
• We can use pointers for dynamic allocation and deallocation of memory.
• These are also used to create complex data structures, like the linked list, tree,
graph, etc.
• It reduces the code and thus improves the overall performance. We can use it to
retrieve the strings, trees, and many more. We can also use it with structures, arrays,
and functions.
• We can use the pointers for returning various values from any given function.
• One can easily access any location of memory in the computer using the pointers.
Cons of Pointers in C
• The concept of pointers is a bit tricky to understand.
• These can lead to some errors like segmentation faults, accessing of unrequired
memory locations, and many more.
• A pointer may cause corruption of memory if we provide it with an incorrect
value.
• Pointers in a program can lead to leakage of memory.
• As compared to all the other variables, pointers are somewhat slower.
• Some programmers might find it very tricky to deal with pointers in a program. It
is their responsibility to use these pointers and manipulate them carefully.
Applications of Pointers in C
There are various uses of the pointers in C language. Let us look at some of them:
1. Dynamic allocation of memory: We can allocate the memory dynamically in C language when we
use the calloc() and malloc() functions. The pointers are primarily used in such cases.
2. Structures, Functions, and Arrays: We generally use the pointers in the C language in the cases of
structures, functions, and arrays. Here, the pointers help in reducing the code and improving the
program’s performance.

NOTES:

48
2.0 Introduction of Python programming
2.1 Introduction
History
➢ Python was developed by Guido van Rossum in the late eighties and early nineties atthe
National Research Institute for Mathematics and Computer Science in the Netherlands.
➢ Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.

➢ Python is copyrighted. Like Perl, Python source code is now available under the GNUGeneral Public
License (GPL).

➢ Python is now maintained by a core development team at the institute, although Guidovan
Rossum still holds a vital role in directing its progress.

Python's features include −


Easy-to-learn − Python has few keywords, simple structure, and a clearlydefined
syntax. This allows the student to pick up the language quickly.

Easy-to-read − Python code is more clearly defined and visible to the eyes.

Easy-to-maintain − Python's source code is fairly easy-to-maintain.

A broad standard library − Python's bulk of the library is very portable andcross-
platform compatible on UNIX, Windows, and Macintosh.

Interactive Mode − Python has support for an interactive mode which allowsinteractive
testing and debugging of snippets of code.

Portable − Python can run on a wide variety of hardware platforms and has thesame
interface on all platforms.

Extendable − You can add low-level modules to the Python interpreter. Thesemodules
enable programmers to add to or customize their tools to be more efficient.

Databases − Python provides interfaces to all major commercial databases.

NOTES:

49
GUI Programming − Python supports GUI applications that can be created andported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and
the X Window system of Unix.

Scalable − Python provides a better structure and support for large programsthan shell
scripting.

Apart from the above-mentioned features, Python has a big list of good features, feware listed below

• It supports functional and structured programming methods as well as OOP.
• It can be used as a scripting language or can be compiled to byte-code
forbuilding large applications.
• It provides very high-level dynamic data types and supports dynamic
typechecking.
• IT supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

➢ comparison with other programming languages.

Python is an easily adaptable programming language that offers a lot of features. Its concise
syntax and open-source nature promote readability and implementation of programs which makes
it the fastest-growing programming language in current times. Python has various other advantages
which give it an edge over other popular programming languages such as Java and C++.

➢ Install Python Separately

• If you don't want to use Thonny, here's how you can install and run Python
onyour computer.

• Download the latest version of Python.

• Run the installer file and follow the steps to install Python

• During the install process, check Add Python to environment variables. This
willadd Python to environment variables, and you can run Python from any
part of the computer.

NOTES:

50
Also, you can choose the path where Python is installed.

Once you finish the installation process, you can run Python.

1. Run Python in Immediate mode

Once Python is installed, typing python in the command line will invoke the interpreter in
immediate mode. We can directly type in Python code, and press Enter to get the output.

Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used asa calculator.
To exit this mode, type quit() and press enter.

NOTES:

51
2. Run Python in the Integrated Development Environment (IDE)

We can use any text editing software to write a Python script file.

We just need to save it with the .py extension. But using an IDE can make our life a lot easier.
IDE is a piece of software that provides useful features like code hinting, syntaxhighlighting and
checking, file explorers, etc. to the programmer for application development.

By the way, when you install Python, an IDE named IDLE is also installed. You can useit to run
Python on your computer. It's a decent IDE for beginners.

When you open IDLE, an interactive Python Shell is opened.

Now you can create a new file and save it with .py extension. For example, [Link]

Write Python code in the file and save it. To run the file, go to Run > Run Module orsimply
click F5.

NOTES:

52
➢ Python Indentation

Most of the programming languages like C, C++, and Java use braces { } to define ablock of code.
Python, however, uses 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 consistentthroughout that
block.

Generally, four whitespaces are used for indentation and are preferred over tabs.

The enforcement of indentation in Python makes the code look neat and clean. Thisresults in
Python programs that look similar and consistent.

Indentation can be ignored in line continuation, but it's always a good idea to indent. Itmakes the
code more readable.

➢ Python Comments

Comments are very important while writing a program. They describe what is going on inside a
program, so that a person looking at the source code does not have a hard timefiguring it out. You
might forget the key details of the program you just wrote in a month's time. So taking the time to
explain these concepts in the form of comments is always fruitful.

In Python, we use the hash (#) symbol to start writing a comment.

Python Interpreter ignores comments.

Example:
#This is a comment
#print out Hello
print('Hello')

➢ Multi-line comments

We can have comments that extend up to multiple lines.


One way is to use the hash(#) symbol at the beginning of each line. Another way of doing this is to
use triple quotes, either ''' or """.

NOTES:

53
➢ Python Variables
A variable is a named location used to store data in the memory. It is helpful to think ofvariables as a
container that holds data that can be changed later in the program.

Example:
number = 10
➢ Constants:
constant is a type of variable whose value cannot be changed. It is helpful to think ofconstants
as containers that hold information which cannot be changed later. Constants are written in all
capital letters and underscores separating the words.

Example:
PI = 3.14
GRAVITY = 9.8

➢ Rules and Naming Convention for Variables and constants

1. Constant and variable names should have a combination of letters in


lowercase(a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_).

2. Create a name that makes sense.

3. If you want to create a variable name having two words, use underscore
toseparate them.

4. Use capital letters possible to declare a constant.

5. Never use special symbols like!, @, #, $, %, etc.

6. Don't start a variable name with a digit.

2.2 Data types in Python

Every value in Python has a datatype. 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.

➢ Python Numbers

Integers, floating point numbers and complex numbers fall under Python numbers
category. They are defined as int, float and complex classes in Python.

NOTES:

54
We can use the type() function to know which class a variable or a value belongs to.
Similarly, the isinstance() function is used to check if an object belongs to a particularclass.

Python Input, Output and Import

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 andoutput
operations respectively. Let us see the output section first.

Python Output Using print() function

We use the print() function to output data to the standard output device (screen). Wecan also
output data to a file, but this will be discussed later.

An example of its use is given below.


a=5
print ('The value of a is', a)

Output
The value of a is 5

The actual syntax of the print() function is:

print(*objects, sep=' ', end='\n', file=[Link], flush=False)Here,

objects is the value(s) to be printed.

The sep separator is used between the values. It defaults into a space character. After all values are
printed, end is printed. It defaults into a new line.

Output formatting
Sometimes we would like to format our output to make it look attractive. This can bedone by
using the [Link]() method. This method is visible to any string object.

>>> x = 5; y = 10

>>> print('The value of x is {} and y is {}'.format(x,y))

The value of x is 5 and y is 10


Python Input

NOTES:

55
To allow flexibility, we might want to take the input from the user. In Python, we havethe
input() function to allow this. The syntax for input() is:

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input ('Enter a number: ')

Enter a number: 10

>>> num

'10'

Operators

What are operators in python?

Operators are special symbols in Python that carry out arithmetic or logical computation. The
value that the operator operates on is called the operand.
For example:

>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is theoutput of the
operation.

Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication, etc.

Operator Meaning Example

+ Add two operands or unary plus x + y+ 2

NOTES:

56
Subtract right operand from the left or unary
- x - y- 2
minus

* Multiply two operands x*y

/ Divide left operand by the right one (always x/y


results into float)

x%y
Modulus - remainder of the division of left
(remainder
%
operand by the right
ofx/y)

// x // y
Floor division - division that results into whole

number adjusted to the left in the number line

Exponent - left operand raised to the power of right x**y


** (x to the power y)

NOTES:

57
Comparison operators

Comparison operators are used to compare values. It returns


either True or False according to the condition.
Operator Meaning Example

Greater than - True if left operand is greater than theright


> x>y

< Less than - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to - True if left operand is greaterthan or


>= x >= y
equal to the right

Less than or equal to - True if left operand is less than orequal to the
<= x <= y
right

NOTES:

58
Logical operators
Logical operators are the and, or, not operators.

Operator Meaning Example

and True if both the operands are true x and y

Or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

Decision Making and Loops

Decision making is required when we want to execute a code only if a certain conditionis
satisfied. The if…elif…else statement is used in Python for decision making.

Python if

Statement

Syntaxif test expression:

statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True. If the text expression is False, the statement(s) is not executed. In Python, the
body of the if statement is indicated by the indentation. Body starts with an indentation and the first
unindented line marks the end. Python interpretsnon-zero values as True. None and 0are interpreted
as False.

NOTES:

59
Python if Statement Flowchart

Python if...else
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only whentest
condition is True. If the condition is False, body of else is executed. Indentation isused to separate
the blocks.

Python if..else Flowchart

NOTES:

60
Python if...elif...else
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

The elif is short for else if. It allows us to check for multiple expressions. If the conditionfor
ifis False, it checks the condition of the next elif block and so on. If all the conditionsare False, body
of else is executed. Only one block among the several if...elif...else blocks is executed according to
the condition. A if block can haveonly one else block. But it can have multiple elifblocks.

Flowchart of if...elif...else

Looping
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
Body of for

NOTES:

61
Here, val is the variable that takes the value of the item inside the sequence on eachiteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from
the rest of the code using indentation.
Flowchart of for Loop

Python while Loop


The while loop in Python is used to iterate over a block of code as long as the testexpression
(condition) is true. We generally use this loop when we don't know beforehand, the number of times
to iterate.

Syntax of while Loop

while test_expression:

Body of while

In while loop, test expression is checked first. The body of the loop is entered only if the
test_expression evaluates to True. After one iteration, the test expression is checked again. This
process continues untill the test_expression evaluates to False.

NOTES:

62
In Python, the body of the while loop is determined through indentation. Body starts with
indentation and the first unindented line marks the end. Python interprets any non-zero value as True.
None and 0 are interpreted as False.
Flowchart of while Loop

What is a function? Types of Functions, Function Arguments Recursive


Function

What is a function in Python?


In Python, a function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. As our programgrows larger and
larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function

def function name(parameters):

"""docstring"""

statement(s)

NOTES:

63
Above shown is a function definition that consists of the following components.

Keyword def that marks the start of the function header.

A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.

Parameters (arguments) through which we pass values to a function. They are optional.A colon

(:) to mark the end of the function header.

Optional documentation string (docstring) to describe what the function does.

One or more valid python statements that make up the function body. Statements musthave the
same indentation level (usually 4 spaces).

An optional return statement to return a value from the function.

How to call a function in python?

Once we have defined a function, we can call it from another function, program oreven the
Python prompt. To call a function we simply type the function name with appropriate parameters.

The return statement

The return statement is used to exit a function and go back to the place fromwhere it was called.

Syntax of return

return [expression_ list]


This statement can contain an expression that gets evaluated and the value is returned. If there
is no expression in the statement or the return statement itself is notpresent inside a function, then the
function will return the None object.

NOTES:

64
Python Function Arguments

In Python, you can define a function that takes variable number of arguments.

Variable Function Arguments

Up until now, functions had a fixed number of arguments. In Python, there areother ways to
define a function that can take variable number of arguments.

Three different forms of this type are described below.

Python Default Arguments

Function arguments can have default values in Python.

We can provide a default value to an argument by using the assignment operator (=).

Python Keyword Arguments

When we call a function with some values, these values get assigned to thearguments according
to their position.

Python allows functions to be called using keyword arguments. When we callfunctions in this
way, the order (position) of the arguments can be changed.

Python Arbitrary Arguments

Sometimes, we do not know in advance the number of arguments that will be passed into a
function. Python allows us to handle this kind of situation through function calls with an arbitrary
number of arguments.

In the function definition, we use an asterisk (*) before the parameter name to denotethis kind
of argument.

Types of Functions
Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

NOTES:

65
What is recursion?

Recursion is the process of defining something in terms of itself.


A physical world example would be to place two parallel mirrors facing each other. Anyobject in between
them would be reflected recursively.
Python Recursive Function

In Python, we know that a function can call other functions. It is even possible for thefunction to call
itself. These types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recurse.

Advantages of Recursion
1. Recursive functions make the code look clean and elegant.

2. A complex task can be broken down into simpler sub-problems using recursion.

3. Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.

2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.

3. Recursive functions are hard to debug.

Python Anonymous/Lambda Function


What are lambda functions in Python?
In Python, an anonymous function is a function that is defined without a name.

While normal functions are defined using the def keyword in Python, anonymous functions are
defined using the lambda keyword.

Hence, anonymous functions are also called lambda functions.

NOTES:

66
How to use lambda Functions in Python?

A lambda function in python has the following syntax.

Syntax of Lambda Function in pythonlambda

arguments: expression

Lambda functions can have any number of arguments but only one expression. The expression is
evaluated and returned. Lambda functions can be used wherever functionobjects are required.

Example of Lambda Function in python

double = lambda x: x * 2

is nearly the same as:

def double(x):

return x * 2
Python Global, Local and Nonlocal variables

Global Variables
In Python, a variable declared outside of the function or in global scope is known as a global
variable. This means that a global variable can be accessed inside or outside ofthe function.
Local Variables

A variable declared inside the function's body or in the local scope is known as a localvariable.
Nonlocal Variables

Nonlocal variables are used in nested functions whose local scope is not defined. This
means that the variable can be neither in the local nor the global scope.

Python Data Types, Decision Making, and Loops

Python Data Types:

Python data types identify the type of data that a variable can store. Besides, a variable is
basically an object or an element that we store in the memory. This variable stores different types of
values. Hence, the data type decides the type of a value. Every value in python belongs to a different
data type. Moreover, there are various types of data types in python.

NOTES:

67
Python Number

We store numeric values in this data type. Furthermore, it has three different types as follows:

int
It stores all the integer numbers. Moreover, these numbers can be positive or negative. For
example, 1, -99, 10, 25, etc.

float
This data type stores the real or floating type numbers. This means that it stores all the
numbers having decimal values. Moreover, they can be negative or positive. For example, 4.0, -2.89,
3.45, etc.

complex
This data type stores complex type numbers. Moreover, such numbers have two parts, real and
imaginary. For example, 2+4i, 6-8i, etc.

Also, we can use the ‘type()’ function to find out the type of a particular value or variable. For
example,

>>> num=10 >>> type (num) <class 'int'> >>> num=111.23 >>> type (num) <class 'float'> >
>> num= 10 + i55 >>> type (num) <class 'complex'>

Besides, variables that hold these simple data types can hold only a single value at a time.
Therefore, they are not useful for storing things like months, names of employees in a company, etc.
Hence, python consists of data types like lists, sets, tuples, etc for storing such values.
Conversion and types of Conversion:The process of converting the value of one data type
(integer, string, float, etc.) to another data type is called type conversion. Python has two types of
type conversion.
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another datatype.
This process doesn't need any user involvement.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the predefined functions like int(), float(), str(), etc to perform explicit typeconversion.

NOTES:

68
Python Sequence

It is a type that stores more than one item at a time. Therefore, we can say that it is a collection
of items. Moreover, to access these items each item has a particular index number. There are three
types of sequence data types namely, strings, lists, and tuples.

Python Pytho Strings


It is a group of characters. These characters can be digits, alphabets, or special symbols.
Moreover, they can be with or without spaces. We can represent a string using single quotes, double
quotes, or, triple quotes. Hence, these quotes mark the beginning and end of a string and are not a part
of the string. Besides, numeric operations are not valid on a string. Examples of Strings are as follows:

>>> str='hello'

>>> str2=''hello''

>>> str3='231'

Python Lists
It is a collection of different types of data. Besides, we can represent it using square brackets
[]. We sequentially store the items and separate them using commas. Examples are as follows:

# creating a list
>>> list1 = [ 1, 33, 'hello', 45.3 ]
# printing list items
>>> print (list1)
[ 1, 33, 'hello', 45.3 ]

Python Tuples
It is also a sequence of characters separated by commas. Moreover, we declare a tuple using
round brackets (). Besides, we cannot change a tuple once we create it. Examples are as follows:

# creating a tuple

>>> tuple1 = ( 1, 33, 'hello', 45.3 )

# printing tuple items

>>> print (tuple1)

( 1, 33, 'hello', 45.3 )

NOTES:

69
The Python string data type is a sequence made up of one or more individual characters
that could consist of letters, numbers, whitespace characters, or symbols. As the string is a
sequence, it can be accessed in the same ways that other sequence-based data types are, through
indexing and slicing.
Indexing
Indexing means referring to an element of an iterable by its position within the iterable.
Each of a string’s characters corresponds to an index number and each character can be accessed
using its index number. We can access characters in a String in Two ways:
1. Accessing Characters by Positive Index Number
2. Accessing Characters by Negative Index Number

1. Accessing Characters by Positive Index Number: In this type of Indexing, we pass a


Positive index (which we want to access) in square brackets. The index number starts from
index number 0 (which denotes the first character of a string).

Example 1 (Positive Indexing):

# declaring the string

str = "Geeks for Geeks !"

# accessing the character of str at 0th index

print(str[0])

# accessing the character of str at 6th index

print(str[6])

# accessing the character of str at 10th index

NOTES:

70
print(str[10])

Output

G
f
G
2. Accessing Characters by Negative Index Number: In this type of Indexing, we pass the
Negative index (which we want to access) in square brackets. Here the index number starts
from index number -1 (which denotes the last character of a string).
Example 2 (Negative Indexing):
# declaring the string

str = "Geeks for Geeks !"

# accessing the character of str at last index

print(str[-1])

# accessing the character of str at 5th index from the last

print(str[-5])

# accessing the character of str at 10th index from the last

print(str[-10])

Output

!
e
o

NOTES:

71
Slicing
Slicing in Python is a feature that enables accessing parts of the sequence. In slicing a
string, we create a substring, which is essentially a string that exists within another string. We
use slicing when we require a part of the string and not the complete string.
Syntax:
string [start : end : step]
• start: We provide the starting index.
• end: We provide the end index (this is not included in substring).
• step: It is an optional argument that determines the increment between each index for
slicing.

Example 1:
# declaring the string

str ="Geeks for Geeks !"

# slicing using indexing sequence

print(str[: 3])

print(str[1 : 5 : 2])

print(str[-1 : -12 : -2])

Output

Gee
ek
!seGrf
Decision-making statements in Python
There come situations in real life when we need to make some decisions and based on
these decisions, we decide what should we do next.
Similar situations arise in programming also where we need to make some decisions and
based on these decisions we will execute the next block of code. This is done with the help of
decision-making statements in Python.

NOTES:

72
Example:

# Python program to demonstrate

# decision making

i = 20;

if (i < 15):

print ("i is smaller than 15")

print ("i'm in if Block")

else:

print ("i is greater than 15")

print ("i'm in else Block")

print ("i'm not in if and not in else Block")

Output:

i is greater than 15
i'm in else Block
i'm not in if and not in else Block
Nested-if Statement
We can have an 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. This can get confusing,
so it must be avoided if we can.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

NOTES:

73
Example 1:

# Python program to demonstrate

# nested if statement

num = 15

if num >= 0:

if num == 0:

print("Zero")

else:

print("Positive number")

else:

print("Negative number")

Output:

Positive number

Python break and continue Statement

In Python, break and continue statements can alter the flow of a normal loop. Loops iterate
over a block of code until test expression is false, but sometimes we wish to terminate the current
iteration or even the whole loop without cheking test [Link] break and continue statements
are used in these cases.

break statement
The break statement terminates the loop containing it. Control of the program flows tothe
statement immediately after the body of the loop. If it is inside a nested loop (loop inside another
loop), break will terminate the innermost loop.

Syntax of break
for / while loop:
# statement(s)
if condition:
break
# statement(s)
# loop end

NOTES:

74
Flowchart of break

The working of break statement in for loop and while loop is shown below.

Example:
# Python program to demonstrate

# break statement

s = 'geeksforgeeks'

# Using for loop

for letter in s:

print(letter)

# break the loop as soon it sees 'e'

# or 's'

NOTES:

75
if letter == 'e' or letter == 's':

break

print("Out of for loop")

print()

i=0

# Using while loop

while True:

print(s[i])

# break the loop as soon it sees 'e'

# or 's'

if s[i] == 'e' or s[i] == 's':

break

i += 1

print("Out of while loop")

Output:
g
e
Out of for loop

Continue Statement in Python


Continue is also a loop control statement just like the break statement. continue statement
is opposite to that of the break statement, instead of terminating the loop, it forces to execute the
next iteration of the loop. As the name suggests the continue statement forces the loop to continue
or execute the next iteration. When the continue statement is executed in the loop, the code inside
the loop following the continue statement will be skipped and the next iteration of the loop will
begin.

Syntax of Continue Statement

The continue statement in Python has the following syntax:

for / while loop:


# statement(s)
if condition:

NOTES:

76
continue
# statement(s)

Flowchart of Continue

Example:

# Python program to

# demonstrate continue

# statement

# loop from 1 to 10

for i in range(1, 11):

# If i is equals to 6,

# continue to next iteration

# without printing

if i == 6:

continue

else:

NOTES:

77
# otherwise print the value

# of i

print(i, end = " ")

Output:

1 2 3 4 5 7 8 9 10

Sets and Dictionaries:

Python Set
Mathematically a set is a collection of items not in any particular order. A Python set is similar
to this mathematical definition with below additional conditions.

• The elements in the set cannot be duplicates.


• The elements in the set are immutable(cannot be modified) but the set as
awhole is mutable.
• There is no index attached to any element in a python set. So they do
notsupport any indexing or slicing operation.

Set Operations

The sets in python are typically used for mathematical operations like union, intersection,
difference and complement etc. We can create a set, access it’s elements and carry out these
mathematical operations as shown below.

Creating a set
A set is created by using the set() function or placing all the elements within a pair ofcurly
braces.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)

NOTES:

78
When the above code is executed, it produces the following result. Please note howthe order
of the elements has changed in the result.

set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])set(['Jan',


'Mar', 'Feb'])
set([17, 21, 22])

Accessing Values in a Set

We cannot access individual values in a set. We can only access all the elements together as
shown above. But we can also get a list of individual elements by looping through the set.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) for d in

Days:
print(d)

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

Wed
Sun
Fri
Tue
Mon
Thu
Sat

Adding Items to a Set

We can add elements to a set by using add() method. Again as discussed there is no
specific index attached to the newly added element.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])

[Link]("Sun")
print(Days)

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

set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

NOTES:

79
Removing Item from a Set
We can remove elements from a set by using discard() method. Again as discussedthere
is no specific index attached to the newly added element.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])

[Link]("Sun")
print(Days)

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

set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Union of Sets
The union operation on two sets produces a new set containing all the distinct elements from
both the sets. In the below example the element “Wed” is present in both the sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA|DaysB
print(AllDays)

When the above code is executed, it produces the following result. Please note theresult has only
one “wed”.

set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Intersection of Sets
The intersection operation on two sets produces a new set containing only the common
elements from both the sets. In the below example the element “Wed” is present in both the sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)

When the above code is executed, it produces the following result. Please note theresult has only
one “wed”.

set(['Wed'])

NOTES:

80
Difference of Sets
The difference operation on two sets produces a new set containing only the elements from the
first set and none from the second set. In the below example the element “Wed” is present in both the
sets so it will not be found in the result set.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB
print(AllDays)

When the above code is executed, it produces the following result. Please note theresult has only
one “wed”.

set(['Mon', 'Tue'])

Compare Sets
We can check if a given set is a subset or superset of another set. The result is True orFalse depending
on the elements present in the sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
SubsetRes = DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes) print(SupersetRes)

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

True
True

Python Dictionary
Each key is separated from its value by a colon (:), the items are separated bycommas, and
the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just
two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can
be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to
obtain its value. Following is a simple example −

NOTES:

81
Live Demo
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result –
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, weget
an error as follows −
Live Demo
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print "dict['Alice']: ", dict['Alice']

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


dict['Alice']:
Traceback (most recent call last):
File "[Link]", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying anexisting
entry, or deleting an existing entry as shown below in the simple example −
Live Demo
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age']
= 8; # update existing entry dict['School'] = "DPS
School"; # Add new entry

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

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


dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements

You can either remove individual dictionary elements or clear the entire contents of adictionary.
You can also delete entire dictionary in a single operation.

NOTES:

82
To explicitly remove an entire dictionary, just use the del statement. Following is asimple
example −
Live Demo
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
[Link](); # remove all entries in dict
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

This produces the following result. Note that an exception is raised because after del dict
dictionary does not exist any more −
dict['Age']:
Traceback (most recent call last):
File "[Link]", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section.

Properties of Dictionary Keys


Dictionary values have no restrictions. They can be any arbitrary Python object, eitherstandard objects
or user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins. For
example −Live Demo
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']

When the above code is executed, it produces the following result −dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple
example−
Live Demo
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']

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


Traceback (most recent call last):

NOTES:

83
File "[Link]", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'

List Comprehensions:

Comprehensions in Python provide us with a short and concise way to construct new
sequences (such as lists, sets, dictionaries, etc.) using previously defined
sequences. Python supports the following 4 types of comprehension:
• List Comprehensions
• Dictionary Comprehensions
• Set Comprehensions
• Generator Comprehensions
List Comprehensions
List Comprehensions provide an elegant way to create new lists. The following is the
basic structure of list comprehension:

Syntax: output_list = [output_exp for var in input_list if (var satisfies this condition)]

Note that list comprehension may or may not contain an if condition. List
comprehensions can contain multiple

Example 1: Generating Even list using List comprehensions

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

list_using_comp = [var for var in input_list if var % 2 == 0]

print("Output List using list comprehensions:" list_using_comp)


Output:
Output List using list comprehensions: [2, 4, 4, 6]

Here is an example of using list comprehension to find the square of the number
in Python.
Example:

numbers = [1, 2, 3, 4, 5]

squared = [x ** 2 for x in numbers]

print(squared)

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

NOTES:

84
Iteration with List Comprehension: In this example, we are assigning 1, 2, and 3 to the list
and we are printing the list using List Comprehension.

Example:

# Using list comprehension to iterate through loop

List = [character for character in [1, 2, 3]]

# Displaying list

print(List)

Output
[1, 2, 3]

2.3 Tuples, Dictionaries, and Data Processing

What is Immutable Nature?

Immutable is the when no change is possible over time. In Python, if the value of an object cannot
be changed over time, then it is known as immutable. Once created, the value of these objects is
permanent.

Tuple Methods:

1. count (value):
2. index (value):

Tuple Operations:

1. Concatenation (‘+’):
2. Repetition (*):
3. Membership (in and not in):
4. Length (‘len()’):
5. Slicing:

NOTES:

85
Files:

File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk). Since, random accessmemory (RAM) is volatile
which loses its data when computer is turned off, we use files for future use of the data. When we
want to read from or write to a file we need to open it first. When we are done,it needs to be closed,
so that resources that are tied with the file are freed. Hence, in Python, a file operation takes place in
the following order.

1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening a File
Python has a built-in function open() to open a file. This function returns a file object,also called
a handle, as it is used to read or modify the file accordingly.

>>> f = open("[Link]") # open file in current directory


>>> f = open("C:/Python33/[Link]") # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we want toread
'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary
mode. The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-
text files like image or exe files

Python File
Modes

Mode Description

'r' Open a file for reading. (default)

NOTES:

86
'w' Open a file for writing. Creates a new file if it does not exist or truncates the
file if it exists.

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

'a' Open for appending at the end of the file without truncating it. Creates a new
file if it does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

f = open("[Link]")
# equivalent to 'r' or 'rt'
f = open("[Link]",'w') # write in text mode
f = open("[Link]",'r+b') # read and write in binary mode

Since the version 3.x, Python has made a clear distinction between str (text) and bytes (8-bits). Unlike
other languages, the character 'a' does not imply the number 97 until it is encoded using ASCII (or other
equivalent encodings). Hence, when working with files in text mode, it is recommended to specify the
encoding type. Files are stored in bytes in the disk, we need to decode them into str when we read into Python.
Similarly, encoding is performed while writing texts to the file. The default encoding is platform dependent.
In windows, it is 'cp1252' but 'utf-8' in Linux. Hence, we must not rely on the default encoding otherwise, our
code will behavedifferently in different platforms. Thus, this is the preferred way to open a file for readingin
text mode.
= open("[Link]",mode = 'r',encoding = 'utf-8')

Closing a File
When we are done with operations to the file, we need to properly close it. Python has agarbage
collector to clean up unreferenced objects. But we must not rely on it to close the file. Closing a file
will free up the resources that were tied with the file and is done using the close()method.

NOTES:

87
f = open("[Link]",encoding = 'utf-8')

# perform file operations


[Link]()

This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file. A safer way is to usea
try...finally block.

try:

f = open("[Link]",encoding = 'utf-8')
# perform file operations
finally:
[Link]()

This way, we are guaranteed that the file is properly closed even if an exception is raised, causing
program flow to stop. The best way to do this is using the with statement. This ensures that the file is
closed when the block inside with is exited. We don't need to explicitly call the close() [Link] is
done internally.

with open("[Link]",encoding = 'utf-8') as f: #


perform file operations

Writing to a File
In order to write into a file we need to open it in write 'w', append 'a' or exclusive creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the fileif it already exists. All previous
data are erased. Writing a string or sequence of bytes (for binary files) is done using write() method.
Thismethod returns the number of characters written to the file.

with open("[Link]",'w',encoding = 'utf-8') as f:


[Link]("my first file\n")
[Link]("This file\n\n")
[Link]("contains three lines\n")
This program will create a new file named '[Link]' if it does not exist. If it does exist, it is
overwritten. We must include the newline characters ourselves to distinguish differentlines.

NOTES:

88
Reading From a File
To read the content of a file, we must open the file in reading mode. There are variousmethods available
for this purpose. We can use the read(size) method to read in size number of data. If size parameter is
not specified, it reads and returns up to theend of the file.

>>> f = open("[Link]",'r',encoding = 'utf-8')

>>> [Link](4) # read the first 4 data


'This'
>>> [Link](4) # read the next 4 data' is
'
>>> [Link]() # read in the rest till end of file'my
first file\nThis file\ncontains three lines\n'
>>> [Link]() # further reading returns empty sting''
We can see, that read() method returns newline as '\n'. Once the end of file is reached,we get empty
string on further reading. We can change our current file cursor (position)using the seek() method.
Similarly, the tell() method returns our current position (in number of bytes).
>>> [Link]() # get the current file position
56
>>> [Link](0) # bring file cursor to initial position
0
>>> print([Link]()) # read the entire file This is
my first file
This file
contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.

>>> for line in f:


... print(line, end = '')
...
This is my first file
This file
contains three lines

NOTES:

89
The lines in file itself have a newline character '\n'. Moreover,the print() function also
appends a newline by default. Hence, we specify the end parameter to avoid two newlines when
printing. Alternately, we can use readline() method to read individual lines of a file. This method
reads a file till the newline, including the newline character.

>>> [Link]()
'This is my first file\n'

>>>[Link]()
'This file\n'
>>> [Link]()
'contains three lines\n'
>>> [Link]()
''
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these
reading method return empty values when end of file (EOF) is reached.
>>> [Link]()
['This is my first file\n', 'This file\n', 'contains three lines\n']

2.4 Python Object-Oriented Programming:

Like other general-purpose programming languages, Python is also an object-

oriented language since its beginning. It allows us to develop applications using an Object-
Oriented approach.

In Python, we can easily create and use classes and objects.

An object-oriented paradigm is to design the program using classes and objects. The

object is related to real-world entities such as book, house, pencil, etc. The oops concept

focuses on writing the reusable code. It is a widespread technique to solve the problem by

creating objects. Major principles of object-oriented programming system are given below.

➢ Class
➢ Object
➢ Method
➢ Inheritance

NOTES:

90
➢ Polymorphism
➢ Data Abstraction
➢ Encapsulation

Class

The class can be defined as a collection of objects. It is a logical entity that has

some specific attributes and methods. For example: if you have an employee class, then

it should contain an attribute and method, i.e. an email id, name, age, salary, etc.

Syntax

1. class ClassName:

2. <statement-1>

3. .

4. .
5. <statement-N>

Object

The object is an entity that has state and behavior. It may be any real-world object

like the mouse, keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods.

All functions have a built-in attribute doc , which returns the docstring defined in the function

source code.

When we define a class, it needs to create an object to allocate the memory. Consider

the following example.

NOTES:

91
Example:

1. class car:

2. def init (self,modelname, year):

3. [Link] = modelname

4. [Link] = year

5. def display(self):

6. print([Link],[Link])

7.
8. c1 = car("Toyota", 2016)

9. [Link]()

Output:

Toyota 2016

In the above example, we have created the class named car, and it has two attributes
model name and year. We have created a c1 object to access the class attribute. The c1 object
will allocate memory for these values. We will learn more about class and object in the next
tutorial.

Inheritance:
Inheritance is the most important aspect of object-oriented programming, which

simulates the real- world concept of inheritance. It specifies that the child object acquires all

the properties and behaviors of the parent object.

By using inheritance, we can create a class which uses all the properties and

behavior of another class. The new class is known as a derived class or child class, and the

one whose properties are acquired is known as a base class or parent class.

It provides the re-usability of the code.

NOTES:

92
Polymorphism:
Polymorphism contains two words "poly" and "morphs". Poly means many, and

morph means shape. By polymorphism, we understand that one task can be performed in

different ways. For Example - you have a class animal, and all animals speak. But they speak

differently. Here, the "speak" behavior is polymorphic in a sense and depends on the animal.
So, the abstract "animal" concept does not actually "speak", but specific animals (like dogs

and cats) have a concrete implementation of the action "speak".

Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are

nearly synonyms because data abstraction is achieved through encapsulation.

Abstraction is used to hide internal details and show only functionalities.

Abstracting something means to give names to things so that the name captures the core

of what a function or a whole program does.

Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to

restrict access to methods and variables. In encapsulation, code and data are wrapped together

within a single unit from being modified by accident.

Advance OOP

Python Class and Objects

We have already discussed in the previous topic, a class is a virtual entity and can be
seen as a blueprint of an object. The class came into existence when it instantiated. Let's
understand it by an example.

Suppose a class is a prototype of a building. A building contains all the details about
the floor, rooms, doors, windows, etc. we can make as many buildings as we want, based
on these details. Hence, the building can be seen as a class, and we can create as many
objects of this class.

NOTES:

93
On the other hand, the object is the instance of a class. The process of creating an
object can be called instantiation.

we will discuss creating classes and objects in Python. We will also discuss how
a class attribute is accessed by using the object.

Creating classes in Python

In Python, a class can be created by using the keyword class, followed by the class
name. The syntax to create a class is given below.

Syntax

1. class ClassName:

2. #statement_suite

In Python, we must notice that each class is associated with a documentation


string which can be accessed by using <class-name>. doc . A class contains a statement
suite including fields, constructor, function, etc. definition.

Consider the following example to create a class Employee which contains two
fields as Employee id, and name.

The class also contains a function display(), which is used to display the information

of the Employee.

Example

1. class Employee:

2. id = 10

3. name = "Devansh"

4. def display (self):

5. print([Link],[Link])

NOTES:

94
Here, the self is used as a reference variable, which refers to the current class object.
It is always the first argument in the function definition. However, using self is optional
in the function call.

The self-parameter
The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of any
function which belongs to the class.

NOTES:

95

You might also like