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

Final

Sarthak Goyal completed a computer science project on Python for his class 11. The project acknowledges the guidance of his computer teacher, Neha Saxena, and thanks his parents and friends for their support. The project contains an introduction to Python, its history and development, popular applications of Python like web development, machine learning, data science, and more. It also discusses advantages of Python like its simplicity, extensive libraries, readability and more. The project is certified by the subject teacher and principal.

Uploaded by

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

Final

Sarthak Goyal completed a computer science project on Python for his class 11. The project acknowledges the guidance of his computer teacher, Neha Saxena, and thanks his parents and friends for their support. The project contains an introduction to Python, its history and development, popular applications of Python like web development, machine learning, data science, and more. It also discusses advantages of Python like its simplicity, extensive libraries, readability and more. The project is certified by the subject teacher and principal.

Uploaded by

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

SESSION

2022-23

SHRI DEVI AHILYA SHISHU VIHAR

COMPUTER
SCIENCE
SUBMITTED BY- SARTHAK GOYAL

SUBMITTED TO- NEHA SAXENA MAM

P
PYTHON

PROJECT WORK
PROJECT WORK
ACKNOWLEDGMENT
I am glad to present my computer project. This
project was given by our respected computer
teacher Neha Saxena Mam. I am really thankful
to her for giving us such a wonderful and
interesting topic for our project.

I would also like to thank my parents and


friends from my heart. Without their
suggestions and feedback, the project would
not have achieved such a good outcome.

I hope everyone will like my project and


appreciate my hard work.
CERTIFICATE
This is to certify that Sarthak Goyal of class 11
of school Shri Devi Ahilya Shishu Vihar has
successfully completed his Computer Science
project work for the topic ‘Python’ for the
academic year 2022-23

I further certify that this project is the


individual work of the student.

___________ ____________
Subject Teacher Principal
INDEX
1. INTRODUCTION
2. HISTORY OF PYTHON
3. APPLICATIONS OF PYTHON
4. ADVANTAGES OF PYTHON
5. DISADVANTAGES OF PYTHON
6. TOKENS IN PYTHON
7. KEYWORDS
8. IDENTIFIRES
9. LITERALS
10. OPERATORS
11. BAREBONES OF A PYTHON PROGRAM
12. FLOW CONTROL STATEMENTS
13. LOOPING
INTRODUCTION
Python is a high-level, general-purpose programming language.
Its design philosophy emphasizes code readability with the use
of significant indentation.

Python is dynamically-typed and garbage-collected. It


supports multiple programming paradigms, including structured
(particularly procedural), object-oriented and functional
programming. It is often described as a "batteries included"
language due to its comprehensive standard library.

Guido van Rossum began working on Python in the late 1980s as


a successor to the ABC programming language and first
released it in 1991 as Python 0.9.0. Python 2.0 was released in
2000 and introduced new features such as list
comprehensions, cycle-detecting garbage collection, reference
counting, and Unicode support.

Python 3.0, released in 2008, was a major revision that is not


completely backward-compatible with earlier versions.
Python 2 was discontinued with version 2.7.18 in 2020.
Python consistently ranks as one of the most popular
programming languages

1
HISTORY OF
PYTHON
Python was conceived in the late 1980s by Guido van Rossum
at Centrum Wiskunde & Informatica (CWI) in the Netherlands as
a successor to the ABC programming language, which was
inspired by SETL, capable of exception handling and interfacing
with the Amoeba operating system. Its implementation began in
December 1989, Van Rossum shouldered sole responsibility for
the project, as the lead developer, until 12 July 2018, when he
announced his "permanent vacation" from his responsibilities as
Python's "benevolent dictator for life", a title the Python
community bestowed upon him to reflect his long-term
commitment as the project's chief decision-maker. In January
2019, active Python core developers elected a five-member
Steering Council to lead the project.

Python 2.0 was released on 16 October 2000, with many major


new features. Python 3.0, released on 3 December 2008, with
many of its major features backported to Python 2.6.xand 2.7.x.
Releases of Python 3 include the 2to3 utility, which automates
the translation of Python 2 code to Python 3.

Python 2.7's end-of-life was initially set for 2015, then


postponed to 2020 out of concern that a large body of existing

2
code could not easily be forward-ported to Python 3. No further
security patches or other improvements will be released for
it. Currently only 3.7 and later are supported. In 2021,
Python 3.9.2 and 3.8.8 were expedited as all versions of Python
(including 2.7) had security issues leading to possible remote
code execution and web cache poisoning.

In 2022, Python 3.10.4 and 3.9.12 were expedited and 3.8.13, and
3.7.13, because of many security issues. When Python 3.9.13 was
released in May 2022, it was announced that the 3.9 series
(joining the older series 3.8 and 3.7) will only receive security
fixes going forward. On September 7, 2022, four new releases
were made due to a potential denial-of-service attack: 3.10.7,
3.9.14, 3.8.14, and 3.7.14.

3
APPLICATIONS
OF PYTHON
1. Web Development

It is one of the most astonishing applications of Python. This is


because Python comes up with a wide range of frameworks
like Django, Flask, Bottle, and a lot more that provide ease to
developers. Furthermore, Python has inbuilt libraries and tools
which make the web development process completely
effortless. Use of Python for web development also offers:
• Amazing visualization
• Convenience in development
• Enhanced security
• Fast development process

2. Machine Learning and Artificial Intelligence

Machine Learning and Artificial Intelligence are the hottest


subjects right now. Python along with its inbuilt libraries and
tools facilitate the development of AI and ML algorithms.
Further, it offers simple, concise, and readable code which
makes it easier for developers to write complex algorithms
and provide a versatile flow. Some of the inbuilt libraries and
tools that enhance AI and ML processes are:

4
• Numpy for complex data analysis
• Keras for Machine learning
• SciPy for technical computing
• Seaborn for data visualization
3. Data Science
Data science involves data collection, data sorting, data
analysis, and data visualization. Python provides amazing
functionality to tackle statistics and complex mathematical
calculations. The presence of in-built libraries provides
convenience to data science professionals. Some of the
popular libraries that provide ease in the data science process
are TensorFlow, Pandas, and Socket learning. These libraries
provide an ecosystem for fine-tuning data models, data
preprocessing, and performing complex data analysis.

4. Game Development

With the rapidly growing gaming industry Python has proved to


be an exceptional option for game development. Popular
games like Pirates of the Caribbean, Bridge commander, and
Battlefield 2 use Python programming for a wide range of
functionalities and addons. The presence of popular 2D and 3D
gaming libraries like pygame, panda3D, and Cocos2D make the
game development process completely effortless.

5. Audio and Visual Applications

Audio and video applications are undoubtedly the most


amazing feature of Python. Python is equipped with a lot of
5
tools and libraries to accomplish your task flawlessly.
Applications that are coded in Python include popular ones like
Netflix, Spotify, and YouTube. This can be handled by libraries
like
• Dejavu
• Pyo
• Mingus
• SciPy
• OpenCV

6. Software Development

Python is just the perfect option for software development.


Popular applications like Google, Netflix, and Reddit all use
Python. This language offers amazing features like:
• Platform independence
• Inbuilt libraries and frameworks to provide ease of
development.
• Enhanced code reusability and readability
• High compatibility
Apart from these Python offers enhanced features to work with
rapidly growing technologies like Machine learning and
Artificial intelligence. All these embedded features make it a
popular choice for software development.

7. CAD Applications

6
CAD refers to computer-aided design; it is the process of
creating 3D and 2D models digitally. This application has
replaced manual drift and is used by architects, product
designers, and construction managers to design products with
extremely high consistency. Python is embedded with amazing
applications like Blender, FreeCAD, open cascade, and a lot
more to efficiently design products. These provide enhanced
features like technical drawing, dynamic system development,
recordings, file export, and import.

8. Business Applications

Python offers excellent security and scalability features that


make it perfect for delivering high-performance business
applications. It has inbuilt libraries and tools like:
• Odoo is business management software that provides you
with an automated solution for your business process.
• Tryton is easy-to-use open-source business software. It has
fully integrated features like financial accounting, sales,
CRM, purchasing, shipping, and the list goes on.
All these distinguishing features make it fit for creating
business applications.

9. Desktop GUI

Python is an interactive programming language that helps


developers to create GUIs easily and efficiently. It has a huge
list of inbuilt tools like PyQT, kivy, wxWidgets, and many other

7
libraries like them to build a fully functional GUI in an
extremely secure and efficient manner.

10. Web Scraping Application

Web scraping is an automated process used to extract


information from websites in an easier and faster way. The
information is used by researchers, organizations, and
analysts for a wide variety of tasks. Python has a wide range of
features that make it suitable for web scraping some of them
are:
• A concise syntax that enhances the readability and saves
your time.
• A wide range of libraries and tools like pandas, matplotlib,
and Selenium makes the web scraping process easy and
efficient.
• Easy to use and understand

8
ADVANTAGES
OF PYTHON
1.Simple to Use and Understand
For newcomers, Python is simple to understand and use. It's a
highly developed programming language with an English-like
syntax. The language is simple to adapt as a result of these
factors. Because of its simplicity, Python's fundamentals can be
implemented faster than those in other programming
languages.
2.Free and Open-Source
Python is distributed under an open-source license approved by
the Open-Source Initiative (OSI). As a result, users can work on
it and distribute it. Users can download the source code, modify
it, and even distribute their Python version. Companies that wish
to modify a specific behavior and build their version will benefit.
3.Productivity has Increased
Users can create new kinds of applications using the Python
programming language. Because of its versatility, this language
permits the operator to try new things. Because of the language,
the user is not prevented from trying something new. Python is
favored in these scenarios since other programming languages
lack the flexibility and freedom that Python does.

9
4.Interpreted Language
It is an interpreted language, implying that the code is
implemented line by line. This is one of the features that makes
it simple to use. In the event of an error, it halts the process and
reports the problem. Python only shows one error, even if the
program has multiple errors. This makes debugging easier.
5.Extensive library
Python includes a huge number of libraries that the user can
use. The standard library in Python is immense, and it includes
almost every function imaginable. Large and supportive
communities, as well as corporate sponsorship, have
contributed to this. When working with Python, users do not
need to use external libraries.
6.Dynamically Typed
Until we run the program, Python has no idea what kinds of
parameter we're talking about. It allocates the data type
automatically during execution. Variables and their data types
do not need to be declared by the programmer.
7.Portability
Many other languages, including C/C++, demand that user must
change their code to run on different platforms. Python, on the
contrary, is not equivalent to other programming languages. It
only needs to be written once, and then it can be run anywhere.

10
However, the user should avoid involving any system-
dependent features.
8.Supportive community
Python is a programming language generated many years ago
and has a large community that can assist programmers of all
experience levels, from rookies to specialists. Python's
community has helped it grow quickly in comparison to other
languages. The Python programming language comes with many
guides, instructional videos, and highly understandable
documentation to help developers learn the language faster and
more effectively.

11
DISADVANTAGES
OF PYTHON
1.Speed
Python is slower than C or C++. But of course, Python is a high-
level language, unlike C or C++ it's not closer to hardware.
2.Mobile Development
Python is not a very good language for mobile development . It
is seen as a weak language for mobile computing. This is the
reason very few mobile applications are built in it like
Carbonnelle.
3.Memory Consumption
Python is not a good choice for memory intensive tasks. Due to
the flexibility of the data-types, Python's memory consumption
is also high.
4.Database Access
Python has limitations with database access . As compared to
the popular technologies like JDBC and ODBC, the Python's
database access layer is found to be bit underdeveloped
and primitive .
5.Runtime Errors
Python programmers cited several issues with the design of the
language. Because the language is dynamically typed , it
requires more testing and has errors that only show up
at runtime .

12
TOKENS IN
PYTHON
Tokens. Python breaks each logical line into a sequence of
elementary lexical components known as tokens. Each token
corresponds to a substring of the logical line.

The normal token types are :

>Identifiers

> Keywords

>Operators

>Literals

>Punctuators

13
KEYWORDS
Python has a set of keywords that are reserved words that
cannot be used as variable names, function names, or any other
identifiers:

Keyword Description

and A logical operator

as To create an alias

assert For debugging

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop

14
def To define a function

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

except Used with exceptions, what to do when an exception occurs

False Boolean value, result of comparison operations

finally Used with exceptions, a block of code that will be executed no


matter if there is an exception or not

for To create a for loop

from To import specific parts of a module

15
global To declare a global variable

if To make a conditional statement

import To import a module

in To check if a value is present in a list, tuple, etc.

is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

nonlocal To declare a non-local variable

not A logical operator

16
or A logical operator

pass A null statement, a statement that will do nothing

raise To raise an exception

return To exit a function and return a value

True Boolean value, result of comparison operations

try To make a try...except statement

while To create a while loop

with Used to simplify exception handling

yield To end a function, returns a generator

17
IDENTIFIRES
Identifiers are the name given to variables, classes, methods,
etc. For example,

language = “Python”

Here, language is a variable (an identifier) which holds the


value 'Python'.
We cannot use keywords as variable names as they are
reserved names that are built-in to Python. For example,

Continue = “Python”

The above code is wrong because we have used continue as a


variable name. To learn more about variables, visit Python
Variables.

Rules for Naming an Identifier


• Identifiers cannot be a keyword.
• Identifiers are case-sensitive.
• It can have a sequence of letters and digits. However, it must
begin with a letter or _. The first letter of an identifier cannot be
a digit.

18
• It's a convention to start an identifier with a letter rather _.
• Whitespaces are not allowed.
• We cannot use special symbols like !, @, #, $, and so on.

Some Valid and Invalid Identifiers in Python

Valid Identifiers Invalid Identifiers

score @core

return_value return

highest_score highest score

name1 1name

convert_to_string convert to_string

19
Things to Remember
Python is a case-sensitive language. This
means, Variable and variable are not the same.
Always give the identifiers a name that makes sense. While c =
10 is a valid name, writing count = 10 would make more sense,
and it would be easier to figure out what it represents when you
look at your code after a long gap.
Multiple words can be separated using an underscore,
like this_is_a_long_variable.

20
LITERALS
Python literals constant or fixed values in the source code that
do not change during the execution of a program. Literals can
also be defined as the raw values that are given to Python
variables.

Literals are a way of representing data types in Python. They


can be anything from numbers to textual data, Boolean values,
etc. discuss the various types of literals are–
Types of Python Literals
The usage of Python literals varies according to the type. Let’s
look at the five types of literals Python has to offer:

21
Numeric Literals
These literals contain only immutable numeric values. By
immutable, we mean that the values cannot be changed during
runtime.
From Python 3 onwards, numeric literals have three subtypes:
• Integers
• Float
• Complex
Integers
All the natural numbers – negative, zero, or positive are
integers. They can also be categorized into the following types:
• Decimal integers – contain digits from 0 to 9. The base for
decimal values is 10.
• Binary integers – contain only two digits- 0 and 1. The base for
binary values is 2 and prefixed with “0b”.
• Octal integers – contain the digits from 0 to 7. The base for
octal values is 8. In Python, the octal values are prefixed with
“0o”.
• Hexadecimal integers – Contain digits from 0 to 9 and
alphabets from A to F.
• examples of integer literals:
#Positive
x = 734

22
#Negative
y = -8672
#Binary
a = 0b111001100
#Decimal
b = 21
#Octal
c = 0o544
#Hexadecimal
d = 0xC9

print (x,y)
print(a, b, c, d)
Output:

Float

23
Float literals or floating-point literals contain numeric values in
decimal points. They are also sometimes referred to as real
literals. They are categorized into two main types:
• Fractional – contain whole numbers and decimal points.
#Positive
x = 1090.0
#Negative
y = -227.0
• Exponential – these values are represented in the powers of
10, represented by the letter e or E. The digits before the
symbol E in an exponential literal are known as
the mantissa and the digits succeeding the symbol E are
the exponent. The exponent value describes the placement of
the decimal point.
#Positive
print(25.53E3) #Decimal point will jump 3 places
#Negative
print(-105.03E5) #Decimal point will jump 5 places
Output:

24
Complex
Complex literals are represented as X+Yj, where X is the real
part of the value and Yj is the imaginary or complex part.
Here,j=-1 examples of complex literals are:
#Positive
print(12 + 8j)
#Negative
print(-5j)
Output:

String Literals

These literals contain textual data in the form of characters,


enclosed within quotes. Based on quotes, the string literals are
divided into two subtypes:
• Single-line
• Multi-line
Let’s look at both of them in detail –
Single-line String Literals
Single-line string literals are enclosed within a single quote (‘ ‘)
or double quotes (” “).

25
examples of string literals:
#Single line string literals
print('Python Tutorial')
Output:

Multi-line String Literals


Multi-line string literals are a collection of characters that span
multiple lines. In Python, they can be declared in two ways:
• Backlashes – using a backlash at the end of each line.
#Multi-line string literals
str = "Welcome\
to\
Naukri\
Learning"
print(str)
Output:

Triple quotes – you can also enclose multi-line strings in triple


quotes (“””).
#Multi-line string literals
str = """This
is

26
a
Python
Tutorial"""
print(str)
Output:

Boolean Literals

These literals take only two values: True (aka 1) and False (aka
0).
Let’s look at the below example:
#Boolean Literals
x = 1.0
a = (x == 1)
print("a is", a)
b = (x == 7)
print("b is", b)
Output:

27
OPERATORS
Python Operators
The operator can be defined as a symbol which is responsible
for a particular operation between two operands. Operators are
the pillars of a program on which the logic is built in a specific
programming language. Python provides a variety of operators,
which are described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations
between two operands. It includes + (addition), - (subtraction),
*(multiplication), /(divide), %(reminder), //(floor division), and
exponent (**) operators.
Consider the following table for a detailed explanation of
arithmetic operators.

28
Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 =>


a+b = 30

- (Subtraction) It is used to subtract the second operand from the first


operand. If the first operand is less than the second operand,
the value results negative. For example, if a = 20, b = 10 => a -
b = 10

/ (divide) It returns the quotient after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a/b = 2.0

* (Multiplication) It is used to multiply one operand with the other. For


example, if a = 20, b = 10 => a * b = 200

% (reminder) It returns the reminder after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a%b = 0

** (Exponent) It is an exponent operator represented as it calculates the


first operand power to the second operand.

// (Floor division) It gives the floor value of the quotient produced by dividing
the two operands.

Comparison operator
Comparison operators are used to comparing the value of the
two operands and returns Boolean true or false accordingly. The
comparison operators are described in the following table.

29
Operator Description

== If the value of two operands is equal, then the condition becomes


true.

!= If the value of two operands is not equal, then the condition


becomes true.

<= If the first operand is less than or equal to the second operand,
then the condition becomes true.

>= If the first operand is greater than or equal to the second operand,
then the condition becomes true.

> If the first operand is greater than the second operand, then the
condition becomes true.

< If the first operand is less than the second operand, then the
condition becomes true.

Assignment Operators
The assignment operators are used to assign the value of the
right expression to the left operand. The assignment operators
are described in the following table.

Operator Description

= It assigns the value of the right expression to the left operand.

30
+= It increases the value of the left operand by the value of the right
operand and assigns the modified value back to left operand. For
example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.

-= It decreases the value of the left operand by the value of the right
operand and assigns the modified value back to left operand. For
example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right
operand and assigns the modified value back to then the left
operand. For example, if a = 10, b = 20 => a* = b will be equal to a = a*
b and therefore, a = 200.

%= It divides the value of the left operand by the value of the right
operand and assigns the reminder back to the left operand. For
example, if a = 20, b = 10 => a % = b will be equal to a = a % b and
therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will
assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will


assign 4//3 = 1 to a.

Bitwise Operators
The bitwise operators perform bit by bit operation on the values
of the two operands. Consider the following example.
For example,

31
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description

& (binary and) If both the bits at the same place in two operands are 1, then 1 is
copied to the result. Otherwise, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the
resulting bit will be 1.

^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise,
the resulting bit will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit
is 0, the resulting bit will be 1 and vice versa.

<< (left shift) The left operand value is moved left by the number of bits present
in the right operand.

>> (right shift) The left operand is moved right by the number of bits present in
the right operand.

32
Logical Operators
The logical operators are used primarily in the expression
evaluation to make a decision. Python supports the following
logical operators.

Operator Description

and If both the expression are true, then the condition will be true. If a
and b are the two expressions, a → true, b → true => a and b →
true.

or If one of the expressions is true, then the condition will be true. If


a and b are the two expressions, a → true, b → false => a or b →
true.

not If an expression a is true, then not (a) will be false and vice versa.

Membership Operators
Python membership operators are used to check the
membership of value inside a Python data structure. If the value
is present in the data structure, then the resulting value is true
otherwise it returns false.

Operator Description

in It is evaluated to be true if the first operand is found in the second


operand (list, tuple, or dictionary).

33
not in It is evaluated to be true if the first operand is not found in the
second operand (list, tuple, or dictionary).

Identity Operators
The identity operators are used to decide whether an element
certain class or type.

Operator Description

is It is evaluated to be true if the reference present at both sides point


to the same object.

is not It is evaluated to be true if the reference present at both sides do


not point to the same object.

Operator Precedence
The precedence of the operators is essential to find out since it
enables us to know which operator should be evaluated first.
The precedence table of the operators in Python is given below.

Operator Description

** The exponent operator is given priority over all the others used in
the expression.

~+- The negation, unary plus, and minus.

34
* / % // The multiplication, divide, modules, reminder, and floor division.

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greater than,
greater then equal to).

<> == != Equality operators.

= %= /= //= -= Assignment operators


+=
*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

35
BAREBONES
OF A PYTHON
PROGRAM
The barebones of python program are Expressions, Statements,
Comments, Functions and Block & Indentation.
1. Expression:
Expression is evaluated and produces the results.
Ex: (10=2)/2
2. Statements:
Indicates that we are doing something.
Ex: a=10
print("Calling in proper sequence")
3. Comments:
Comments are readable messages for a programmer but it
is overlooked by the python interpreter.
a. Single line comment (#)
b. Multi-line comment (''' ''')
Ex: #this is a single-line comment
''' this is
multiple '''
4. Function:
A function is a block of code which only runs when it is
called. Ex: getStudentMarks()

36
5. Block & Indentation:
A group of statements in block indentation at the same level
creates a block. Ex: all the statements that are under the
function getStudentMarks()

37
FLOW CONTROL
STATEMENTS
The order of execution of the statements in a program is known
as flow of control. The flow of control can be implemented using
control structures. Python supports two types of control
structures—selection and repetition.

Selection Statement (Conditional Statement)

Conditions are tested by selection statements, This type of


statement depending on the condition and generate the result
based on condition. If a condition is met in this sentence, a true
block is run; else, a false block is. example of selection
statement is If…Else statement and Switch Statement.

If Statement having three types –

1. If – Else Statement
2. Elif Statement
3. Nested If Statement

>>If – Else Statement

If statement called if..else statement allows us to write two


alternative paths and the control condition determines which

38
path gets executed. The syntax for if..else statement is as
follows.

The syntax of if statement is:


if condition:
statement(s)
else:
statement(s)
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
else :
print(“a is greater than b”)

>>Elif Statement

You can build a chain of if statements using the elif statement.


Before the end of the elif chain is reached or one of the if
expressions is true, the if statements are evaluated one at a
time. If there is no true expression at the end of the elif chain,
then else statement will be execuited.

The syntax for a selection structure using elif is as shown


below.

39
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

Indentation

The statements included within a block are typically enclosed in


curly brackets in programming languages. Python, however,
uses indentation for both block and nested block structures.
Indentation is the practise of placing leading whitespace
(spaces and tabs) at the start of a sentence.

40
LOOPING
Looping – The ability to repeatedly run a group of statements in
a programme based on a condition is provided by looping
constructs. While a certain logical condition is true, the
statements in a loop are repeated again.

There are two type of looping –

1. Entry Control Loop – The loop which check the condition


first and then execuite the body of loop is known as entry
control loop. example, for & while
2. Exit Control Loop – The loop which execuite the body of loop
first and then check the condition is known as exit control
loop. example do-while

>>For Loop

The for statement allows you to specify how many times a


statement or compound statement should be repeated. A for
statement’s body is executed one or more times until an
optional condition is met.

Syntax of the For Loop

for <control-variable> in <sequence/ items in range>:


<statements inside body of the loop>

41
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

>>The ‘While’ Loop

While a loop’s control condition is true, a block of code is


continuously run using the while statement. The while loop’s
control condition is carried out before any statements inside the
loop are performed. The loop continues as long as the control
condition is true after each iteration. The statements in the body
of the loop are not performed while this condition is false, and
instead, control is passed to the statement that follows the
while loop’s body. The body is not even once run if the while
loop’s initial condition is false.

Syntax of while Loop

while test_condition:
body of while
Example:
i = 1
while i < 6:
print(i)
i += 1

42
>>Nested Loops

A loop may contain another loop inside it. A loop inside another
loop is called a nested loop. Python does not impose any
restriction on how many loops can be nested inside a loop or on
the levels of nesting. Any type of loop (for/while) may be nested
within another loop (for/while).

Example:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

43

You might also like