Professional Documents
Culture Documents
DEPARTMENT : BIOTECHNOLOGY
SEMESTER IV
Unit:4 Python
Python:
About python, features of python, python set up, fundamentals of python, values and data types,
variables, key word, identifier of python, quotations, indentation, multi line statement, input-output and
import function in python, advantages and disadvantages of python.
Unit:5
Fruitful functions in python:
Defining a function, function call, types of function, python function arguments, composition, python
recursion and python lambda function.
UNIT I
Computer Algorithms:
Basics of Algorithms- Pseudo code-Flowchart-Stack-Queues.
Fundamentals in C:
History of C- Basic Structure of a C program- Simple C Program- Character set - C tokens -
Keywords - Identifiers - Constants – Variables – Data Types -Declaration of Variable -
Assigning Values to Variables –Initialization.
COMPUTER ALGORITHMS:
BASIC OF ALGORITHMS
Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its steps
should be clear in all aspects and must lead to only one meaning.
Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs.
Well-Defined Outputs: The algorithm must clearly define what output will be yielded
and it should be well-defined as well.
Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops
or similar.
Feasible: The algorithm must be simple, generic and practical, such that it can be
executed upon with the available resources. It must not contain some future
technology, or anything.
Language Independent: The Algorithm designed must be language-independent, i.e. it
must be just plain instructions that can be implemented in any language, and yet the
output will be same, as expected.
Advantages of Algorithms:
It is easy to understand.
Algorithm is a step-wise representation of a solution to a given problem.
In Algorithm the problem is broken down into smaller pieces or steps hence, it is
easier for the programmer to convert it into an actual program.
Disadvantages of Algorithms:
5. The solution to this problem, in the given constraints: The solution consists of
adding the 3 numbers. It can be done with the help of ‘+’ operator, or bit-wise, or
any other method.
Step 2: Designing the algorithm
Now let’s design the algorithm with the help of above pre -requisites:
Algorithm to add 3 numbers and print their sum:
1. START
2. Declare 3 integer variables num1, num2 and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and
num3 respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of variable sum
7. END
Step 3: Testing the algorithm by implementing it.
Inorder to test the algorithm, let’s implement it in C language.
1. Priori Analysis: “Priori” means “before”. Hence Priori analysis means checking the
algorithm before its implementation. In this, the algorithm is checked when it is
written in the form of theoretical steps. This Efficiency of an algorithm is measured by
assuming that all other factors, for example, processor speed, are constant and have
no effect on the implementation. This is done usually by the algorithm designer. It is
in this method, that the Algorithm Complexity is determined.
2. Posterior Analysis: “Posterior” means “after”. Hence Posterior analysis means
checking the algorithm after its implementation. In this, the algorithm is checked by
implementing it in any programming language and executing it. This analysis helps to
get the actual and real analysis report about correctness, space required, time
consumed etc.
Time Factor: Time is measured by counting the number of key operations such as
comparisons in the sorting algorithm.
Space Factor: Space is measured by counting the maximum memory space required by
the algorithm.
1. Space Complexity: Space complexity of an algorithm refers to the amount of memory
that this algorithm requires to execute and get the result. This can be for inputs,
temporary operations, or outputs.
How to calculate Space Complexity?
The space complexity of an algorithm is calculated by determining following 2
components:
Fixed Part: This refers to the space that is definitely required by the algorithm.
For example, input variables, output variables, program size, etc.
Variable Part: This refers to the space that can be different based on the
implementation of the algorithm. For example, temporary variables, dynamic
memory allocation, recursion stack space, etc.
2. Time Complexity: Time complexity of an algorithm refers to the amount of time that
this algorithm requires to execute and get the result. This can be for normal
operations, conditional if-else statements, loop statements, etc.
How to calculate Time Complexity?
The time complexity of an algorithm is also calculated by determining following 2
components:
Constant time part: Any instruction that is executed just once comes in this part.
For example, input, output, if-else, switch, etc.
Variable Time Part: Any instruction that is executed more than once, say n times,
comes in this part. For example, loops, recursion, etc.
PSEUDO CODE
What is Pseudocode?
You see, computers and human beings are quite different, and therein lies the problem.
The language of a computer is very rigid: you are not allowed to make any mistakes
or deviate from the rules. Even with the invention of high-level, human-readable languages
like JavaScript and Python, it’s still pretty hard for an average human developer to reason
and program in those coding languages.
With pseudocode, however, it’s the exact opposite. You make the rules. It doesn’t
matter what language you use to write your pseudocode. All that matters is
comprehension.
In pseudocode, you don't have to think about semi-colons, curly braces, the syntax
for arrow functions, how to define promises, DOM methods and other core language
principles. You just have to be able to explain what you're thinking and doing.
When you're writing code in a programming language, you’ll have to battle with
strict syntax and rigid coding patterns. But you write pseudocode in a language or form
with which you're very familiar.
Since pseudocode is an informal method of program design, you don’t have to obey
any set-out rules. You make the rules yourself.
Pseudocode acts as the bridge between your brain and computer’s code executor. It allows
you to plan instructions which follow a logical pattern, without including all of the technical
details.
You can get quality code from many platforms online, but you have to learn problem
solving and practice it a lot.
Planning computer algorithms with pseudocode makes you meticulous. It helps you
explain exactly what each line in a software program should do. This is possible because
you are in full control of everything, which is one of the great features of pseudocode.
Example of Pseudocode
1. Derive an email regular expression (regex) to test the user's email address against.
2. Access the user's email from the DOM and store it in a variable. Find and use the right DOM
method for that task.
3. With the email value now accessed and stored, create a conditional statement:
If the email format doesn’t match the rule specified by the regex, access the element with
the myAlert id attribute and pass in the “Invalid Email” message for the user to see.
Else, if the above condition isn’t true and the email address format actually matches with
the regex, check to see if the database already has such an email address. If it already does,
access the element with the myAlert id attribute and pass in the “Email exists!” message for
the user to see.
Now, if both of these conditions aren’t met, (that is the email format matches the regex
and the database doesn’t have such an email address stored yet), push the users email
address into the database and pass in the “Successful!” message for the user to see.
Solving programming problems can be hard. Not only do you have the logical part to
reckon with, but also the technical (code forming) part as well. I recently uncovered a
brilliant and effective formula for solving tricky coding problems.
Here are the steps you can follow to solving programming problems with
pseudocode:
If you fail to properly understand the question, you won’t be able to work through
the problem and figure out the possible steps to take. Once you identify the main
problem to be solved you'll be ready to tackle it.
It helps to represent these problem solving steps in the clearest and most easily
understandable way you can – which is psedocode!
Start solving: open and use tools like Google, Stack Overflow, MDN, and of course
freeCodeCamp! :)
For every step of the problem that you solve, test the output to make sure you’re on the
right path. Keep solving these small problems until you arrive at the final solution.
FLOWCHART
WHAT IS A FLOWCHART?
History
Flowcharts to document business processes came into use in the 1920s and ‘30s. In
1921, industrial engineers Frank and Lillian Gilbreth introduced the “Flow Process Chart”
to the American Society of Mechanical Engineers (ASME). In the early 1930s, industrial
engineer Allan H. Morgensen used Gilbreth’s tools to present conferences on making work
more efficient to business people at his company. In the 1940s, two Morgensen students,
Art Spinanger and Ben S. Graham, spread the methods more widely. Spinanger introduced
the work simplification methods to Procter and Gamble. Graham, a director at Standard
Register Industrial, adapted flow process charts to information processing. In 1947, ASME
adopted a symbol system for Flow Process Charts, derived from the Gilbreths’ original
work.
Also in the late ‘40s, Herman Goldstine and John Van Neumann used flowcharts to
develop computer programs, and diagramming soon became increasingly popular for
computer programs and algorithms of all kinds. Flowcharts are still used for
programming today, although pseudocode, a combination of words and coding language
meant for human reading, is often used to depict deeper levels of detail and get closer to
a final product.
Materials needed: Sticky notes or cards, a large piece of flipchart paper or newsprint, and
marking pens.
1. Define the process to be diagrammed. Write its title at the top of the work surface.
2. Discuss and decide on the boundaries of your process: Where or when does the process
start? Where or when does it end? Discuss and decide on the level of detail to be included
in the diagram.
3. Brainstorm the activities that take place. Write each on a card or sticky note.
4. Arrange the activities in proper sequence.
5. When all activities are included and everyone agrees that the sequence is correct, draw
arrows to show the flow of the process.
6. Review the flowchart with others involved in the process (workers, supervisors,
suppliers, customers) to see if they agree that the process is drawn accurately.
Flowchart Considerations
Don’t worry about drawing the flowchart the "right way." Ultimately, the right way is the
way that helps those involved understand the process.
Identify and involve in the flowcharting process all key people involved with the process.
This includes suppliers, customers, and supervisors. Involve them in the actual
flowcharting sessions by interviewing them before the sessions and/or by showing them
the developing flowchart between work sessions and obtaining their feedback.
Do not assign a "technical expert" to draw the flowchart. People who actually perform the
process should do it.
Types of flowcharts
Different authors describe various types of flowcharts in different terms. These people
include published experts such as Alan B. Sterneckert, Andrew Veronis, Marilyn Bohl and
Mark A. Fryman.
Sterneckert, in his 2003 book Critical Incident Management, listed four popular flowchart
types, framed around the concept of flow controls rather than the flow itself:
Document Flowcharts: These “have the purpose of showing existing controls over
document-flow through the components of a system. … The chart is read from left to
right and documents the flow of documents through the various business units.”
Data Flowcharts: These show “the controls governing data flows in a system. … Data
flowcharts are used primarily to show the channels that data is transmitted through
the system rather than how controls flow.”
System Flowcharts: These “show the flow of data to and through the major components
of a system such as data entry, programs, storage media, processors, and
communication networks.”
Program Flowcharts: These show “the controls placed internally to a program within a
system.”
Veronis , in his 1978 book Microprocessors: Design and Applications, outlined three
flowchart types based on scope and level of detail:
Bohl, in her 1978 book A Guide for Programmers, listed only two:
System Flowchart.
Program Flowchart.
But Fryman, in his 2001 book Quality and Process Improvement, differentiated the types in
multiple ways from more of a business perspective than a computer perspective:
Decision Flowchart.
Logic Flowchart.
Systems Flowchart.
Product Flowchart.
Process Flowchart.
Swimlane Diagram, a.k.a Swimlane Flowchart: To delineate who does what in cross-
team processes.
1. Define your purpose and scope. What do you hope to accomplish? Are you studying the
right things with appropriate start and end points to accomplish that purpose? Be
detailed enough in your research but simple enough in your charting to communicate
with your intended audience.
2. Identify the tasks in chronological order. This might involve talking to participants,
observing a process and/or reviewing any existing documentation. You might write out
the steps in note form, or begin a rough chart.
3. Organize them by type and corresponding shape, such as process, decision, data, inputs
or outputs.
4. Draw your chart, either sketching by hand or using a program such as Lucidchart.
5. Confirm your flowchart, walking through the steps with people who participate in the
process. Observe the process to make sure you haven’t missed anything important to
your purpose.
STACK
Stack is a linear data structure that follows a particular order in which the
operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last
Out).
Mainly the following three basic operations are performed in the stack:
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow
condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in
which they are pushed. If the stack is empty, then it is said to be an Underflow
condition.
Peek or Top: Returns the top element of the stack.
isEmpty: Returns true if the stack is empty, else false.
There are many real-life examples of a stack. Consider the simple example of plates
stacked over one another in a canteen. The plate which is at the top is the first one to be
removed, i.e. the plate which has been placed at the bottommost position remains in the
stack for the longest period of time. So, it can be simply seen to follow the LIFO/FILO order.
push(), pop(), isEmpty() and peek() all take O(1) time. We do not run any loop in any of
these operations.
Applications of stack:
Balancing of symbols
Infix to Postfix /Prefix conversion
Redo-undo features at many places like editors, photoshop.
Forward and backward feature in web browsers
Used in many algorithms like Tower of Hanoi, tree traversals, stock span
problem, histogram problem.
Backtracking is one of the algorithm designing techniques. Some examples of
backtracking are the Knight-Tour problem, N-Queen problem, find your way through
a maze, and game-like chess or checkers in all these problems we dive into someway if
that way is not efficient we come back to the previous state and go into some another
path. To get back from a current state we need to store the previous state for that
purpose we need a stack.
In Graph Algorithms like Topological Sorting and Strongly Connected Components
In Memory management, any modern computer uses a stack as the primary
management for a running purpose. Each program that is running in a computer
system has its own memory allocations
String reversal is also another application of stack. Here one by one each character
gets inserted into the stack. So the first character of the string is on the bottom of the
stack and the last element of a string is on the top of the stack. After Performing the
pop operations on the stack we get a string in reverse order.
Implementation:
There are two ways to implement a stack:
Using array
Using linked list
Stack in Python
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-
In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is
removed from that end only. The insert and delete operations are often called push and
pop.
Implementation
There are various ways from which a stack can be implemented in Python. This article
covers the implementation of a stack using data structures and modules from the Python
library.
Stack in Python can be implemented using the following ways:
list
Collections.deque
queue.LifoQueue
Python’s built-in data structure list can be used as a stack. Instead of push(),
append() is used to add elements to the top of the stack while pop() removes the element
in LIFO order.
Unfortunately, the list has a few shortcomings. The biggest issue is that it can run
into speed issues as it grows. The items in the list are stored next to each other in
memory, if the stack grows bigger than the block of memory that currently holds it, then
Python needs to do some memory allocations. This can lead to some append() calls taking
much longer than other ones.
Python stack can be implemented using the deque class from the collections
module. Deque is preferred over the list in the cases where we need quicker append and
pop operations from both the ends of the container, as deque provides an O(1) time
complexity for append and pop operations as compared to list which provides O( n) time
complexity.
The same methods on deque as seen in the list are used, append() and pop().
Queue module also has a LIFO Queue, which is basically a Stack. Data is inserted
into Queue using the put() function and get() takes data out from the Queue.
There are various functions available in this module:
maxsize – Number of items allowed in the queue.
empty() – Return True if the queue is empty, False otherwise.
full() – Return True if there are maxsize items in the queue. If the queue was
initialized with maxsize=0 (the default), then full() never returns True.
get() – Remove and return an item from the queue. If the queue is empty, wait until an
item is available.
get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
put(item) – Put an item into the queue. If the queue is full, wait until a free slot is
available before adding the item.
put_nowait(item) – Put an item into the queue without blocking.
qsize() – Return the number of items in the queue. If no free slot is immediately
available, raise QueueFull.
QUEUE
Like Stack, Queue is a linear structure which follows a particular order in which
the operations are performed. The order is First In First Out (FIFO). A good example of
queue is any queue of consumers for a resource where the consumer that came first is
served first.
Operations on Queue:
Applications of Queue:
Queue is used when things don’t have to be processed immediately, but have to be
processed in First In First Out order like Breadth First Search. This property of Queue
makes it also useful in following kind of scenarios.
1) When a resource is shared among multiple consumers. Examples include CPU
scheduling, Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate
as sent) between two processes. Examples include IO Buffers, pipes, file IO, etc.
See this for more detailed applications of Queue and Stack.
For implementing queue, we need to keep track of two indices, front and rear. We
enqueue an item at the rear and dequeue an item from the front. If we simply increment
front and rear indices, then there may be problems, the front may reach the end of the
array. The solution to this problem is to increase front and rear in circular manner.
Queue in Python
Like stack, queue is a linear data structure that stores items in First In First Out
(FIFO) manner. With a queue the least recently added item is removed first. A good
example of queue is any queue of consumers for a resource where the consumer that
came first is served first.
Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an
Overflow condition – Time Complexity : O(1)
Dequeue: Removes an item from the queue. The items are popped in the same order
in which they are pushed. If the queue is empty, then it is said to be an Underflow
condition – Time Complexity : O(1)
Front: Get the front item from queue – Time Complexity : O(1)
Rear: Get the last item from queue – Time Complexity : O(1)
Implementation
There are various ways to implement a queue in Python. This article covers the
implementation of queue using data structures and modules from Python library.
Queue in Python can be implemented by the following ways:
list
collections.deque
queue.Queue
Priority Queue
Priority Queue is an abstract data type, which is similar to a queue, however, in the
priority queue, every element has some priority. The priority of the elements in a priority
queue determines the order in which elements are removed from the priority queue.
Therefore all the elements are either arranged in an ascending or descending order.
So, a priority Queue is an extension of the queue with the following properties.
Every item has a priority associated with it.
An element with high priority is dequeued before an element with low priority.
If two elements have the same priority, they are served according to their order in the
queue.
In the below priority queue, an element with a maximum ASCII value will have the
highest priority. The elements with higher priority are served first.
1) Insertion: When a new element is inserted in a priority queue, it moves to the empty
slot from top to bottom and left to right. However, if the element is not in the correct place
then it will be compared with the parent node. If the element is not in the correct order, the
elements are swapped. The swapping process continues until all the elements are placed in
the correct position.
2) Deletion: As you know that in a max heap, the maximum element is the root node.
And it will remove the element which has maximum priority first. Thus, you remove the
root node from the queue. This removal creates an empty slot, which will be further filled
with new insertion. Then, it compares the newly inserted element with all the elements
inside the queue to maintain the heap invariant.
3) Peek: This operation helps to return the maximum element from Max Heap or
minimum element from Min Heap without deleting the node from the priority queue.
1) Ascending Order: As the name suggests, in ascending order priority queue, the
element with a lower priority value is given a higher priority in the priority list. For
example, if we have the following elements in a priority queue arranged in ascending
order like 4,6,8,9,10. Here, 4 is the smallest number, therefore, it will get the highest
priority in a priority queue.
2) Descending order: The root node is the maximum element in a max heap, as you may
know. It will also remove the element with the highest priority first. As a result, the root
node is removed from the queue. This deletion leaves an empty space, which will be filled
with fresh insertions in the future. The heap invariant is then maintained by comparing
the newly inserted element to all other entries in the queue.
HISTORY OF C
There are many programming languages in use today, one of which is C. There are
many offshoots of the C programming language, including Objective-C, C++, and C#. None of
these are the same language. So, how did C begin?
The Beginning
The C programming language came out of Bell Labs in the early 1970s. According to
the Bell Labs paper The Development of the C Language by Dennis Ritchie, “The C
programming language was devised in the early 1970s as a system implementation
language for the nascent Unix operating system. Derived from the typeless language BCPL,
it evolved a type structure; created on a tiny machine as a tool to improve a meager
programming environment.” Originally, Ken Thompson, a Bell Labs employee, desired to
make a programming language for the new Unix platform. Thompson modified the BCPL
system language and created B. However, not many utilities were ever written in B due to
its slow nature and inability to take advantage of PDP-11 features in the operating system.
This led to Ritchie improving on B, and thus creating C.
The development of C was to become the basis for Unix. According to the Bell Labs
paper, “By early 1973, the essentials of modern C were complete. The language and
compiler were strong enough to permit us to rewrite the Unix kernel for the PDP-11 in C
during the summer of the year.” This now meant that C was becoming a strong language
that could, and would be, implemented across many systems. By the middle of the 1970s,
the C-based Unix was used in many projects within the Bell System as well as “a small
group of research-oriented industrial, academic, and government organizations outside
[Bell Labs]".
Currently, we are on the fourth standard of C, known as C18 as it was published in June of
2018 JavaTpoint.
Uses Today
According to Toptal, UNIX operating systems are written in C and most of Linux is
also in C. Also databases such as Oracle Database, MySQL, MS SQL Server, and PostgresSQL
are at least partially written in C. C is the basis of many system kernels. Other programming
languages, like Python and Perl, use compilers or interpreters that are written in C.
C has changed over the years and is still a common language to use in lower level
programs, like kernels. But it is also used for many applications ranging from device drivers
to other programming languages’ compilers or interpreters. The language also made way
for C++, Objective-C, C#, and many more C-based languages that each have their own
speciality.
1. Document section
2. Preprocessor/link Section
3. Definition section
4. Global declaration section
5. Function declaration section
6. Main function
7. User-defined function section
1. Documentation Section
It is the section in which you can give comments to make the program more
interactive. The compiler won’t compile this and hence this portion would not be displyed
on the output screen.
This section involves the use of header files that are to included necessarily
program.
3. Definition section
This section is used to define the global variables to be used in the programs, that
means you can use these variables throughout the program.
This section gives the information about a function that includes, the data type or
the return type, the parameters passed or the arguments.
6.Main function
It is the major section from where the execution of the program begins. The main
section involves the declaration and executable section.
When you want to define your function that fulfills a particular requirement, you
can define them in this section.
SIMPLE C PROGRAM
#include <stdio.h>
int main() {
// printf() displays the string inside
quotation printf("Hello, World!");
return 0;
}
Output
Hello, World!
The #includ is a preprocessor command that tells the compiler to include the contents
of stdio.h (standard input and output) file in the program.
The stdio.h file contains functions such as scanf() and printf() to take input and display
output respectively.
If you use the printf( function without writing #include <stdio.h>, the program will not
compile.
The execution of a C program starts from the main() function.
printf( is a library function to send formatted output to the screen. In this
program, printf() displays Hello, World! text on the screen.
The return 0; statement is the "Exit status" of the program. In simple terms, the
program ends with this statement.
CHARACTER SET
In the C programming language, the character set refers to a set of all the valid
characters that we can use in the source program for forming words, expressions, and
numbers.
The source character set contains all the characters that we want to use for the
source program text. On the other hand, the execution character set consists of the set of
those characters that we might use during the execution of any program. Thus, it is not a
prerequisite that the execution character set and the source character set will be the same,
or they will match altogether.
Just like we use a set of various words, numbers, statements, etc., in any language
for communication, the C programming language also consists of a set of various different
types of characters. These are known as the characters in C. They include digits, alphabets,
special symbols, etc. The C language provides support for about 256 characters.
Every program that we draft for the C program consists of various statements. We
use words for constructing these statements. Meanwhile, we use characters for
constructing these statements. These characters must be from the C language character set.
Let us look at the set of characters offered by the C language.
Types of Characters in C
The C programming language provides support for the following types of characters. In
other words, these are the valid characters that we can use in the C language:
Digits
Alphabets
Main Characters
All of these serve a different set of purposes, and we use them in different contexts in the C
language.
Alphabets
The C programming language provides support for all the alphabets that we use in
the English language. Thus, in simpler words, a C program would easily support a total of
52 different characters- 26 uppercase and 26 lowercase.
Digits
The C programming language provides the support for all the digits that help in
constructing/ supporting the numeric values or expressions in a program. These range
from 0 to 9, and also help in defining an identifier. Thus, the C language supports a total of
10 digits for constructing the numeric values or expressions in any program
Special Characters
We use some special characters in the C language for some special purposes, such as
logical operations, mathematical operations, checking of conditions, backspaces, white
spaces, etc.
We can also use these characters for defining the identifiers in a much better way.
For instance, we use underscores for constructing a longer name for a variable, etc.
White Spaces
Blank Spaces
Carriage Return
Tab
New Line
C TOKENS
Classification of tokens in C
o Keywords in C
o Identifiers in C
o Strings in C
o Operators in C
o Constant in C
o Special Characters in C
Keywords
Keywords in C can be defined as the pre-defined or the reserved words having its
own importance, and each keyword has its own functionality. Since keywords are the pre-
defined words used by the compiler, so they cannot be used as the variable names. If the
keywords are used as the variable names, it means that we are assigning a different
meaning to the keyword, which is not allowed.
Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc.
Identifiers in C are the user-defined words. It can be composed of uppercase letters,
lowercase letters, underscore, or digits, but the starting letter should be either an
underscore or an alphabet. Identifiers cannot be used as keywords. Rules for constructing
identifiers in C are given below:
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can
say that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to
read.
Strings in C
Strings in C are always represented as an array of characters having null character '\
0' at the end of the string. This null character denotes the end of the string. Strings in C are
enclosed within double quotes, while characters are enclosed within single characters. The
size of a string is a number of characters that the string contains.
char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.
char a[] = "javatpoint"; // The compiler allocates the memory at the run time.
Operators in C
Operators in C is a special symbol used to perform the functions. The data items on which
the operators are applied are known as operands. Operators are applied between the
operands. Depending on the number of operands, operators are classified as follows:
Unary Operator
A unary operator is an operator applied to the single operand. For example: increment
operator (++), decrement operator (--), sizeof, (type)*.
Binary Operator
The binary operator is an operator applied between two operands. The following is the list
of the binary operators:
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Conditional Operators
o Assignment Operator
o Misc Operator
Constants in C
A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.
Special characters in C
Some special characters are used in C, and they have a special meaning which cannot be
used for another purpose.
o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when
printing the value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes
that we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an operator
for multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.
KEYWORDS
A keyword is a reserved word. You cannot use it as a variable name, constant name,
etc. There are only 32 reserved words (keywords) in the C language.
C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned
IDENTIFIERS
C identifiers represent the name in the C program, for example, variables, functions,
arrays, structures, unions, labels, etc. An identifier can be composed of letters such as
uppercase, lowercase letters, underscore, digits, but the starting letter should be either an
alphabet or an underscore. If the identifier is not used in the external linkage, then it is
called as an internal identifier. If the identifier is used in the external linkage, then it is
called as an external identifier.
ten numerical digits (0-9) that represent the identifiers. There is a total of 63
alphanumerical characters that represent the identifiers.
Types of identifiers
o Internal identifier
o External identifier
Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal identifier.
The internal identifiers can be local variables.
External Identifier
If the identifier is used in the external linkage, then it is known as an external identifier.
The external identifiers can be function names, global variables.
CONSTANTS
A constant is a value or variable that can't be changed in the program, for example: 10, 20,
'a', 3.4, "c programming" etc.
List of Constants in C
Constant Example
Primary constants − Integer, float, and character are called as Primary constants.
1. const keyword
2. #define preprocessor
C const keyword
C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define
preprocessor directive later.
VARIABLES
A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
type variable_list;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
1. int a;
2. int _ab;
3. int a30;
1. int 2;
2. int a b;
3. int long;
Types of Variables in C
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
void function1(){
int x=10;//local variable
}
Global Variable
A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.
Static Variable
A variable that is declared with the static keyword is called static variable.
void function1(){
int x=10;//local variable
tatic int y=10;//static variable
x=x+1;
y=y+1; printf("%d,
%d",x,y);
}
If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We
can explicitly declare an automatic variable using auto keyword.
void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
External Variable
We can share a variable in multiple C source files by using an external variable. To declare
an external variable, you need to use extern keyword.
DATA TYPES
Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. Let us briefly
describe them one by one:
Following are the examples of some very common data types used in C:
char: The most basic data type in C. It stores a single character and requires a single
byte of memory in almost all compilers.
int: As the name suggests, an int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with
single precision.
double: It is used to store decimal numbers (numbers with floating point value) with
double precision.
The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating
system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
float 4 byte
double 8 byte
1 Basic Types
They are arithmetic types and are further classified into: (a) integer types
and (b) floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define variables that
can only assign certain discrete integer values throughout the program.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d)
Union types and (e) Function types.
The void type specifies that no value is available. It is used in three kinds of situations −
1
Function returns as void
There are various functions in C which do not return any value or you can
say they return void. A function with no return value has the return type as
void. For example, void exit (int status);
3 Pointers to void
A pointer of type void * represents the address of an object, but not its type.
For example, a memory allocation function void *malloc( size_t size
); returns a pointer to void which can be casted to any data type.
DECLARATION OF VARIABLE
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and layout of
the variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase letters
are distinct because C is case-sensitive. Based on the basic types explained in the previous
chapter, there will be the following basic variable types −
1 char
Typically a single octet(one byte). It is an integer type.
2 int
The most natural size of integer for the machine.
3 float
A single-precision floating point value.
4 double
A double-precision floating point value.
5 void
Represents the absence of type.
C programming language also allows to define various other types of variables, which we
will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc.
For this chapter, let us study only basic variable types.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler
to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables are
undefined.
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with
the given type and name so that the compiler can proceed for further compilation without
requiring the complete detail about the variable. A variable definition has its meaning at
the time of compilation only, the compiler needs actual variable definition at the time of
linking the program.
A variable declaration is useful when you are using multiple files and you define your
variable in one of the files which will be available at the time of linking of the program.
You will use the keyword extern to declare a variable at any place. Though you can declare
a variable multiple times in your C program, it can be defined only once in a file, a function,
or a block of code.
Example
Try the following example, where variables have been declared at the top, but they
have been defined and initialized inside the main function −
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result
− value of c : 30
value of f : 23.333334
The same concept applies on function declaration where you provide a function name at
the time of its declaration and its actual definition can be given anywhere else. For
example −
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
An undefined value is different from a NULL value. If you attempt to use a variable
with an undefined value within the SPL routine, you receive an error.
You can assign a value to a routine variable in any of the following ways:
INITIALIZATION
In computer programming, initialization (or initialisation) is the assignment of an
initial value for a data object or variable. The manner in which initialization is performed
depends on programming language, as well as type, storage class, etc., of an object to be
initialized. Programming constructs which perform initialization are typically
called initializers and initializer lists. Initialization is distinct from (and preceded
by) declaration, although the two can sometimes be conflated in practice. The complement
of initialization is finalization, which is primarily used for objects, but not variables.
Initialization is done either by statically embedding the value at compile time, or
else by assignment at run time. A section of code that performs such initialization is
generally known as "initialization code" and may include other, one-time-only, functions
such as opening files; in object-oriented programming, initialization code may be part of
a constructor (class method) or an initializer (instance method). Setting a memory location
to hexadecimal zeroes is also sometimes known as "clearing" and is often performed by
an exclusive or instruction (both operands specifying the same variable), at machine
code level, since it requires no additional memory access.
Initializer
int i = 0;
int k[4] = {0, 1};
char tx[3] = 'a';
char ty[2] = 'f';
struct Point {int x; int y;} p = { .y = 13, .x = 7 };
C++ examples:
int i2(0);
int j[2] = {rand(), k[0]};
MyClass* xox = new MyClass(0, "zaza");
point q = {0, i + 1};
Initializer list[edit]
In C++, a constructor of a class/struct can have an initializer list within the definition but
prior to the constructor body. It is important to note that when you use an initialization list,
the values are not assigned to the variable. They are initialized. In the below example, 0 is
initialized into re and im. Example:
struct IntComplex
{ IntComplex() : re(0), im(0)
{}
int re;
int im;
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College
};
Sometimes the term "initializer list" is also used to refer to the list of expressions in the
array or struct initializer.
C++11 provides for a more powerful concept of initializer lists, by means of a template,
called std::initializer_list.
Default initialization[edit]
Data initialization may occur without explicit syntax in a program to do so. For example,
if static variables are declared without an initializer, then those of primitive data types are
initialized with the value of zero of the corresponding type, while static objects of class type
are initialized with their default constructors.
UNIT II
C OPERATORS
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operator direction to be evaluated; it may be left to right or
right to left.
int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before
+ (additive operator).
ARITHMETIC OPERATORS
• You can use an arithmetic operator with one or two arguments to add, subtract,
multiply, and divide numeric values.
i. 5 + 3 = 8
ii. 5 – 3 = 2
iii. 5 * 3 = 15
/3
=1
v. 5
%3
=2
Example
i. 2+5*4–3=?
ii. ii. (2 + 5) * (4 – 3) = ?
i. z=x+y
ii. no1 = x – y
iii. age = a * b + c
iv. velocity = distance / time
v. force = mass * acceleration
vi. count = count + 1
Integer Arithmetic
• When an arithmetic operation is performed on two whole numbers or integers than
such an operation is called as integer arithmetic.
Example
Let x = 27 and y = 5 be two integer numbers. Then the integer operation leads to the
following results:
i. x + y = 32
ii. x – y = 22
iii. x * y = 115
iv. x%y=2
v. x/y=5
Floating-point Arithmetic
Floating-point Arithmetic
Example
i. x + y = 18.0
ii. x – y = 10.0
iii. x * y = 56.0
iv. x / y = 3.50
RELATIONAL OPERATORS
• This expression will have a value of TRUE if the variable x is less than 5; otherwise the
value of the expression will be FALSE.
• A simple relational expression contains only one relational operator and takes the
following form:
Where exp1 and exp2 are expressions, which may be simple constants, variables or
combination of them.
Example:
i. x<y = True
ii. (x + 2) > (y * 2) = False
iii. (x + 3) <= y = True
iv. x != y = True
v. y > (3 + x) = False
LOGICAL OPERATORS
Operator Name
|| Logical OR
! Logical NOT
Logical AND
• This operator is used to evaluate two conditions or expressions with relational operators
simultaneously.
• If both the expressions to the left and to the right of the logical operator is true then the
whole compound expression is true.
Example:
The expression to the left is a > b and that on the right is x == 10, the whole expression is
true only if both expressions are true i.e., if a is greater than b and x is equal to 10.
Example:
Given a = 2, b = 3 and c = 5, evaluate the following logical expressions:
Logical OR
• The logical OR is used to combine two expressions or the condition evaluates to true if
any one of the 2 expressions is true.
• The expression evaluates to true if any one of them is true or if both of them are true.
Example:
(a < m) || (a < n)
The expression evaluates to true if any one of them is true or if both of them are true.
Example:
i. (a > b) || (c != 5) = False
ii. (a < b) || (c < b) = True
Logical NOT
• The logical NOT operator takes single expression and evaluates to true if the expression is
false and evaluates to false if the expression is true.
Exp1 !Exp1
True False
False True
Example:
! (x >= y)
The NOT expression evaluates to true only if the value of x is neither greater than or equal
to y
Example:
• The increment operator ++ adds the value 1 to the current value of operand.
• The decrement operator – – subtracts the value 1 from the current value of operand.
Example:
• A prefix operator first adds 1 to the operand and then the result is assigned to the
variable on the left.
• On the other hand, a postfix operator first assigns the value to the variable on the left and
then increments the operand.
Example 1:
x=4
y = ++x
PRINT x
PRINT y
Example 2:
x=3
y = x++
PRINT x
PRINT y
ASSIGNMENT OPERATORS
There are different kinds of the operators, such as arithmetic, relational, bitwise,
assignment, etc., in the C programming language. The assignment operator is used to assign
the value, variable and function to another variable. Let's discuss the various types of the
assignment operators such as =, +=, -=, /=, *= and %=.
It is the operator used to assign the right side operand or variable to the left side variable.
Syntax
int a = 5;
or int b = a;
ch = 'a';
Program1.c
#include <stdio.h>
#include <conio.h>
int main ()
{
// initialize variables
int n1, n2, c, x, y;
n1 = 5;
n2 = n1;
c = n1 + n2;
x = 20 / 4 * 2 + 5;
printf (" \n The value of n1: %d", n1);
printf (" \n The value of n2: %d", n2);
printf (" \n The value of c: %d", c);
printf (" \n The value of x: %d", x);
return 0;
}
Output
The operator is used to add the left side operand to the left operand and then assign results
to the left operand.
Syntax
A += B;
Or
A = A + B;
Program2.c
#include <stdio.h>
#include <conio.h>
int main ()
{
// initialize variables
int n1, n2, c;
n1 = 5;
n2 = 10;
n2 += n1;
printf (" \n The value of n1: %d", n1);
printf (" \n The value of n2: %d", n2);
return 0;
}
Output
of 5 b: 15
The value of a: 5
The value of b: 15
The operator is used to subtract the left operand with the right operand and then assigns
the result to the left operand.
Syntax
A -= B;
Or
A = A - B;
Let's create a program to use the Subtract and Assign (-=) operator in C.
Program3.c
#include <stdio.h>
#include <conio.h>
int main ()
{
// initialize variables
return 0;
}
Output
The operator is used to multiply the left operand with the right operand and then assign
result to the left operand.
Syntax
A *= B;
Or
A = A * B;
Let's create a program to use the multiply and assign operator (*=) in C.
The operator is used to multiply the left operand with the right operand and then assign
result to the left operand.
Syntax
A *= B;
Or
A = A * B;
Let's create a program to use the multiply and assign operator (*=) in C.
CONDITIONAL OPERATOR
o In the above syntax, the expression1 is a Boolean condition that can be either true
or false value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // condition
al operator
return 0;
}
In the above code, we are taking input as the 'age' of the user. After taking input, we have
applied the condition by using a conditional operator. In this condition, we are checking the
age of the user. If the age of the user is greater than or equal to 18, then the statement1 will
execute, i.e., (printf("eligible for voting")) otherwise, statement2 will execute, i.e.,
(printf("not eligible for voting")).
If we provide the age of user below 18, then the output would be:
If we provide the age of user above 18, then the output would be:
As we can observe from the above two outputs that if the condition is true, then the
statement1 is executed; otherwise, statement2 will be executed.
Till now, we have observed that how conditional operator checks the condition and based
on condition, it executes the statements. Now, we will see how a conditional operator is
used to assign the value to a variable.
#include <stdio.h>
int main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}
In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value
to the 'a' variable. After the declaration, we are assigning value to the 'b' variable by using
the conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a 3 value
otherwise 2.
Output
The above output shows that the value of 'b' variable is 3 because the value of 'a' variable is
equal to 5.
As we know that the behavior of conditional operator and 'if-else' is similar but they
have some differences. Let's look at their differences.
ARITHMETIC EXPRESSIONS
The plus sign (+) is used to add two values, the minus sign (-) to subtract one value
from another, the asterisk(*) to multiply two values, the division (/) to divide a value and
the modulus (%) to obtain the reminder of integer division. These are known as binary
operators since they operate on two values or variables.
result = x - y;
numsquare = x * x;
Notice the equal sign (=) in the above expressions, it is known as the assignment
operator. It assigns the value on the right hand side of the equal sign to the variable on the
left hand side.
In the last expression, parentheses are used to perform a certain operation first.
This is because in C, operators follow a precedence rule. *, / and % have a higher
precedence over + and -. Hence to override the precedence, parentheses should be used.
Expressions having operators of the same precedence are generally evaluated from left to
right. Another point to note is that in an expression which involves division, care should be
taken to avoid a division by zero, since this results in infinity or an abnormal value. In
Chapter 5 on control statements, we will see how a check can be done before a division
occurs and prevent such operations.
Program
#include
main()
int var2 = 2;
int var4 = 8;
int result;
EVALUATION OF EXPRESSION
Evaluate an expression represented by a String. The expression can contain
parentheses, you can assume parentheses are well-matched. For simplicity, you can
assume only binary operations allowed are +, -, *, and /. Arithmetic Expressions can be
written in one of three forms.
Infix Notation: Operators are written between the operands they operate on, e.g. 3 + 4.
Prefix Notation: Operators are written before the operands, e.g + 3 4
Postfix Notation: Operators are written after operands.
Infix Expressions are harder for Computers to evaluate because of the additional
work needed to decide precedence. Infix notation is how expressions are written and
recognized by humans and, generally, input to programs. Given that they are harder to
evaluate, they are generally converted to one of the two remaining forms. A very well
known algorithm for converting an infix notation to a postfix notation is Shunting Yard
Algorithm by Edgar Dijkstra. This algorithm takes as input an Infix Expression and
produces a queue that has this expression converted to postfix notation. The same
algorithm can be modified so that it outputs the result of the evaluation of expression
instead of a queue. The trick is using two stacks instead of one, one for operands, and one
for operators. The algorithm was described succinctly on http://www.cis.upenn.edu/
Example
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
When you compile and execute the above program, it produces the following result
−
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion
It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long
long is implicitly converted to float).
#include<stdio.h>
int main()
// value of 'a' is 97
x = x + y;
float z = x + 1.0;
return 0;
Output:
x = 107, z = 108.000000
This process is also called type casting and it is user defined. Here the user can type cast
the result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.
#include<stdio.h>
int main()
double x = 1.2;
return 0;
Output:
sum = 2
Advantages of Type Conversion
This is done to take advantage of certain features of type hierarchies or type
representations.
It helps us to compute expressions containing variables of different data types.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Example Code
#include <stdio.h>
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
Output
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
MATHEMATICAL FUNCTIONS
C Math
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.
1) ceil(number) rounds up the given number. It returns the integer value which is
greater than or equal to given number.
2) floor(number) rounds down the given number. It returns the integer value which is
less than or equal to given number.
C Math Example
Let's see a simple example of math functions found in math.h header file.
#include<stdio.h>
#include <math.h>
int main(){ printf("\n
%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
return 0;
}
400
4 Output:
93.7K
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
12
.000000
3.000000
ARRAYS
INTRODUCTION
An array is a collection of items stored at contiguous memory locations. The idea is
to store multiple items of the same type together. This makes it easier to calculate the
position of each element by simply adding an offset to a base value, i.e., the memory
location of the first element of the array (generally denoted by the name of the array).
The base value is index 0 and the difference between the two indexes is the offset.
For simplicity, we can think of an array as a fleet of stairs where on each step is placed a
value (let’s say one of your friends). Here, you can identify the location of any of your
friends by simply knowing the count of the step they are on.
Remember: “Location of next index depends on the data type we use”.
Array’s size
In C language, array has a fixed size meaning once the size is given to it, it cannot be
changed i.e. you can’t shrink it neither can you expand it. The reason was that for
expanding, if we change the size we can’t be sure ( it’s not possible every time) that we
get the next memory location to us as free. The shrinking will not work because the
array, when declared, gets memory statically allocated, and thus compiler is the only
one can destroy it.
Types of indexing in an array:
0 (zero-based indexing): The first element of the array is indexed by a subscript of 0.
1 (one-based indexing): The first element of the array is indexed by the subscript of 1.
n (n-based indexing): The base index of an array can be freely chosen. Usually,
programming languages allowing n-based indexing also allow negative index values,
and other scalar data types like enumerations, or characters may be used as an array
index.
#include <iostream>
using namespace std;
int main()
{
// Creating an integer array named arr of size 10.
int arr[10];
// accessing element at 0 index and setting its value
// to 5.
arr[0] = 5;
// access and print value at 0 index we get the output
// as 5.
cout << arr[0];
return 0;
}
You can’t change the size i.e. once you have declared the array you can’t change its
size because of static memory allocation. Here Insertion(s) and deletion(s) are difficult as
the elements are stored in consecutive memory locations and the shifting operation is
costly too.
Now if take an example of implementation of data structure Stack using array there
are some obvious flaw.
Let’s take the POP operation of the stack. The algorithm would go something like this.
1. Check for the stack underflow
2. Decrement the top by 1
So there what we are doing is that, the pointer to the topmost element is
decremented means we are just bounding our view actually that element stays there
taking up of the memory space. If you have any primitive datatype then it might be ok but
the object of an array would take a lot of memory.
Examples –
// A character array in C/C++/Java
char arr1[] = {'g', 'e', 'e', 'k', 's'};
000
4.000000
One
di45751
16.0000
00dfd
27.000000
12
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College
The variable allows us to store a single value at a time, what if we want to store roll
no. of 100 students? For this task, we have to declare 100 variables, then assign values to
each of them. What if there are 10000 students or more? As you can see declaring that
many variables for a single entity (i.e student) is not a good idea. In a situation like these
arrays provide a better way to store data.
What is an Array?
An array is a collection of one or more values of the same type. Each value is called
an element of the array. The elements of the array share the same variable name but each
element has its own unique index number (also known as a subscript). An array can be of
any type, For example: int, float, char etc. If an array is of type int then it's elements must be
of type int only.
Conceptually you can think of a one-dimensional array as a row, where elements are stored
one after another.
size: Number of elements an array can hold. here are some example of array declarations:
1int num[100];
2float temp[20];
3char ch[50];
num is an array of type int, which can only store 100 elements of type int.
temp is an array of type float, which can only store 20 elements of type float.
ch is an array of type char, which can only store 50 elements of type char.
1 #define SIZE 10
2
3 int main()
4{
5 int size = 10;
6
7 int my_arr1[SIZE]; // ok
8 int my_arr2[size]; // not allowed until C99
9 // ...
10}
Note: Until C99 standard, we were not allowed to use variables to specify the size of the
array. If you are using a compiler which supports C99 standard, the above code would
compile successfully. However, If you're using an older version of C compiler like Turbo C+
+, then you will get an error.
The use of symbolic constants makes the program maintainable, because later if you want
to change the size of the array you need to modify it at once place only i.e in
the #define directive.
DECLARATION OF ARRAY
An "array declaration" names the array and specifies the type of its elements. It can
also define the number of elements in the array. A variable with array type is considered a
pointer to the type of the array elements.
Syntax
declaration:
declaration-specifiers init-declarator-listopt ;
init-declarator-list:
init-declarator
init-declarator-list , init-declarator
init-declarator:
declarator
declarator = initializer
declarator:
pointeropt direct-declarator
The first form defines an array variable. The constant-expression argument within
the brackets specifies the number of elements in the array. The constant-expression,
if present, must have integral type, and a value larger than zero. Each element has the
type given by type-specifier, which can be any type except void. An array element
cannot be a function type.
The second form declares a variable that has been defined elsewhere. It omits
the constant-expression argument in brackets, but not the brackets. You can use this
form only if you previously have initialized the array, declared it as a parameter, or
declared it as a reference to an array explicitly defined elsewhere in the program.
In both forms, direct-declarator names the variable and can modify the variable's type. The
brackets ([ ]) following direct-declarator modify the declarator to an array type.
Type qualifiers can appear in the declaration of an object of array type, but the qualifiers
apply to the elements rather than the array itself.
You can declare an array of arrays (a "multidimensional" array) by following the array
declarator with a list of bracketed constant expressions in this form:
You can define arrays of pointers to various types of objects by using complex declarators,
as described in Interpreting More Complex Declarators.
Arrays are stored by row. For example, the following array consists of two rows with three
columns each:
CCopy
char A[2][3];
The three columns of the first row are stored first, followed by the three columns of the
second row. This means that the last subscript varies most quickly.
Examples
float matrix[10][15];
The two-dimensional array named matrix has 150 elements, each having float type.
struct {
float x, y;
} complex[100];
This is a declaration of an array of structures. This array has 100 elements; each element is
a structure containing two members.
This statement declares the type and name of an array of pointers to char. The actual
definition of name occurs elsewhere.
Microsoft Specific
The type of integer required to hold the maximum size of an array is the size of size_t.
Defined in the header file STDDEF.H, size_t is an unsigned int with the range 0x00000000
to 0x7CFFFFFF.
data_type array_name[size1][size2]....[sizeN];
Multi dimensional arrays are the arrays with a single variable name and more than
one subscript. Declaration is as like one dimensional but only change is there in the
subscript. It need data type array name and the subscript (indices).
int multi[10][10][10];
here the multidimensional array ‘multi’ is an integer array the sizes are given as the
subscript.
Matrix
A two dimensional array is called a matrix. Thus it is two dimensional it has two
subscripts. A matrix is used to store a table of values. As it is similar to a table a matrix has
rows and columns. Thus the first subscript refers as the rows and second index as the
columns.
Syntax :
Data-type matrix-name[rows][columns];
Example :
int a[2][2];
here a is a matrix with 2 rows and 2 columns. We can say ‘a’ is a 2 x 2 (read 2 by two)
matrix.
Column 0 Column 1
A matrix can be assigned values by specifying bracketed values for each row as Follows.
Here the values enclosed in brackets denotes the rows of the matrix.
0 1
2 3
For accessing matrix variables we use the subscripts along with the name of the
matrix. But make sure that we number the values of rows and columns from 0. In the
above example to access the value 1 we use a[0][1] that is the position of 1 is in the 0 th row
and the 1st column.
The dynamic initialization of matrix, need two loops one for row values and another
for column values.
Program to assign the values to the matrix and print that matrix
#include <stdio.h>
void main()
{
int i, j, m, n, a[10][10];
0 10 8
4 9 12
The values are assigned like this and it displays the matrix as
0 10 8
4 9 12
Operations on matrices
Addition
Subtraction
Multiplication
Transpose etc.
For the first three we need two or more arrays , transpose is done on that same matrix, it is
changing the values on rows to columns and columns as rows.
#include <stdio.h>
int main()
{
int m, n, i, j, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix");
for (i = 0 ; i < m ; i++ )
{
for ( j= 0 ; j < n ; j++)
{
scanf("%d", &first[i][j]);
}
}
printf("Enter the elements of second matrix ");
for ( i = 0 ; i< m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
scanf("%d", &second[c][d]);
}
}
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
sum[i][j] = first[i][j] + second[i][j];
}
printf("Sum is") ;
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
printf("%d\t", sum[i][j]);
}
printf("\n");
}
}
first
10 5
20 10
second
9 10
3 25
sum
19 15
23 35
Two – dimensional array is the simplest form of a multidimensional array. We can see a
two – dimensional array as an array of one – dimensional array for easier understanding.
data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.
We can declare a two-dimensional integer array say ‘x’ of size 10,20 as:
int x[10][20];
Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the
row number and ‘j’ is the column number.
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where
the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1).
A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below:
Initializing Two – Dimensional Arrays: There are two ways in which a Two-Dimensional
array can be initialized.
First Method:
Better Method:
int x[2][1];
The above example represents the element present in the third row and second column.
Note: In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for row
index 2 row number is 2+1 = 3.
To output all the elements of a Two-Dimensional array we can use nested for loops. We will
require two for loops. One to traverse the rows and another to traverse columns.
// Two-Dimensional array
#include<iostream>
int main()
return 0;
Output:
Element at x[0][0]: 0
Element at x[0][1]: 1
Element at x[1][0]: 2
Element at x[1][1]: 3
Element at x[2][0]: 4
Element at x[2][1]: 5
Three-Dimensional Array
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
{
cout << "Element at x[" << i << "][" << j
<< "][" << k << "] = " << x[i][j][k]
<< endl;
}
}
}
return 0;
}
Output:
Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11
In similar ways, we can create arrays with any number of dimensions. However,
the complexity also increases as the number of dimensions increases.
The most used multidimensional array is the Two-Dimensional Array.
UNIT III
DECISION MAKING, BRANCHING, LOOPING
Decision Making and Branching:
Introduction to if, if...else, nesting of if ...else statements- else if ladder – The switch
statement, The ?: Operator – The goto Statement.
Decision Making and Looping:
Introduction - while loop –do loop –do while lopp –for loop –Nested Loops–break– continue–goto–
exit–return.
If statement
Switch statement
IF STATEMENT
‘If’ is the most powerful decision making statement in C language. Thus it is used to control
the execution of statements. ‘If’ is used along with an expression. It is a two way
branching or decision making statement.
Syntax :
if(test expression)
{
Body of if;
}
Using an ‘if’ a computer first evaluate the expression and if it is true the body of if is
executed which means the flow of control passes to the if’s body, or if the test condition
is false then the flow of control passes to the immediate step next to if’s body. If there are
more than one step in the body of ‘if’ they are normally written with in brackets ‘{ }’ to
denote it is the body of ‘if’.
The test expression will return a Boolean value which is a’0’ or ‘1’. Here 1 is ‘true’ and 0
denotes it is ‘false’.
Example:
if(age>55){
printf(“ Retired”);
}
Depending upon the complexity and conditions to be tested if can be further subdivided.
Simple if
if…..else
nested if…else
if…else…if
ladder simple if
statement
if(test expression)
{
Body of if;
}
Statement X;
The body of ‘if’ may be a single statement or group of statements. When the test expression
returns a true value these body of if is executed. If the condition is false the flow of control
passes to the statement X. The statement X will be executed in both cases.
IF ELSE
if(condition) {
// Statements inside body of if
}
else {
//Statements inside body of else
}
In this program user is asked to enter the age and based on the input, the if..else
statement checks whether the entered age is greater than or equal to 18. If this condition
meet then display message “You are eligible for voting”, however if the condition doesn’t
meet then display a different message “You are not eligible for voting”.
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible for voting");
}
return 0;
}
Output:
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
printf("You are eligible for voting");
else
printf("You are not eligible for voting");
return 0;
}
When an if else statement is present inside the body of another “if” or “else” then
this is called nested if else.
Syntax of Nested if else statement:
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to var2\n");
//Nested if else
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:
NESTED IF STATEMENT
It is used when a series of decisions are involved and have to use more than one
if…else statement.
Syntax :
if(condition 1)
{
if(condition 2)
{
body of if;
}
else
{
Body of else;
}
}
else
{
Body of else;
}
Statement x;
Example :
if( a>b)
{
if(a>c)
printf(“ a is greater”);
else
printf(“ c is greater”);
}
else
{
if(b>c)
{
Printf(“b is greater”);
}
else
{
Printf(“c is greater”);
}
}
ELSE IF LADDER
This is the most general way of writing a multi-way decision.
Syntax
Refer the syntax given below −
if (condition1)
stmt1;
else if (condition2)
stmt2;
-----
-----
else if (condition n)
stmtn;
else
stmt x;
Algorithm
Refer the algorithm given below −
START
Print b is largest
iii. else if(c>d && c>a && c>b)
Print c is largest
iv. else
print d is largest
STOP
Example
Following is the C program to execute Else If Ladder conditional operators −
#include<stdio.h
> void main (){
int a,b,c,d;
printf("Enter the values of a,b,c,d:
"); scanf("%d%d%d
%d",&a,&b,&c,&d); if(a>b && a>c
&& a>d){
printf("%d is the largest",a);
}else if(b>c && b>a && b>d)
{ printf("%d is the
largest",b);
}else if(c>d && c>a && c>b)
{ printf("%d is the
largest",c);
}else{
Output
You will see the following output −
Syntax :
switch(expression)
{
case constant1 :
block1;
break;
case constant2 :
block2;
break;
case constant n:
block n;
break;
.
.
.
default:
default block;
break;
}
statement x;
When the ‘switch’ is executed the value of the expression is successfully compared
against the case’s constants. When a case constant is found the block of codes associated
with it is executed, and if till the last case constant no match is found the block
associated with the default case is executed. The default is an optional case . If it is not
present and no matches are found then control passes to the statement x.
Example :
int num;
printf(“enter a number”);
scanf(‘%d”,&num);
switch(num)
{
case 1:
printf(“Sunday”);
break;
case 2:
printf(“Monday”);
break;
case 3:
printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
case 5:
printf(“Thursday”);
break;
case 6:
printf(“Friday”);
break;
case 7:
printf(“Saturday”);
break;
default:
printf(“wrong choice”);
break;
}
Here according to numbers from 1 to 7 the corresponding day is displayed. If we input any
number other than 1 to 7 then the default case is executed.
THE ?: OPERATOR
?: is a ternary operator that is part of the syntax for basic conditional expressions in
several programming languages. It is commonly referred to as the conditional
operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value
of
a is true, and otherwise to c . One can read it aloud as "if a then b otherwise c".
if (a < b) {
c = a;
}
else {
c = b;
}
printf("%d", c);
This example takes more than 10 lines, but that isn’t necessary. You can write the above
program in just 3 lines of code using a ternary operator.
Syntax
c = (a < b) ? a : b;
printf("%d", c);
10
int a = 1, b = 2, ans;
if (a == 1) {
if (b == 2) {
ans = 3;
} else {
ans = 5;
}
} else {
ans = 0;
}
printf ("%d\n", ans);
Here's the code above rewritten using a nested ternary operator:
int a = 1, b = 2, ans;
ans = (a == 1 ? (b == 2 ? 3 : 5) : 0);
printf ("%d\n", ans);
GOTO STATEMENT
The goto statement is known as jump statement in C. As the name suggests, goto is
used to transfer the program control to a predefined label. The goto statment can be used
to repeat some part of the code for a particular condition. It can also be used to break the
multiple loops which can't be done by using a single break statement. However, using goto
is avoided these days since it makes the program less readable and complecated.
Syntax:
1. label:
2. //some part of the code;
3. goto label;
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
Output:
When the control statement is placed after the body of the loop then such loops are
called as exit controlled loop.
In this the body of the loop is executed first then the test condition in the control statement
is checked.
In the beginning the loop control variable is initialized after that step2, step3 and
step4 are carried out till specified test condition becomes false.
The test may be either to determine whether the loop has been repeated the specified
number of times or to determine whether a particular condition has been met. The C
language provides 3 loop structures.
1. while loop.
2. do loop.
3. for loop.
WHILE LOOP
While loop is also known as a pre-tested loop. In general, a while loop allows a part
of the code to be executed multiple times depending upon a given boolean condition. It can
be viewed as a repeating if statement. The while loop is mostly used in the case where the
number of iterations is not known in advance.
1. while(condition){
2. //code to be executed
3. }
Let's see the simple program of while loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
This is similar to for loops, but much simpler than it. While and do/while loops have
similar functionality with small difference. The while loop checks for the condition/s and
executes the set of statements within it until the condition is false. It does not require any
initial values or increment factor. It always gets executed until the condition is false.
In while loop, condition is checked at the beginning of the loop whereas in do/while
loop condition is checked at the end of the loop. Hence in while loop, if the condition is false
at the beginning itself, then it will not execute its body and comes out of the loop. But in
do/while loop as the condition is checked at the end, it will execute body of it at least once.
The general syntax for while and do/while loops are given below :
while (condition/s)
{ Expression /
statements;
do{
Expression / statements;
} while (condition/s);
Like in for loops, these conditions can be anything. It can be a single condition with any
operator or multiple conditions joined using logical operator.
Let us consider the same example of displaying first 15 natural numbers using both while
and do while loops.
#include
void main() {
int intNum = 0;
intNum++;
In the example above, intNum is used to check for the condition and display the
numbers. Initially it is declared and initialized. In while and do/while loops we cannot
declare and initialize it like we did in for loops. This is because, these loops checks for the
conditions and does not have any execution for the initial value. Hence if we declare or
initialize the variable in while loop, it will check for the same condition repeatedly and the
loop will never terminate
When the while loop starts, it checks for the value in intNum with the condition, i.e.;
0. In the next lines it finds do/while loop. Here we have not initialized intNum and it has
value 15. Since it is a do while loop, it does not checks for the condition first. Hence it enters
the loop without any condition check. It prints the value of intNum which is 15. You will
find the printf statement has postfix decrement operator on intNum – intNum –. Though we
have decrement operator, printf statement prints 15 instead of 14. This is because of the
priority of operator.
Since it is a postfix operator, it first prints the value of intNum and then decrements
the value of intNum. Hence intNum gets value 14 after printing it. Thus 15 is displayed at
the first. Then comes the while condition. It checks if intNum >=0 → 14 >=0 → TRUE. Hence
it repeats the loop and prints 14 and decrements the number. Again checks for condition
and repeats the loop until it is false. i.e.; when intNum = -1, it checks -1 >=0 → FALSE.
Hence comes out of the loop. Now intNum will have value -1. This is how both while and
do/while loop works.
Here we have given the example of displaying the numbers with increment and
decrement operators. It need not be increment / decrement by one. We can have any factor
#include
void main() {
int intOption=1;
int intMark;
scanf("%d", &intMark);
scanf("%d", &intOption);
Here the program checks for the user input value and the loop continues until they
enter any other number other than 1, though it says 0 for No. this is because the condition
in while loop is intOption == 1. This means when any other number is entered the
condition returns FALSE and loop terminates.
Same can be re-written using do/while loop. Here initialization of intOption is not
required as the condition is checked at the end. Hence it executes the loop at least once
irrespective of the option being entered or whether it is initialized or not. Here you can
note that we have entered option as 5 to terminate the loop even though it says 0 for No.
#include
void main() {
int intOption;
int intMark;
do{
scanf("%d", &intMark);
scanf("%d", &intOption);
FOR LOOP
The for loop in C language is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like the array and linked
list.
Let's see the simple program of for loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }
Output
1
2
3
4
5
6
7
8
9
10
NESTED LOOPS
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping
of statements inside another loop. Let's observe an example of nesting loops in C.
Any number of loops can be defined inside another loop, i.e., there is no restriction for
defining any number of loops. The nesting level can be defined at n times. You can define
any type of loop inside another loop; for example, you can define 'while' loop inside a 'for'
loop.
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-
while' loop.
The nested for loop means any type of loop which is defined inside the 'for' loop.
#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}
o First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
o The program control checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of the
outer loop, i.e., i++.
o After incrementing the value of the loop counter, the condition is checked again, i.e.,
i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true.
Output:
The nested while loop means any type of loop which is defined inside the 'while' loop.
while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}
#include <stdio.h>
int main()
{
int rows; // variable declaration
int columns; // variable declaration
int k=1; // variable initialization
printf("Enter the number of rows :"); // input the number of rows.
scanf("%d",&rows);
printf("\nEnter the number of columns :"); // input the number of columns.
scanf("%d",&columns);
int a[rows][columns]; //2d array declaration
int i=1;
while(i<=rows) // outer loop
{
int j=1;
while(j<=columns) // inner loop
{
printf("%d\t",k); // printing the value of k.
k++; // increment counter
j++;
}
i++;
printf("\n");
}
}
Output:
The nested do..while loop means any type of loop which is defined inside the 'do..while'
loop.
1. do
2. {
3. do
4. {
5. // inner loop statements.
6. }while(condition);
7. // outer loop statements.
8. }while(condition);
#include <stdio.h>
int main()
{
/*printing the pattern
********
********
********
******** */
int i=1;
do // outer loop
{
int j=1;
do // inner loop
{
printf("*");
j++;
}while(j<=8);
printf("\n");
i++;
}while(i<=4);
}
Output:
BREAK STATEMENT
The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the
loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then
proceeds to outer loops. The break statement in C can be used in the following two
scenarios:
Syntax:
Example
#include<stdio.h>
#include<stdlib.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
Output
Click here to see the example of C break with the switch statement
In such case, it breaks only the inner loop, but not outer loop.
1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. printf("%d &d\n",i,j);
7. if(i==2 && j==2){
8. break;//will break loop of j only
9. }
10. }//end of for loop
11. return 0;
12. }
Output
11
12
13
21
22
31
32
33
As you can see the output on the console, 2 3 is not printed because there is a break
statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the break
statement is used to break the inner loop only.
Consider the following example to use break statement inside while loop.
#include<stdio.h>
void main ()
{
int i = 0;
while(1)
{
printf("%d ",i);
i++;
if(i == 10)
break;
}
printf("came out of while loop");
}
Output
BREAK STATEMENT
Consider the following example to use the break statement with a do-while loop.
#include<stdio.h>
void main ()
{
int n=2,i,choice;
do
{
i=1;
while(i<=10)
{
printf("%d X %d = %d\n",n,i,n*i);
i++;
}
printf("do you want to continue with the table of %d , enter any non-
zero value to continue.",n+1);
scanf("%d",&choice);
if(choice == 0)
{
break;
}
n++;
}while(1);
}
Output
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
do you want to continue with the table of 3 , enter any non-zero value to continue.1
3X1=3
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
do you want to continue with the table of 4 , enter any non-zero value to continue.0
CONTINUE STATEMENT
The continue statement in C language is used to bring the program control to the beginning
of the loop. The continue statement skips some lines of code inside the loop and continues
with the next iteration. It is mainly used for a condition so that we can skip some code for a
particular condition.
Syntax:
//loop statements
continue;
//some lines of the code which is to be skipped
#include<stdio.h>
void main ()
{
int i = 0;
while(i!=10)
{
printf("%d", i);
continue;
i++;
}
}
Output
infinite loop
#include<stdio.h>
int main(){
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5){//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for loop
return 0;
}
Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.
In such case, C continue statement continues only inner loop, but not outer loop.
#include<stdio.h>
int main(){
int i=1,j=1;//initializing a local variable
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==2 && j==2){
continue;//will continue loop of j only
}
printf("%d %d\n",i,j);
}
}//end of for loop
return 0;
}
Output
11
12
13
21
23
31
32
33
As you can see, 2 2 is not printed on the console because inner loop is continued at i==2
and j==2.
GOTO STATEMENT
The goto statement is known as jump statement in C. As the name suggests, goto is
used to transfer the program control to a predefined label. The goto statment can be used
to repeat some part of the code for a particular condition. It can also be used to break the
multiple loops which can't be done by using a single break statement. However, using goto
is avoided these days since it makes the program less readable and complecated.
Syntax:
label:
//some part of the code;
goto label;
goto example
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
Output:
10 x 10 = 100
EXIT
Following are the main points of the exit function in C programming as follows:
1. We must include the stdlib.h header file while using the exit () function.
2. It is used to terminate the normal execution of the program while encountered the
exit () function.
3. The exit () function calls the registered atexit() function in the reverse order of their
registration.
4. We can use the exit() function to flush or clean all open stream data like read or
write with unwritten buffered data.
5. It closed all opened files linked with a parent or another function or file and can
remove all files created by the tmpfile function.
6. The program's behaviour is undefined if the user calls the exit function more than
one time or calls the exit and quick_exit function.
7. The exit function is categorized into two parts: exit(0) and exit(1).
Following are the main points of the exit function in C programming as follows:
1. We must include the stdlib.h header file while using the exit () function.
2. It is used to terminate the normal execution of the program while encountered the
exit () function.
3. The exit () function calls the registered atexit() function in the reverse order of their
registration.
4. We can use the exit() function to flush or clean all open stream data like read or
write with unwritten buffered data.
5. It closed all opened files linked with a parent or another function or file and can
remove all files created by the tmpfile function.
6. The program's behaviour is undefined if the user calls the exit function more than
one time or calls the exit and quick_exit function.
7. The exit function is categorized into two parts: exit(0) and exit(1).
7M
203
int status: It represents the status value of the exit function returned to the parent process.
Let's create a program to demonstrate the exit (0) function for normal terminating the
process in the C programming language.
1. #include <stdio.h>
2. #include <stdlib.h>
3. int main ()
4. {
5. // declaration of the variables
6. int i, num;
7. printf ( " Enter the last number: ");
8. scanf ( " %d", &num);
Output
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
RETURN
A return statement ends the execution of a function, and returns control to the
calling function. Execution resumes in the calling function at the point immediately
following the call. A return statement can return a value to the calling function. For more
information, see Return type.
Syntax
jump-statement:
return expressionopt ;
As a good engineering practice, always specify a return type for your functions. If a
return value isn't required, declare the function to have void return type. If a return type
isn't specified, the C compiler assumes a default return type of int.
The compiler may issue a warning diagnostic message about unreachable code if it finds
any statements placed after the return statement.
In a main function, the return statement and expression are optional. What happens
to the returned value, if one is specified, depends on the implementation. Microsoft-
specific: The Microsoft C implementation returns the expression value to the process that
invoked the program, such as cmd.exe. If no return expression is supplied, the Microsoft C
runtime returns a value that indicates success (0) or failure (a non-zero value).
Example
This example is one program in several parts. It demonstrates the return statement,
and how it's used both to end function execution, and optionally, to return a value.
CCopy
// C_return_statement.c
// Compile using: cl /W4 C_return_statement.c
#include <limits.h> // for INT_MAX
#include <stdio.h> // for printf
The square function returns the square of its argument, in a wider type to prevent an
arithmetic error. Microsoft-specific: In the Microsoft C implementation, the long long type
is large enough to hold the product of two int values without overflow.
UNIT IV
PYTHON
Python:
About python, features of python, python set up, fundamentals of python, values and data
types, variables, key word, identifier of python, quotations, indentation, multi line
statement, input-output and import function in python, advantages and disadvantages of
python.
ABOUT PYTHON
What is Python?
While you may know the python as a large snake, the name of the Python
programming language comes from an old BBC television comedy sketch series
called Monty Python’s Flying Circus.
One of the amazing features of Python is the fact that it is actually one person’s
work. Usually, new programming languages are developed and published by large
companies employing lots of professionals, and due to copyright rules, it is very hard to
name any of the people involved in the project. Python is an exception.
Of course, van Rossum did not develop and evolve all the Python components
himself. The speed with which Python has spread around the world is a result of the
continuous work of thousands (very often anonymous) programmers, testers, users (many
of them aren’t IT specialists) and enthusiasts, but it must be said that the very first idea
(the seed from which Python sprouted) came to one head – Guido’s.
Python isn’t a young language. It is mature and trustworthy. It’s not a one-hit
wonder. It’s a bright star in the programming firmament, and time spent learning Python is
a very good investment.
Python goals
About 20 years later, it is clear that all these intentions have been fulfilled. Some sources
say that Python is the third-most popular programming language in the world, while others
claim it’s the fifth.
Why Python?
What makes Python so special? How does it happen that programmers, young and
old, experienced and novice, want to use it? How did it happen that large companies
adopted Python and implemented their flagship products using it?
There are many reasons – we’ve listed some of them already, but let’s enumerate them
again in a more practical manner:
it’s easy to learn – the time needed to learn Python is shorter than for many
other languages; this means that it’s possible to start the actual programming faster;
it’s easy to teach – the teaching workload is smaller than that needed by other
languages; this means that the teacher can put more emphasis on general (language-
independent) programming techniques, not wasting energy on exotic tricks, strange
exceptions and incomprehensible rules;
it’s easy to use for writing new software – it’s often possible to write code faster
when using Python;
it’s easy to understand – it’s also often easier to understand someone else’s code
faster if it is written in Python;
it’s easy to obtain, install and deploy – Python is free, open and multiplatform; not all
languages can boast that.
Python in Action
Where can we see Python in action? We see it every day and almost everywhere.
It’s used extensively to implement complex Internet services like search engines,
cloud storage and tools, social media and so on. Whenever you use any of these
services, you are actually very close to Python, although you wouldn’t know it.
More and more everyday use applications are being written in Python. Lots of
scientists have abandoned expensive proprietary tools and switched to Python.
Lots of IT project testers have started using Python to carry out repeatable test
procedures. The list is long.
Python Examples
Web and Internet development (e.g., Django and Pyramid frameworks, Flask and
Bottle micro-frameworks)
Scientific and numeric computing (e.g., SciPy – a collection of packages for the
purposes of mathematics, science, and engineering; Ipython – an interactive shell
that features editing and recording of work sessions)
Education (it’s a brilliant language for teaching programming!)
Desktop GUIs (e.g., wxWidgets, Kivy, Qt)
Software Development (build control, management, and testing – Scons, Buildbot,
Apache Gump, Roundup, Trac)
Business applications (ERP and e-commerce systems – Odoo, Tryton)
Games (e.g., Battlefield series, Sid Meier\’s Civilization IV…), websites and
services (e.g., Dropbox, UBER, Pinterest, BuzzFeed…)
And that’s just the beginning…
FEATURES OF PYTHON
Python is a dynamic, high level, free open source and interpreted programming
language. It supports object-oriented programming as well as procedural oriented
programming.
Features in Python
There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in
python language and anybody can learn python basics in a few hours or days. It is also a
developer-friendly language.
2. Free and Open Source:
Python language is freely available at the official website and you can download it from the
given download link below click on the Download Python keyword.
Since it is open-source, this means that source code is also available to the public. So you
can download it as, use it as well as share it.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, objects encapsulation, etc.
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or
Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to
remember the system architecture, nor do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++
language and also we can compile that code in C/C++ language.
7. Python is Portable language:
Python language is also a portable language. For example, if we have python code for
windows and if we want to run this code on other platforms such as Linux, Unix, and Mac
then we do not need to change it, we can run this code on any platform.
8. Python is Integrated language:
Python is also an Integrated language because we can easily integrated python with other
languages like c, c++, etc.
9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time.
like other languages C, C++, Java, etc. there is no need to compile python code this makes
it easier to debug our code. The source code of python is converted into an immediate
form called bytecode.
10. Large Standard Library
Python has a large standard library which provides a rich set of module and functions so
you do not have to write your own code for every single thing. There are many libraries
present in python for such as regular expressions, unit-testing, web browsers, etc.
11. Dynamically Typed Language:
Python is a dynamically-typed language. That means the type (for example- int, double,
long, etc.) for a variable is decided at run time not in advance because of this feature we
don’t need to specify the type of variable.
PYTHON SET UP
This page explains how to set up Python on a machine so you can run and edit
Python programs, and links to the exercise code to download. You can do this before
starting the class, or you can leave it until you've gotten far enough in the class that you
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College
want to write some code. The Google Python Class uses a simple, standard Python
installation, although more complex strategies are possible. Python is free and open source,
available for all operating systems from python.org. In particular we want a Python install
where you can do two things:
Run the Python interpreter interactively, so you can type code right at it
Both of the above are done quite a lot in the lecture videos, and it's definitely something
you need to be able to do to solve the exercises.
Most operating systems other than Windows already have Python installed by
default. To check that Python is installed, open a command line (typically by running the
"Terminal" program), and cd to the google-python-exercises directory. Try the following to
run the hello.py program (what you type is shown in bold):
If python is not installed, see the Python.org download page. To run the Python interpreter
interactively, just type python in the terminal:
~/google-python-exercises$ python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 + 1
2
>>> you can type expressions here .. use ctrl-d to exit
For Google's Python Class, it's best to use Python 2.7. Although Python 3.x is becoming
more popular, this course is designed for Python 2.6 or later.
The commands above are the simplest way to run python programs. If the "execute bit" is
set on a .py file, it can be run by name without having to type python first. Set the execute
bit with the chmod command like this:
Python on Windows
Windows -- do not use Notepad or Wordpad. Try the free and open source Notepad++ or
the free and open source JEdit
Mac -- The built in TextEdit works, but not very well. Try the free BBEdit or the free and
open source JEdit
Linux -- any unix text editor is fine, or try the above JEdit.
Editor Settings
Following are some recommended settings for your text editor:
When you press Tab, it's best if your editor inserts spaces instead of a real tab
character. All of the tutorial files use 2-spaces as the indent, and 4-spaces is another
popular choice.
It's helpful if the editor will "auto indent" so when you press Enter, the new line
starts with the same indentation as the previous line.
When you save your files, use the unix line-ending convention, since that's how the
various starter files are set up. If running hello.py gives the error "Unknown option: -", the
file may have the wrong line-ending.
Here are the preferences to set for common editors to treat tabs and line-endings
correctly for Python:
Windows Notepad++ -- Tabs: Settings > Preferences > Edit Components > Tab
settings, and Settings > Preferences > MISC for auto-indent. Line endings: Format >
Convert, set to Unix.
JEdit (any OS) -- Line endings: Little 'U' 'W' 'M' on status bar, set it to 'U' (for Unix line-
endings).
Windows Notepad or Wordpad -- do not use.
Mac BBEdit -- Tabs: At the top, BBEdit > Preferences (or Cmd + , shortcut). Go to Editor
Defaults section and make sure Auto-indent and Auto-expand tabs are checked. Line
endings: In Preferences go to Text Files section and make sure Unix (LF) is selected under
Line breaks.
Mac TextEdit -- do not use.
Unix pico -- Tabs: Esc-q toggles tab mode, Esc-i to turns on auto-indent mode.
Unix emacs -- Tabs: manually set tabs-inserts-spaces mode: M-x set-variable(return)
indent-tabs-mode(return) nil.
Editing Check
To try out your editor, edit the hello.py program. Change the word "Hello" in the
code to the word "Howdy" (you don't need to understand all the other Python code in there
- we'll explain it all in class). Save your edits and run the program to see its new output. Try
adding a print 'yay!' just below the existing print and with the same indentation. Try
running the program, to see that your edits work correctly. For class we want an edit/run
workflow that allows you to switch between editing and running easily.
Quick Python Style
One of the advantages of Python is that it makes it easy to type a little code and
quickly see what it does. In class, we want a work setup that matches that: a text editor
working on the current file.py, and a separate command line window where you can just
press the up-arrow key to run file.py and see what it does.
Teaching philosophy aside: the interpreter is great for little experiments, as shown
throughout the lectures. However, the exercises are structured as Python files that students
edit. Since being able to write Python programs is the ultimate goal, it's best to be in that
mode the whole time and use the interpreter just for little experiments.
FUNDAMENTALS OF PYTHON
Fundamentals of Python consists of a discussion of basic building blocks of the
Python programming language. Here, “Fundamentals of Python” is divided into the
following categories. And we will be discussing each topic separately.
Watch this Video on Python Course
Statements
o Expressions
o Assignment Statements
Indentations
Comments
o Single-line comments
o Multi-line comment
o doc-staring comments
Variables
Constants
Tokens
o Identifiers
o Keywords
o Literals
o Operators
Expression Statements
Assignment Statements
Expression Statement:
(1+5) * 3
18
pow (3,2)
9
Assignment Statements
With the help of assignment statements, we create new variables, assign values and also
change values.
Structure of an assignment statement syntax:
We can categorize Assignment statements into three primary categories based on what’s
on the Right-Hand Side of the statement.
Note:
Look at the example shown below:
test1="Hello" id(test1) output:
2524751071304
test2="Hello" id(test2) output:
2524751071304
As you might have noticed that we have assigned the same string to two different variables.
But python allocated the same memory location for both the variables. That is because:
Python allocates the same memory location for the two cases mentioned below:
If the strings with less than 20 characters that don’t have white spaces and
Integers ranging between (-5 to +255).
As you can see we have the same location id allotted for the two variables.
Operation on RHS:
In this category, we have an operation on the right side of the statement, which is the
defining factor of the type of our statement.
Let’s understand that with the help of an example:
test= 7 * 2 type(test) int
test1= 7 * 2 / 10 type(test1) output:
float
Multiline statements
There are two ways to define multiline statements.
Implicit Method
Explicit Method
e.g.
a = (0 + 1 + 2 +
3 + 4 + 5)
a=0+1+2+\
3+4+5
Indentation
Unlike most programming languages python uses indentation to mark a block of code.
According to python style guidelines or PEP8, you should keep an indent size of four.
Most of the programming languages provide indentation for better code formatting and
don’t enforce to have it. But in Python it is mandatory. This is why indentation is so crucial
in Python.
Comments
Comments are nothing but tagged lines of in codes which increases the readability of the
code and make the code self-explanatory. Comments can be of two categories:
Single-line comments:
Multi-line comments:
Docstring comments:
Python has the documentation strings (or docstrings) feature. It gives programmers an
easy way of adding quick notes with every Python module, function, class, and method.
The strings defined using the triple-quotation mark are multiline comments. However, if
such a string is placed immediately after a function or class definition or on top of a
module, then they turn into docstrings.
Example:
def SayFunction(): '''
Strings written using '''_''' after a function represents docstring of func Python docstrings are not comments
'''
print("just a docstring")
print("Let us see how to print the docstring value") print(theFunction. doc )
Variables:
A variable is a memory address that can change and when a memory address cannot
change then it is known as constant. Variable is the name of the memory location where
data is stored. Once a variable is stored then space is allocated in memory. It defines a
variable using a combination of numbers, letters, and the underscore character.
Assigning Values to Variables
There is no need for an explicit declaration to reserve memory. The assignment is done
using the equal (=) operator. Some examples of legal python variables are –
i=1
j=2
Note: Python is a type inferred language i.e. it automatically detects the type of assigned
variable.
For instance,
test=1 type(test) output:
int test1="String" type(test1) output:
str
Constants:
Constant is a type of variable that holds values, whose value cannot be changed. In reality,
we rarely use constants in python.
Assigning a value to a constant in Python
Token
Tokens are the smallest unit of the program. There are the following tokens in Python:
Keywords:
Keywords are nothing but a set of special words, which are reserved by python and have
specific meanings. Remember that we are not allowed to use keywords as variables in
python.
Keywords in python are case sensitive.
We’ve just captured here a snapshot of the possible Python keywords.
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or continue global pass
Identifiers
You can use a sequence of letters (lowercase (a to z) or uppercase (A to Z)). You can
also mix up digits (0 to 9) or an underscore (_) while defining an identifier.
You can’t use digits to begin an identifier name.
You should not use Reserved Keywords to define an identifier.
Other than underscore (_) you are not allowed to use any other special characters.
Even though python doc says that you can name an identifier with unlimited length.
But it is not entirely true.
Using a large name (more than 79 chars) would lead to the violation of a rule set by the
PEP-8 standard. It says.
Literals:
The other built-in objects in python are Literals. Literals can be defined as data that is given
in a variable or constant. Python has the following literals:
String Literals:
A string literal is a sequence of characters surrounded by quotes. We can use both single,
double or triple quotes for a string. And, a character literal is a single character surrounded
by single or double-quotes.
Numeric Literals:
Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different
numerical types Integer, Float, and Complex.
Boolean Literals:
A Boolean literal can have any of the two values: True or False.
Collection literals:
There are four different literal collections List literals, Tuple literals, Dict literals, and Set
literals.
Special literals:
Python contains one special literal i.e. None. We use it to specify that field that is not
created.
Operators:
Operators are the symbols that perform the operation on some values. These values are
known as operands.
In Python, operators are categorized into the following categories:
Arithmetic Operators
Relational Operators
Assignment Operators
Logical Operators
Membership Operators
Identity Operators
Bitwise Operators
Arithmetic Operators
Arithmetic Operator Description Example
Operators Name
Relational Operators
It is also known as the comparison operator because it compares the values. After
comparison, it returns the Boolean value i.e. either true or false.
Operator Operator Name Description Example
!= Not Equal to If the values of two operands are not equal, I = 20, J = 20
then it returns true. (I == J)
is False
< Less than If the value of the left operand is less than the I = 40, J = 20
value of the right operand, then it returns true (I < J)
is False
> Greater than If the value of the left operand is greater than I= 40, J = 20
the value of the right operand, then it returns (I > J)
true is True
<= Less than or equal If the value of the left operand is less than or I = 40, J = 20
to equal to the value of the right operand, then it (I <= J)
returns true is False
>= Greater than or If the value of the left operand is greater than I = 40, J = 20
equal to or equal to the value of the right operand, (I >= J)
then it returns true. is True
<> Not equal to If the values of two operands are not equal, I=40, J = 20
(similar to !=) then the condition becomes true (I <> J)
is True.
Assignment Operators
Operator Operator Name Description Example
//= The floor division then It performs floor division and then I//=J
assign results is assigned to the left-hand that means I = I
operand // J
Logical Operators
Operator Operator Name Description Example
and Logical AND When Both side condition is true the result is 2<1 and 2<3
or Logical OR When at least one condition is true then the 2<1 or 2<3
result is true otherwise false True
Membership Operators
Operator Description Example
<< Binary Left Shift The left operand is moved left by I << 2
the number of bits specified by 240 i.e. 1111
the right operand. 0000
>> Binary Right Shift The left operand is moved right I >> 2
by the number of bits specified by 15 i.e. 1111
the right operand.
Identity Operators
These operators are used to compare the memory address of two objects.
Operator Description Example
# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Creating String
Strings in Python can be created using single quotes or double quotes or even triple
quotes.
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
Output:
Initial String:
GeeksForGeeks
Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
Python3
# Creating a List
List = []
print("Initial blank List: ")
print(List)
Output:
Initial blank List:
[]
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
In order to access the list items refer to the index number. Use the index operator [ ] to
access an item in a list. In Python, negative sequence indexes represent positions from the
end of the array. Instead of having to compute the offset as in List[len(List)-3], it is
enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers
to the last item, -2 refers to the second-last item, etc.
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer Python List.
3) Tuple
Just like list, tuple is also an ordered collection of Python objects. The only difference
between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it
is created. It is represented by tuple class.
Creating Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’
with or without the use of parentheses for grouping of the data sequence. Tuples can
contain any number of elements and of any datatype (like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one
element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a
tuple.
# Creating a Tuple
Output:
Initial empty Tuple:
()
Note – Creation of Python tuple without the use of parentheses is known as Tuple
Packing.
Accessing elements of Tuple
In order to access the tuple items refer to the index number. Use the index
operator [ ] to access an item in a tuple. The index must be an integer. Nested tuples are
accessed using nested indexing.
# Python program to
# demonstrate accessing tuple
Output:
First element of tuple
1
# Python program to
# demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
Set
In Python, Set is an unordered collection of data type that is iterable, mutable and
has no duplicate elements. The order of elements in a set is undefined though it may
consist of various elements.
Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by ‘comma’. Type of
elements in a set need not be the same, various mixed-up data type values can also be
passed to the set.
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
Output:
# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)
Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\
nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\
nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')]) print("\
nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print(Dict['name'])
Output:
Accessing a element using key:
For
Accessing a element using get:
VARIABLES
Python is not “statically typed”. We do not need to declare variables before using
them or declare their type. A variable is created the moment we first assign a value to it. A
variable is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
Rules for creating variables in Python:
A variable name must start with a letter or the underscore character.
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
Variable names are case-sensitive (name, Name and NAME are three different variables).
The reserved words(keywords) cannot be used naming the variable.
Let’s see the simple variable creation:
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Output:
45
1456.8
John
Declare the Variable:
Let’s see how to declare the variable and print the variable.
# display
print( Number)
Output:
100
Re-declare the Variable:
We can re-declare the python variable once we have declared the variable already.
# display
print("Before declare: ", Number)
Output:
Before declare: 100
After re-declare: 120.3
Assigning a single value to multiple variables:
Also, Python allows assigning a single value to several variables simultaneously with “=”
operators.
For example:
a = b = c = 10
print(a)
print(b)
print(c)
Output:
10
10
10
Assigning different values to multiple variables:
Python allows adding different values in a single line with “,”operators.
a, b, c = 1, 20.2, "GeeksforGeeks"
print(a)
print(b)
print(c)
Output:
1
20.2
GeeksforGeeks
Can we use the same name for different types?
If we use the same name, the variable starts referring to a new value and type.
a = 10
a = "GeeksforGeeks"
print(a)
Output:
GeeksforGeeks
How does + operator work with variables?
a = 10
b = 20
print(a+b)
a = "Geeksfor"
b = "Geeks"
print(a+b)
Output
30
GeeksforGeeks
Can we use + for different types also?
No using for different types would produce error.
a = 10
b = "Geeks"
print(a+b)
Output :
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Global and Local Variables in Python:
Local variables are the ones that are defined and declared inside a function. We can not
call this variable outside the function.
f()
Output:
Welcome geeks
Global variables are the ones that are defined and declared outside a function, and we
need to use them inside a function.
# Global scope
s = "I love Geeksforgeeks"
f()
Output:
I love Geeksforgeeks
Global keyword in Python:
Global keyword is a keyword that allows a user to modify a variable outside of the
current scope. It is used to create global variables from a non-global scope i.e inside a
function. Global keyword is used inside a function only when we want to do assignments
or when we want to change a variable. Global is not needed for printing and accessing.
Rules of global keyword:
If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a
local unless explicitly declared as global.
Variables that are only referenced inside a function are implicitly global.
We Use global keyword to use a global variable inside a function.
There is no need to use global keyword outside a function.
Example:
x = 15
def change():
# increment value of a by 5
x=x+5
print("Value of x inside a function :", x)
change()
print("Value of x outside a function :", x)
Output:
Value of x inside a function : 20
Value of x outside a function : 20
# numberic
var = 123
print("Numbric data : ", var)
# Sequence Type
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Boolean
print(type(True))
print(type(False))
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\
nDictionary with the use of Integer Keys: ")
print(Dict)
Output:
Numbric data : 123
String with the use of Single Quotes:
Welcome to the Geeks World
<class 'bool'>
<class 'bool'>
x=5
y=x
When Python looks at the first statement, what it does is that, first, it creates an
object to represent the value 5. Then, it creates the variable x if it doesn’t exist and made
it a reference to this new object 5. The second line causes Python to create the variable y,
and it is not assigned with x, rather it is made to reference that object that x does. The net
effect is that the variables x and y wind up referencing the same object. This situation,
with multiple names referencing the same object, is called a Shared Reference in Python.
Now, if we write:
x = 'Geeks'
This statement makes a new object to represent ‘Geeks’ and makes x to reference this
new object.
# Class Variable
stream = 'cse'
# Instance Variable
self.roll = roll
Output
cse
cse
101
cse
KEY WORD
Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation. These
keywords can't be used as a variable. Following is the List of Python Keywords.
True False None and as
A B A and B
A B A and B
A Not A
True False
False True
7. assert - This keyword is used as the debugging tool in Python. It checks the correctness
of the code. It raises an AssertionError if found any error in the code and also prints the
message with an error.
Example:
a = 10
b=0
print('a is dividing by Zero')
assert b != 0
print(a / b)
Output:
a is dividing by Zero
Runtime Exception:
Traceback (most recent call last):
File "/home/40545678b342ce3b70beb1224bed345f.py", line 4, in
assert b != 0, "Divide by 0 error"
AssertionError: Divide by 0 error
8. def - This keyword is used to declare the function in Python. If followed by the function
name.
def my_func(a,b):
c = a+b
print(c)
my_func(10,20)
Output:
30
9. class - It is used to represents the class in Python. The class is the blueprint of the objects.
It is the collection of the variable and methods. Consider the following class.
class Myclass:
#Variables……..
def function_name(self):
#statements………
10. continue - It is used to stop the execution of the current iteration. Consider the
following example.
a=0
while a < 4:
a += 1
if a == 2:
continue
print(a)
Output:
1
3
4
11. break - It is used to terminate the loop execution and control transfer to the end of the
loop. Consider the following example.
Example
for i in range(5):
if(i==3):
break
print(i)
print("End of execution")
Output:
0
1
2
End of execution
12. If - It is used to represent the conditional statement. The execution of a particular block
is decided by if statement. Consider the following example.
Example
i = 18
if (1 < 12):
print("I am less than 18")
Output:
I am less than 18
13. else - The else statement is used with the if statement. When if statement returns false,
then else block is executed. Consider the following example.
Example:
n = 11
if(n%2 == 0):
print("Even")
else:
print("odd")
Output:
Odd
14. elif - This Keyword is used to check the multiple conditions. It is short for else-if. If the
previous condition is false, then check until the true condition is found. Condition the
following example.
Example:
marks = int(input("Enter the marks:"))
if(marks>=90):
print("Excellent")
elif(marks<90 and marks>=75):
print("Very Good")
elif(marks<75 and marks>=60):
print("Good")
else:
print("Average")
Output:
Enter the marks:85
Very Good
15. del - It is used to delete the reference of the object. Consider the following
example. Example:
a=10
b=12
del a
print(b)
# a is no longer exist
print(a)
Output:
12
NameError: name 'a' is not defined
16. try, except - The try-except is used to handle the exceptions. The exceptions are run-
time errors. Consider the following example.
Example:
a=0
try:
b = 1/a
except Exception as e:
print(e)
Output:
division by zero
17. raise - The raise keyword is used to through the exception forcefully. Consider the
following example.
Example
a=5
if (a>2):
raise Exception('a should not exceed 2 ')
Output:
Exception: a should not exceed 2
18. finally - The finally keyword is used to create a block of code that will always be
executed no matter the else block raises an error or not. Consider the following example.
Example:
a=0
b=5
try:
c = b/a
print(c)
except Exception as e:
print(e)
finally:
print('Finally always executed')
Output:
division by zero
Finally always executed
19. for, while - Both keywords are used for iteration. The for keyword is used to iterate
over the sequences (list, tuple, dictionary, string). A while loop is executed until the
condition returns false. Consider the following example.
Example: For loop
list = [1,2,3,4,5]
for i in list:
print(i)
Output:
1
2
3
4
5
Example: While loop
a=0
while(a<5):
print(a)
a = a+1
Output:
0
1
2
3
4
20. import - The import keyword is used to import modules in the current Python script.
The module contains a runnable Python code.
Example:
import math
print(math.sqrt(25))
Output:
5
21. from - This keyword is used to import the specific function or attributes in the current
Python script.
Example:
from math import sqrt
print(sqrt(25))
Output:
5
22. as - It is used to create a name alias. It provides the user-define name while importing a
module.
Example:
import calendar as cal
print(cal.month_name[5])
Output:
May
23. pass - The pass keyword is used to execute nothing or create a placeholder for future
code. If we declare an empty class or function, it will through an error, so we use the pass
keyword to declare an empty class or function.
Example:
class my_class:
pass
def my_func():
pass
24. return - The return keyword is used to return the result value or none to called
function.
Example:
def sum(a,b):
c = a+b
return c
a = []
b = []
print(x is y)
print(a is b)
Output:
True
False
26. global - The global keyword is used to create a global variable inside the function. Any
function can access the global. Consider the following example.
Example
def my_func():
global a
a = 10
b = 20
c = a+b
print(c)
my_func()
def func():
print(a)
func()
Output:
30
10
27. nonlocal - The nonlocal is similar to the global and used to work with a variable inside
the nested function(function inside a function). Consider the following example.
Example
def outside_function():
a = 20
def inside_function():
nonlocal a
a = 30
print("Inner function: ",a)
inside_function()
print("Outer function: ",a)
outside_function()
Output:
Inner function: 30
Outer function: 30
28. lambda - The lambda keyword is used to create the anonymous function in Python. It is
an inline function without a name. Consider the following example.
Example
a = lambda x: x**2
for i in range(1,6):
print(a(i))
Output:
1
4
9
16
25
29. yield - The yield keyword is used with the Python generator. It stops the function's
execution and returns value to the caller. Consider the following example.
Example
def fun_Generator():
yield 1
yield 2
yield 3
print(value)
Output:
1
2
3
30. with - The with keyword is used in the exception handling. It makes code cleaner and
more readable. The advantage of using with, we don't need to call close(). Consider the
following example.
Example
with open('file_path', 'w') as file:
file.write('hello world !')
31. None - The None keyword is used to define the null value. It is remembered
that None does not indicate 0, false, or any empty data-types. It is an object of its data type,
which is Consider the following example.
Example:
def return_none():
a = 10
b = 20
c=a+b
x = return_none()
print(x)
Output:
None
We have covered all Python keywords. This is the brief introduction of Python Keywords.
Keyword Description
as To create an alias
or A logical operator
IDENTIFIER OF PYTHON
1. The Python identifier is made with a combination of lowercase or uppercase letters, digit
s or an underscore.
2. An identifier cannot start with a digit. If we create an identifier that starts with a digit
then we will get a syntax error.
If you want to see the list of all the keywords, then in your Python shell, type “help()” and
then type “keywords” to get the list of all Python keywords.
5. The length of the identifiers can be as long as you want. Of course, it can not be greater
than the available memory, however, the PEP-8 standards rule suggests not to
exceed 79 characters in a line.
Testing the Validity of Python Identifiers
Python has some helper functions that are useful when you are not sure whether a string is
a keyword or a valid identifier.
import keyword
print( keyword.iskeyword(“var”) )
print( keyword.iskeyword(“False”) )
print( keyword.iskeyword(“continue”) )
print( keyword.iskeyword(“count”) )
Output:
False
True
True
False
2. The str.isidentifier() function is used to check the validity of an
identifier. print( “name”.isidentifier() )
print( “#today”.isidentifier() )
print( “_12hello”.isidentifier() )
print( “8cellos”.isidentifier() )
Output:
True
False
True
False
Best Practices for Python Identifiers
Following the naming conventions are mandatory for everyone. But that’s not it!
The Python community has made a few more guidelines that are not compulsory but it
is advised to follow some practices that are better for everyone in understanding things.
Let’s see what these guidelines are.
1. Class names should start with a capital letter and all the other identifiers should start
with a lowercase letter.
2. Begin private identifiers with an underscore (_). Note, this is not needed to make
the variable private. It is only for the ease of the programmer to easily distinguish
between private variables and public variables.
3. Use double underscores ( ) around the names of magic methods and don’t use them
anywhere else. Python built-in magic methods already use this notation. For
example: init , len .
4. Double underscores are used only when you are dealing with mangling in Python.
5. Always prefer using names longer than one character. index=1 is better than i=1
6. To combine words in an identifier, you should use underscore(_). For
example: get_user_details.
7. Use camel case for naming the variables. For example: fullName, getAddress,
testModeOn, etc.
QUOTATIONS
Output
Ask?
Python Programming
Hi ABC
Invalid Syntax
What are double quotes in Python used for?
A double quotation mark is to set off a direct (word-for-word) quotation. For example – “I
hope you will be here,” he said. In Python Programming, we use Double Quotes for string
representation. Let us understand with an example through code in python.
NOTE: Use double quotes to enclose your strings when you know there are going to be
single quotes within your string
Code
1 wish = "Hello World!"
2 print(wish)
3 hey = "AskPython says "Hi""
4 print(hey)
5 famous ="'Taj Mahal' is in Agra."
6 print(famous)
Output
Hello World!
Invalid Syntax
'Taj Mahal' is in Agra.
Key Differences Between Single and Double Quotes in Python
Single Quotation Mark Double Quotation Mark
Represented as ‘ ‘ Represented as ” “
Single quotes are used for regular expressions, dict Double quotes are used for string
keys or SQL. representation.
INDENTATION IN PYTHON
To understand this consider a situation where you are reading a book and all of a
sudden all the page numbers from the book went missing. So you don’t know, where to
continue reading and you will get confused. This situation is similar with Python. Without
indentation, Python does not know which statement to execute next or which statement
belongs to which block. This will lead to IndentationError.
Python indentation is a way of telling a Python interpreter that the group of
statements belongs to a particular block of code. A block is a combination of all these
statements. Block can be regarded as the grouping of statements for a specific purpose.
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation to highlight the blocks of code. Whitespace is used for
indentation in Python. All statements with the same distance to the right belong to the
same block of code. If a block has to be more deeply nested, it is simply indented further
to the right. You can understand it better by looking at the following lines of code.
Example #1:
site = 'gfg'
if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')
Output:
Logging on to geeksforgeeks...
All set !
The lines print(‘Logging on to geeksforgeeks…’) and print(‘retype the URL.’) are two
separate code blocks. The two blocks of code in our example if-statement are both
indented four spaces. The final print(‘All set!’) is not indented, and so it does not belong
to the else-block.
Example #2:
j=1
while(j<= 5):
print(j)
j=j+1
Output:
1
2
3
4
5
To indicate a block of code in Python, you must indent each line of the block by the same
whitespace. The two lines of code in the while loop are both indented four spaces. It is
required for indicating what block of code a statement belongs to. For
example, j=1 and while(j<=5): is not indented, and so it is not within while block. So,
Python code structures by indentation.
Note: Python uses 4 spaces as indentation by default. However, the number of spaces is
up to you, but a minimum of 1 space has to be used.
Python statements are the code instructions that are executed by the Python
interpreter.
Python Statements Examples
Let’s look at some simple statement examples.
count = 10 # statement 1
math_result = 1 + 2 + 3 + 4 + \
5+6+7+8+\
9 + 10
print(message)
print(math_result)
Python Statements
math_result = (1 + 2 + 3 + 4 +
5+6+7+8+
9 + 10)
prime_numbers_tuple = (2, 3, 5, 7,
11, 13, 17)
2. Assignment Statement
count = 10 # value is assigned to the variable, no expression is evaluated
message = "Hi"
3. Assert Statement
assert 5 < 10
assert (True or False)
4. pass Statement
def foo():
pass # pass statement
5. del Statement
name = "Python"
del name # del statement
return Statement
def foo():
return 10 # return statement
7. yield Statement
def yield_statement():
yield 'Statement 1' # yield statement
8. raise Statement
def raise_example():
raise TypeError('Exception Example') # raise statement
9. break Statement
numbers = [1, 2, 3]
import collections
import calendar as cal
from csv import DictReader
def global_example():
global name # global statement
name = "Flask"
def outer_function():
scope = "local"
def inner_function():
nonlocal scope # nonlocal statement
scope = "nonlocal"
print(scope)
inner_function()
print(scope)
outer_function()
print("Unreachable Code")
2. for Statement
for n in (1, 2, 3):
print(n)
3. while Statement
count = 5
while count > 0:
print(count)
count -= 1
4. try Statement
try:
print("try")
except ValueError as ve:
print(ve)
5. with Statement
with open('data.csv') as file:
file.read()
Python statements are used by the Python interpreter to run the code. It’s good to know
about the different types of statements in Python.
# Output
print("Hello, " + name)
print(type(name))
Output:
Enter your name: GFG
Hello, GFG
<class 'str'>
Note: Python takes all the input as a string input by default. To convert it to any other
data type we have to convert the input explicitly. For example, to convert the input to int
or float we have to use the int() and float() method respectively.
Example 2: Integer input in Python
add = num + 1
# Output
print(add)
Output:
Enter a number: 25
26
Output
GFG
GFG
In the above example, we can see that in the case of the 2nd print statement there is a
space between every letter and the print statement always add a new line character at
the end of the string. This is because after every character the sep parameter is printed
and at the end of the string the end parameter is printed. Let’s try to change this sep and
end parameter.
Example: Python Print output with custom sep and end parameter
Output
GFG@G#F#G
Formatting Output
Formatting output in Python can be done in many ways. Let’s discuss them below
Using formatted string literals
We can use formatted string literals, by starting a string with f or F before opening
quotation marks or triple quotation marks. In this string, we can write Python
expressions between { and } that can refer to a variable or any literal value.
Example: Python String formatting using F string
# Declaring a variable
name = "Gfg"
# Output
print(f'Hello {name}! How are you?')
Output:
Hello Gfg! How are you?
Using format()
We can also use format() function to format our output to make it look presentable. The
curly braces { } work as placeholders. We can specify the order in which variables occur
in the output.
Example: Python string formatting using format() function
# Initializing variables
a = 20
b = 10
# addition
sum = a + b
# subtraction
sub = a- b
# Output
print('The value of a is {} and b is {}'.format(a,b))
Output:
Using % Operator
We can use ‘%’ operator. % values are replaced with zero or more value of elements.
The formatting using % is similar to that of ‘printf’ in the C programming language.
%d – integer
%f – float
%s – string
%x – hexadecimal
%o – octal
Example:
add = num + 5
# Output
print("The sum is %d" %add)
Output:
Enter a value: 50
The sum is 55
IMPORT IN PYTHON
Import is a keyword that is used to import the definitions or functions from a
module. Also, a module is a Python file that contains prewritten code or functions. The
import keyword is used along with another keyword from which is used to import the
module.
Suppose you want a program that accepts an integer and give the square root of the
integer. For this, you can make a program or you can use a predefined function sqrt(),
which is a part of module math. So, to use the sqrt() function, you need to import it on your
current file by using the import keyword.
Let’s understand it with the following example:
from math import sqrt
var = int(input("Enter a Number: "))
sqt = sqrt(var)
print(sqt)
Output
Enter a Number: 10
3.1622776601683795
Important Points to Remember
To print two different data types using the print() function, use a comma to separate
them.
Use Type conversion to convert the data type of the value which you get from
the input() function.
The from keyword is used to import a module.
The import keyword imports the definitions or functions from a module.
There are many modules in Python.
You can also install the third-party modules or libraries using the pip install command.
ADVANTAGES OF PYTHON
Easy to use and learn: For beginners, Python is straightforward to use. It is a high-level
programming language, and its syntax is like the English language. These reasons make the
language easy to learn and adapt to. Compared to Java and C, in Python, the same task can
be performed using fewer lines of code. As a result of its easy learning, the principles in
Python can be executed faster compared to other languages.
Increased productivity: Python is a very productive language. The simple nature of
Python helps the developers to concentrate on solving the issues in it. To understand the
syntax and behavior of the programming language, the users do not have to spend hours, so
more work is done.
Flexibility: This language is very flexible, and hence it allows the user to try new things.
The users can develop new sorts of the application using Python programming language.
The language does not restrict the user from trying something different. Other
programming languages do not provide this type of flexibility and freedom, and hence
Python is more preferred in these matters.
Extensive library: Python provides the user with a vast library. Python’s standard library
is massive, and just about every function one needs to perform is available in its library.
This is because it has a hugely supportive community and corporate sponsorship. External
libraries are not used by users while working with Python.
Supportive community: The Python language was created years ago, and hence it has a
mature community that can support every type of developer, starting from beginners’ level
to expert level. There are enough guides, tutorials, and documentation available on the
Python programming language, which helps the developers to understand the language
faster and better. Because of its supportive community, Python has rapid growth compared
to other languages.
DISADVANTAGES OF PYTHON
Memory consumption: Python has a very high memory consumption. This is because it is
flexible to the data types. It uses large amounts of memory. Python is not a good choice for
tasks where the user wants to optimize memory, i.e., a memory-intensive language.
Mobile development: Python is strong in server platforms and desktops, and hence it is a
fantastic server-side programming language. But it is not appropriate for mobile
development. For mobile development, Python is a fragile language. Since it is not memory
efficient and has a prolonged power for processing, due to these reasons, Python does not
have many built-in mobile applications. Carbonnelle is a built-in application present in
Python.
Database access: Python provides easy programming. However, when it interacts with the
database, some issues arise. Compared to technologies like JDBC and ODBC, which are
pretty famous, the database access layer of the Python programming language is primitive
and underdeveloped. Large enterprises that usually need smooth interaction with complex
legacy data do not prefer the usage of Python.
Runtime errors: The users of Python mentioned various issues they faced with the
language design. Since the language of Python is dynamically typed, there can be changes in
the data type of a variable at any time. Therefore, it needs to be tested more often, and also,
there are errors in the language displayed during runtime.
Simplicity: Python is a straightforward and easy-to-use programming language which is
also a disadvantage of the language. The users of Python get so accustomed to its easy
syntax and extensive library feature that they face issues while learning other
programming languages. Some users also feel that the Java codes are unnecessary due to
their complexity. Therefore, Python has a very vulnerable nature, and the users start taking
everything lightly.
UNIT V
FRUITFUL FUNCTIONS IN PYTHON
DEFINING A FUNCTION
def fun():
print("Welcome to GFG")
Rules for defining a function
The def keyword is used in the Python function to declare and define a function.
The function name must begin with the following identifiers such as: A-Z, a- z, and
underscore (_).
Every function must follow colon (:) and then indention to write the program.
In a Python function, the reserved word cannot be used as a function name or
identifier.
In Python, the function parameter can be empty or multiples.
Output:
WELCOME TO JAVATPOINT
HELLO, WELCOME TO JAVATPOINT
Write a program to call a function inside the class.
Student.py
class Student:
Roll_no = 101
name = "Johnson"
def show(self):
print(" Roll no. is %d\nName of student is %s" % (self.Roll_no, self.name))
Calling a Function
After creating a function we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
Example: Python Calling Function
def fun():
print("Welcome to GFG")
Output
Welcome to GFG
Arguments of a Function
Arguments are the values passed inside the parenthesis of the function. A function can
have any number of arguments separated by a comma.
Example: Python Function with arguments
In this example, we will create a simple function to check whether the number passed as
an argument to the function is even or odd.
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
Output
even
odd
Types of Arguments
Python supports various types of arguments that can be passed at the time of the function
call. Let’s discuss each type in detail.
Default arguments
A default argument is a parameter that assumes a default value if a value is not provided
in the function call for that argument. The following example illustrates Default
arguments.
Output
Keyword arguments
The idea is to allow the caller to specify the argument name with values so that caller
does not need to remember the order of parameters.
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output
('Geeks', 'Practice')
('Geeks', 'Practice')
Variable-length arguments
In Python, we can pass a variable number of arguments to a function using special
symbols. There are two special symbols:
*args (Non-Keyword Arguments)
**kwargs (Keyword Arguments)
Example 1: Variable length non-keywords argument
def myFun(*argv):
for arg in argv:
print(arg)
Output
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first='Geeks', mid='for', last='Geeks')
Output
first == Geeks
mid == for
last == Geeks
Docstring
The first string after the function is called the Document string or Docstring in short. This
is used to describe the functionality of the function. The use of docstring in functions is
optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function:
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function
def evenOdd(x):
"""Function to check if the number is even or odd"""
if (x % 2 == 0):
print("even")
else:
print("odd")
Output
Function to check if the number is even or odd
The return statement
The function return statement is used to exit from a function and go back to the function
caller and return the specified value or data item to the caller.
Syntax: return [expression_list]
The return statement can consist of a variable, an expression, or a constant which is
returned to the end of the function execution. If none of the above is present with the
return statement a None object is returned.
Example: Python Function Return Statement
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Output:
4
16
Is Python Function Pass by Reference or pass by value?
One important thing to note is, in Python every variable name is a reference. When we
pass a variable to a function, a new reference to the object is created. Parameter passing
in Python is the same as reference passing in Java.
Example:
Output
[20, 11, 12, 13, 14, 15]
When we pass a reference and change the received reference to something else, the
connection between the passed and received parameter is broken. For example, consider
the below program.
def myFun(x):
Output
[10, 11, 12, 13, 14, 15]
Another example to demonstrate that the reference link is broken if we assign a new
value (inside the function).
def myFun(x):
Output
10
Exercise: Try to guess the output of the following code.
# Driver code
x=2
y=3
swap(x, y)
print(x)
print(y)
Output
2
3
Anonymous functions:
In Python, an anonymous function means that a function is without a name. As we already
know the def keyword is used to define the normal functions and the lambda keyword is
used to create anonymous functions. Please see this for details.
print(cube(7))
print(cube_v2(7))
Output
343
Python Function within Functions
A function that is defined inside another function is known as the inner function or
nested function. Nested functions are able to access variables of the enclosing scope.
Inner functions are used so that they can be protected from everything happening outside
the function.
# Python program to
# demonstrate accessing of
# variables of nested functions
def f1():
s = 'I love GeeksforGeeks'
def f2():
print(s)
f2()
# Driver's code
f1()
Output
I love GeeksforGeeks
After Calling : 50
If you observe the Addition() Function, We haven’t passed any arguments /parameters to
the Addition()
We declared the integer variables a, b, and assigned 20 to a and 30 to b. In the next line, we
calculate the sum using Arithmetic operator ( + )
a = 20
b = 30
Sum = a + b
The below Python print statement is to print the output. Whenever we call the Adding(), it
prints the same output because a and b have fixed values inside the method.
print("After Calling :", Sum)
Python Function with no argument and with a Return value
In this type of function in Python, We won’t pass any arguments to the function while
defining, declaring, or calling it. When we call this type of function in Python, it returns
some value.
Function with No arguments and with a Return value Example
In this type of function in the Python program, we are going to calculate the multiplication
of 2 integer values using the user defined function without arguments and return keyword.
# Python Function with No Arguments, and with Return Value
def Multiplication():
a = 10
b = 25
Multi = a * b
return Multi
print("After Calling the Multiplication : ", Multiplication())
Python Function with No arguments and with a Return value output
After Calling the Multiplication : 250
>>> Multiplication()
250
Within the Multiplication (), We haven’t passed any arguments /parameters. Next, We
declared the integer variables of Multi, a, b, and we assigned 10 to a, and 25 to b. In the
next line, we Multiplied both a and b using an Arithmetic operator ( * ).
a = 10
b = 25
Multi = a * b
Lastly, the print statement is to print the output. Remember, we are using the print
statement outside the defined function, and we are using the name inside the print
statement. (nothing but calling the method)
print("After Calling the Multiplication : ", Multiplication())
Here also, Whenever we call the Multiplication(), it prints the same output because a and b
have fixed values inside it.
Python Function with argument and No Return value
If you observe the above 2 types of functions, No matter how many times you executive,
Python gives the same output. We don’t have any control over the variable values (a, b)
because they are fixed values. In real-time, we mostly deal with dynamic data means we
have to allow the user to enter his own values rather than fixed ones.
This type of function in Python allows us to pass the arguments while calling it. But, This
type of function in Python won’t return any value when we call it.
Python Function with argument and No Return value Example
This program for the type of function in Python allows the user to enter 2 integer values
and then, We are going to pass those values to the user defined function to Multiply them.
Python Function with Arguments, and NO Return Value
def Multiplications(a, b):
Multi = a * b
print("After Calling the Function:", Multi)
Multiplications(10, 20)
We called the Multiplication function with different values, and it is giving the output as per
the values.
Python Function with argument and Return value
This type of python function allows us to pass the arguments to the function while calling
the function. This type of functions in Python returns some value when we call the function.
This type of user defined function called a fully dynamic function means it provides
maximum control to the end-user.
Python Function with arguments and Return value Example
This type of function in the Python program allows the user to enter 2 integer values. Then,
we pass those values to the user-defined function to add those values and return the value
using the return keyword.
# Python Function with Arguments, and NO Return
Value def Addition(a, b):
Sum = a + b
return Sum
# We are calling the Function Outside the Definition
print("After Calling the Function:", Addition(25,
45))
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname+ "Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname,lname):
print(fname+ "" +lname)
my_function("Emil", "Refsnes")
Try it Yourself »
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
def my_function(fname,lname):
print(fname+ "" +lname)
my_function("Emil")
COMPOSITION IN PYTHON
In the above UML diagram, we have represented two different type of classes i.e.,
composites and components. The relationship between the composites and components is
the composition. As we can see that we have represented the composition through a line
where diamond from the composite class is pointing towards the components class
representing the composition relationship.
In the composition relation, the composite class side represents the cardinality.
Basically, the cardinality means the number of valid ranges or objects of the components
class that a composite class is containing in it. As we can see in the above diagram, the 1 in
the composite class represents only object of component class type is present in the
composite class through composition.
We can express the cardinality of the composition through the following ways:
By using a number (1, 2, 3, etc.)
By using the * symbol
By defining a range in composite (1...3, 2...5 etc.)
Composition allows us to reuse our code by adding objects with the other new objects, the
feature which is not present in the inheritance concept.
We know that Python is object-oriented programming language so it also follows
the composition method. In Python, the composition allows us to reuse the implementation
of the component class object in the composite classes. We have to remember that the
composite class is not actually inheriting the component class interface but it is adapting
the interface of instances of component class.
The composition relationship in Python between composite class and component
class is considered as loosely coupled. It means that if we make changes in component
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College
class, it will rarely affect the composite class and if we make changes in the composite class,
it will never affect the component class. This feature of composition in Python provides us
better adaptability with the changes. It also allows us to introduce new changes in the
application according to the requirements without affecting the existing code.
First, we will understand this through a basic example where we will use the basic
concept of composition in our Python program and then we will move forward with the use
of composition.
Example:
# create a component class in program
class ComponentClass:
# create the composite class constructor in component
def init (self):
print('An object for the Component class is created ...')
# using the composite class instance method
def mk1(self):
print('The Component class method mk1() is executed successfully ...')
# create a composite class in program
class CompositeClass:
# create a class constructor for composite class
def init (self):
# creating an instance for the component class
self.inst1 = ComponentClass()
print('An object for the Composite class is also created ...')
# creating a class instance method for composite class
def mk(self):
print('The Composite class method mk() is also successfully executed ...')
# calling the mk1() method of component class in composite class
self.inst1.mk1()
# creating an instance for the composite class
inst2 = CompositeClass()
# calling out mk() method from the composite class
inst2.mk()
Output:
An object for the Component class is created ...
An object for the Composite class is also created ...
The Composite class method mk() is also successfully executed ...
The Component class method mk1() is executed successfully ...
Explanation: In the above given program, we have created two classes i.e., composite class
and component class and named them specifically. The ComponentClass and
CompositeClass shares the ‘has a type’ relation between them i.e., Composition relation. We
have also created one object for both the classes. To use the composition between the
classes, we have created a constructor for the composition class. We can see that we
also have defined two methods into the respective classes i.e., mk() & mk1(). We have
called out mk1() method of component class inside the mk() method of composite
class. So, whenever we will call out the mk1() in the program, the mk() method will
also be called out. We can also see this in the output of the program.
That’s how we use the composition relation between the composite and component class in
our Python program. Now, lets move forward with the uses of composition in Python.
Use of Composition in Python:
As we already discussed that the with the help of composition, we can use the
interface of component class objects in the composite class. We can also reuse the code for
the instance and interfaces of it. By this we can save our lot of time and writing of code for
it. Let's understand how the composition in Python will be really helpful to us in daily life
through the following example program:
First create a Python program file by writing the following program in it:
# create an address class in the program
class AddressClass:
# define the components of the address class with default function
def init (self, Street1, LiveinCity, LiveinState, PostalCode, Country, Street2 = ''): #
defining components of address class as variables
self.Street1 = Street1
self.Street2 = Street2
self.LiveinCity = LiveinCity
self.LiveinState = LiveinState
self.PostalCode = PostalCode
self.Country = Country
# define the properties of the address class with default function
def str (self):
TotalLines = [self.Street1]
# using the if method to append the lines
if self.Street2:
lines.append(self.Street2)
# printing following components in next line
TotalLines.append(f'{self.LiveinCity},{self.LiveinState}{self.PostalCode}
{self.Country}')
return '\n'.join(TotalLines) # appending the lines for output
After writing the above program, save this Python file into the disk (We saved it with
changing.py name in the device).
After that, open another Python program file and write the following program in it:
# import the python program script for the address class
from changing import AddressClass
# define the elements for the address class
Address1 = AddressClass('55 Main St.', 'Concord City', 'NH25', '03301', 'Mexico')
Address2 = AddressClass('36 Side St.', 'New Mexico City', 'NH67', '033207', 'Mexico')
# print the address elements in the output
print('The first address element we added is: ')
print(Address1)
print('The second address element we added is: ')
print(Address2)
Output:
The first address element we added is:
55 Main St.
Concord City, NH25 03301 Mexico
The second address element we added is:
36 Side St.
New Mexico City, NH67 033207 Mexico
Explanation:
In the above program, we have used composition relation in the address class that
we defined in the changing.py script file.
In the address class, we have also defined the components of it. After that, we set the
components of address class to variables so that it can store values in it. Then, we have
modified the components and append the lines for the components in the output.
We used if statement for it. Then, we saved the script file in the device. We opened another
Python file after that as we can see above. In the second file, we imported the address class
from the changing.py script file. We used the addressclass() to add the elements of address
in it. After that, the elements we added, we stored them as variable. Then, we printed the
address elements that are stored in variables in the output.
We have implemented the str() function in address class to modify the
components of the address class i.e., how they being displayed and append the line in the
output. While we use the address class components, it will also invoke the str() function
to called out. This is because of the composition relation function we used in the address
class. It will help us to reuse the code we have written and interface of the str()
function.
RECURSION IN PYTHON
The term Recursion can be defined as the process of defining something in terms of
itself. In simple words, it is a process in which a function calls itself directly or indirectly.
S Sree Narayana Guru College - Study Material - Even
Semester [2021- 22]
Sree Narayana Guru College
Syntax:
def func(): <--
|
| (recursive call)
|
func() ----
Example 1:
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
# Recursive function
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
Output:
Fibonacci series:
0
1
1
2
3
5
8
13
21
34
Example 2:
The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720.
# Recursive function
def recursive_factorial(n):
if n == 1:
return n
else:
return n * recursive_factorial(n-1)
# user input
num = 6
utput:
Factorial of number 6 = 720
What is Tail-Recursion?
if (n == 0):
return 1
return n * Recur_facto(n-1)
Output:
720
We can write the given function Recur_facto as a tail-recursive function. The idea is to use
one more argument and in the second argument, we accommodate the value of the
factorial. When n reaches 0, return the final value of the factorial of the desired number.
if (n == 0):
return a
return Recur_facto(n - 1, n * a)
Output:
720
Python Lambda Functions are anonymous function means that the function is
without a name. As we already know that the def keyword is used to define a normal
function in Python. Similarly, the lambda keyword is used to define an anonymous
function in Python.
Python Lambda Function Syntax:
lambda arguments: expression
This function can have any number of arguments but only one expression, which is
evaluated and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically restricted to
a single expression.
It has various uses in particular fields of programming besides other types of expressions
in functions.
Example: Lambda Function Example
string ='GeeksforGeeks'
Output
<function <lambda> at 0x7f65e6bbce18>
In this above example, the lambda is not being called by the print function but simply
returning the function object and the memory location where it is stored.
So, to make the print to print the string first we need to call the lambda so that the string
will get pass the print.
Example:
x ="GeeksforGeeks"
Output
GeeksforGeeks
Output:
125
125
As we can see in the above example both the cube() function and lambda_cube()
function behave the same and as intended. Let’s analyze the above example a bit more:
Without using Lambda: Here, both of them return the cube of a given number. But, while
using def, we needed to define a function with a name cube and needed to pass a value to
it. After execution, we also needed to return the result from where the function was called
using the return keyword.
Using Lambda: Lambda definition does not include a “return” statement, it always
contains an expression that is returned. We can also put a lambda definition anywhere
a function is expected, and we don’t have to assign it to a variable at all. This is the
simplicity of lambda functions.
Let’s see some more commonly used examples of lambda functions.
Output
10
20
30
40
50
60
70
80
90
100
Example 2: Python Lambda Function with if-else
print(Max(1, 2))
Output
2
print(res)
Output
[3, 16, 9]
In the above example, we have created a lambda function that sorts each sublist of the
given list. Then this list is passed as the parameter to the second lambda function which
returns the n-2 element from the sorted list where n is the length of the sublist.
Lambda functions can be used along with built-in functions
like filter(), map() and reduce().
Using lambda() Function with filter()
The filter() function in Python takes in a function and a list as arguments. This offers an
elegant way to filter out all the elements of a sequence “sequence”, for which the function
returns True. Here is a small program that returns the odd numbers from an input list:
Example 1:
Output:
[5, 7, 97, 77, 23, 73, 61]
Example 2:
print(adults)
Output:
[90, 59, 21, 60]
Output:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
Example 2:
print(uppered_animals)
Output:
['DOG', 'CAT', 'PARROT', 'RABBIT']
Output:
193
Here the results of previous two elements are added to the next element and this goes on
till the end of the list like (((((5+8)+10)+20)+50)+100).
Example 2:
# initializing list
lis = [ 1 , 3, 5, 6, 2, ]
Output:
The maximum element of the list is : 6