Computer Programing
Computer Programing
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.
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.
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
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 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.
#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
NOTES:
7
Example of Variable:
int var1;
int my_var1;
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.
Examples :
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.
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.
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.
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[] = “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.
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:
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:
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.
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.
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.
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
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.
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
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.
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
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.
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.
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)
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.
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.
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.
The C language also comes with a very unusual operator for its programmers – the
conditional operator.
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;
return 0;}
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.
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.
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
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)
return 0;
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) {
A. a= 51>50
NOTES:
28
B. a= 50<51
3. What would be the output obtained out of the program mentioned below?
#include<stdio.h>
int main()
int val=109;
if(val<100)
else
return 0;
NOTES:
29
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.
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 A[10];
2 5 8 44 21 11 7 9 3 1
char B[10];
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:
Types of Arrays:
• One-Dimensional Arrays
• Multi-Dimensional Arrays
Multi-Dimensional Arrays
• 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.
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.
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:
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
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.
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.
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:
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.
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
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.
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
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
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
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.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
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.
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.
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++.
• If you don't want to use Thonny, here's how you can install and run Python
onyour computer.
• 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.
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.
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.
Example:
#This is a comment
#print out Hello
print('Hello')
➢ Multi-line comments
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
3. If you want to create a variable name having two words, use underscore
toseparate them.
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 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.
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.
Output
The value of a is 5
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
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])
Enter a number: 10
>>> num
'10'
Operators
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
NOTES:
56
Subtract right operand from the left or unary
- x - y- 2
minus
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
NOTES:
57
Comparison operators
< Less than - True if left operand is less than the right x<y
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.
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
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.
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
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
Syntax of Function
"""docstring"""
statement(s)
NOTES:
63
Above shown is a function definition that consists of the following components.
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
One or more valid python statements that make up the function body. Statements musthave the
same indentation level (usually 4 spaces).
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 is used to exit a function and go back to the place fromwhere it was called.
Syntax of return
NOTES:
64
Python Function Arguments
In Python, you can define a function that takes variable number of 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.
We can provide a default value to an argument by using the assignment operator (=).
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.
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:
NOTES:
65
What is recursion?
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.
While normal functions are defined using the def keyword in Python, anonymous functions are
defined using the lambda keyword.
NOTES:
66
How to use lambda Functions in Python?
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.
double = lambda x: x * 2
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 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.
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.
>>> 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
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
print(str[0])
print(str[6])
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
print(str[-1])
print(str[-5])
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
print(str[: 3])
print(str[1 : 5 : 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:
# decision making
i = 20;
if (i < 15):
else:
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:
# nested if statement
num = 15
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output:
Positive number
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'
for letter in s:
print(letter)
# or 's'
NOTES:
75
if letter == 'e' or letter == 's':
break
print()
i=0
while True:
print(s[i])
# or 's'
break
i += 1
Output:
g
e
Out of for loop
NOTES:
76
continue
# statement(s)
Flowchart of Continue
Example:
# Python program to
# demonstrate continue
# statement
# loop from 1 to 10
# If i is equals to 6,
# without printing
if i == 6:
continue
else:
NOTES:
77
# otherwise print the value
# of i
Output:
1 2 3 4 5 7 8 9 10
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.
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.
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)
Wed
Sun
Fri
Tue
Mon
Thu
Sat
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)
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)
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”.
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)
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.
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
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
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
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.
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']
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
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
Here is an example of using list comprehension to find the square of the number
in Python.
Example:
numbers = [1, 2, 3, 4, 5]
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:
# Displaying list
print(List)
Output
[1, 2, 3]
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.
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
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.
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')
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.
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.
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.
We can read a file line-by-line using a for loop. This is both efficient and fast.
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']
oriented language since its beginning. It allows us to develop applications using an Object-
Oriented approach.
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
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
NOTES:
91
Example:
1. class car:
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
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.
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
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are
Abstracting something means to give names to things so that the name captures the core
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
Advance OOP
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.
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
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"
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