0% found this document useful (0 votes)
9 views70 pages

Python Programming 1

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

Python Programming 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

PYTHON

PROGRAMMING
UNIT 1

By Ms. K. S. Jeswani
INTRODUCTION
• Python is a general-purpose, dynamically
typed, high-level, compiled and interpreted,
garbage-collected, and purely object-oriented
programming language that supports
procedural, object-oriented, and functional
programming.
• Python is a widely used high-level,
interpreted programming language.
• It was designed with an emphasis on code
readability, and its syntax allows
programmers to express their concepts in
fewer lines of code.
• Python is a programming language that lets
you work quickly and integrate systems more
HISTORY
• Python laid its foundation in the late 1980s.
• The implementation of Python was started in
December 1989 by Guido Van Rossum at CWI in
Netherland.
• In February 1991, Guido Van Rossum published the code
(labeled version 0.9.0) to alt.sources.
• In 1994, Python 1.0 was released with new features like
lambda, map, filter, and reduce.
• Python 2.0 added new features such as list
comprehensions, garbage collection systems.
• On December 3, 2008, Python 3.0 (also called "Py3K") was
released. It was designed to rectify the fundamental flow
of the language.
• ABC programming language is said to be the predecessor
of Python language, which was capable of Exception
Handling and interfacing with the Amoeba Operating
System.
• The following programming languages influence Python -
• ABC language
Easy to
Use &
Read
Dynami
Open
cally
Source
Typed

Rich Featur
Standar High
d es of Level
Library Python
Cross
Compile
Platfor
d&
m
Interpre
Compat Garbag ted
ibility e
Collecte
d
FEATURES
• Easy to use and Read - Python's syntax is clear
and easy to read, making it an ideal language for
both beginners and experienced programmers. This
simplicity can lead to faster development and
reduce the chances of errors.
• Dynamically Typed - The data types of variables
are determined during run-time. We do not need to
specify the data type of a variable during writing
codes.
• High-level - High-level language means human
readable code.
• Compiled and Interpreted - Python code first gets
compiled into bytecode, and then interpreted line by
line. When we download the Python in our system
form org we download the default implement of
Python known as CPython. CPython is considered to
be Complied and Interpreted both.
FEATURES
• Garbage Collected - Memory allocation and de-
allocation are automatically managed.
Programmers do not specifically need to manage
the memory.
• Cross-platform Compatibility - Python can be
easily installed on Windows, macOS, and various
Linux distributions, allowing developers to create
software that runs across different operating
systems.
• Rich Standard Library - Python comes with
several standard libraries that provide ready-to-use
modules and functions for various tasks, ranging
from web development and data manipulation to
machine learning and networking.
• Open Source - Python is an open-source, cost-
free programming language. It is utilized in several
APPLICATION
• Data Science AREAs of Python
• Desktop • Computer Vision
Applications or Image
• Console-based Processing
Applications Applications
• Mobile • Audio and Music
Applications • Writing scripts
• Software • Speech
Development Recognition
• Artificial • Scientific
Intelligence computing
• Web Applications • Education
• Enterprise • Testing
Applications • Gaming
• 3D CAD • IoT
Applications • Networking
• APPLICATIONS
Data Science: Data Science is a vast field, and Python is an important
language for this field because of its simplicity, ease of use, and availability
of powerful data analysis and visualization libraries like NumPy, Pandas, and
Matplotlib.
• Desktop Applications: PyQt and Tkinter are useful libraries that can be used
in GUI - Graphical User Interface-based Desktop Applications. There are
better languages for this field, but it can be used with other languages for
making Applications.
• Console-based Applications: Python is also commonly used to create
command-line or console-based applications because of its ease of use and
support for advanced features such as input/output redirection and piping.
• Mobile Applications: While Python is not commonly used for creating mobile
applications, it can still be combined with frameworks like Kivy or BeeWare
to create cross-platform mobile applications.
• Software Development: Python is considered one of the best software-
making languages. Python is easily compatible with both from Small Scale to
Large Scale software.
• Artificial Intelligence: AI is an emerging Technology, and Python is a perfect
language for artificial intelligence and machine learning because of the
availability of powerful libraries such as TensorFlow, Keras, and PyTorch.
• Web Applications: Python is commonly used in web development on the
backend with frameworks like Django and Flask and on the front end with
tools like JavaScript HTML and CSS.
• Enterprise Applications: Python can be used to develop large-scale
enterprise applications with features such as distributed computing,
networking, and parallel processing.
APPLICATIONS
• Machine Learning: Python is widely used for machine learning due to its simplicity, ease
of use, and availability of powerful machine learning libraries.
• Computer Vision or Image Processing Applications: Python can be used for computer
vision and image processing applications through powerful libraries such as OpenCV and
Scikit-image.
• Speech Recognition: Python can be used for speech recognition applications through
libraries such as SpeechRecognition and PyAudio.
• Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced
numerical computing capabilities for tasks like data analysis, machine learning, and
more.
• Education: Python's easy-to-learn syntax and availability of many resources make it an
ideal language for teaching programming to beginners.
• Testing: Python is used for writing automated tests, providing frameworks like unit tests
and pytest that help write test cases and generate reports.
• Gaming: Python has libraries like Pygame, which provide a platform for developing
games using Python.
• IoT: Python is used in IoT for developing scripts and applications for devices like
Raspberry Pi, Arduino, and others.
• Networking: Python is used in networking for developing scripts and applications for
network automation, monitoring, and management.
• DevOps: Python is widely used in DevOps for automation and scripting of infrastructure
management, configuration management, and deployment processes.
• Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial
modeling and analysis.
• Audio and Music: Python has libraries like Pyaudio, which is used for audio processing,
synthesis, and analysis, and Music21, which is used for music analysis and generation.
• Writing scripts: Python is used for writing utility scripts to automate tasks like file
STRUCTURE OF PYTHON
PROGRAM
• As a dynamically typed, interpreted language, Python
has a simpler basic program structure than compiled
languages like C and C++.
• Python scripts execute top-to-bottom, so order is very
important.
• The use of proper whitespace for indentation also
factors prominently since it defines scope and code
blocks in Python.
• There is no need to explicitly declare variable types
either.
• Python Program Consists of –
The several components that a Python program
holds are -
• Expressions - An expression represents something,
like a number, a string, or an element. Any value is an
expression.
• Statements - Anything that does something is a
statement. Any assignment to a variable or function
call is a statement. Any value contained in that
statement is an expression.
• Comments - Comments are the additional information
provided against a statement or a chunk of code for
the better clarity of the code. Interpreter ignores the
comments and does not count them in commands.
• Functions - Function is a set of instructions defined
under a particular name, which once written can be
called whenever and wherever required.
• Block(s) - A block refers to a group of statements
which are part of another statement or function. All
statements inside a block are indented at the same
level
PYTHON BASICS

• Indentation
• Variables
• Identifiers
• Keywords
• Comments
(spaces or tabs) at the beginning of code line.
• It is used to define the code blocks.
• Indentation is crucial in Python because, unlike
many other programming languages that use
braces "{}" to define blocks, Python uses
indentation.
• It improves the readability of Python code, but on
other hand it became difficult to rectify indentation
errors.
• Even one extra or less space can lead to
indentation error.
• Python Variables -
• A variable is like a container that stores values you
can access or change.
• The purpose of using variables is to allow the
stored values to be used later on.
• Variables in Python are essentially named
references pointing to objects in memory. (Unlike
some other languages, you don't need to declare a
variable's type explicitly in Python)
• Python Identifiers -
• In Python, identifiers are unique names that
are assigned to variables, functions, classes,
and other entities.
• They are used to uniquely identify the entity
within the program.
• They should start with a letter (a-z, A-Z) or
an underscore "_" and can be followed by
letters, numbers, or underscores.
• Python keywords -
• Keywords in Python are reserved words that
have special meanings and serve specific
purposes in the language syntax.
• They cannot be used as identifiers (names
for variables, functions, classes, etc.).
• Below is the list of Keywords -
• Comments in Python -
• Comments in Python are statements written
within the code.
• They are meant to explain, clarify, or give
context about specific parts of the code.
• Python Single Line Comment -
• Single line comments are preceded by the "#"
symbol. Everything after this symbol on the
same line is considered a comment.
• Python Multi-line Comment
• Python doesn't have a specific syntax for multi-
line comments.
• However, programmers often use multiple
single-line comments, one after the other, or
sometimes triple quotes (either ''' or """), even
though they're technically string literals.
NUMERIC DATA TYPES
• Represents the data that has a numeric value.
• A numeric value can be an integer, a floating
number, or a complex number.
• These values are defined as Python int , Python
float , and Python complex classes in Python .
• Integers – Value is represented by int class. It
contains positive or negative whole numbers (without
fractions or decimals). There is no limit to how long an
integer value can be.
• Float – Value is represented by the float class. It is a
real number with a floating-point representation. It is
specified by a decimal point. (Optionally, the character
e or E followed by a positive or negative integer may
be appended to specify scientific notation.)
• Complex Numbers – A complex number is
represented by a complex class. It is specified as (real
part) + (imaginary part)j . For example – 2+3j
• Integer Value -
• a=5
• print("The type of a", type(a))
• Floating Point Value -
• b = 40.5
• print("The type of b", type(b))
• Complex Value -
• c = 1+3j
• print("The type of c", type(c))
• print(" c is a complex number",
isinstance(1+3j,complex))
• Output:
• The type of a <class 'int'>
• The type of b <class 'float'>
• The type of c <class 'complex'>
• c is complex number: True
BOOLEAN DATA TYPES
• Python Data type with one of the two
built-in values, True or False.
• Boolean objects that are equal to True
are truthy (true), and those equal to
False are falsy (false).
• Non-Boolean objects can be evaluated
in a Boolean context as well and
determined to be true or false.
• It is denoted by the class bool.
• False can be represented by the 0 or the
letter "F," while true can be represented
EXAMPLE -
# Python program to check the boolean
type
• print(type(True))
• print(type(False))
• print(false)
Output –
• <class 'bool'>
• <class 'bool'>
• NameError: name 'false' is not defined
SEQUENCE DATA TYPES
• The sequence Data Type in Python is the
ordered collection of similar or
different Python data types.
• Sequences allow storing of multiple
values in an organized and efficient
fashion.
• There are several sequence data types of
Python -
• Python String
• Python List
• Python Tuple
OPERATORS
• Operators are used to perform operations on
variables and values.
• OPERATORS: These are the special symbols. Eg- + ,
* , /, etc.
• OPERAND: It is the value on which the operator is
applied.
• Python divides the operators in the following groups -
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic Operators Assignment Operators
Operat Name Exampl Operato Example Same As
or e r
+ Addition x+y = x=5 x=5
+= x += 3 x=x+3
- Subtraction x-y
-= x -= 3 x=x-3
* Multiplicatio x*y
*= x *= 3 x=x*3
n
/= x /= 3 x=x/3
/ Division x/y
%= x %= 3 x=x%3
% Modulus x%y //= x //= 3 x = x // 3
** Exponentiati x ** y **= x **= 3 x = x ** 3
on &= x &= 3 x=x&3
// Floor x // y |= x |= 3 x=x|3
division ^= x ^= 3 x=x^3
>>= x >>= 3 x = x >>
3
<<= x <<= 3 x = x <<
3
:= print(x := 3) x=3
print(x)
Comparison Operators Identity Operators
Operato Name Example Operat
Description Example
r or
== Equal x == y Returns True if
is both variables are x is y
!= Not equal x != y the same object
> Greater x>y Returns True if
than both variables are
is not x is not y
< Less than x<y not the same
object
>= Greater x >= y
than or
equal to
<= Logical
Less than Operators
x <= y
or equal to
Operato
Description Example
r
Returns True if both
and x < 5 and x < 10
statements are true
Returns True if one of the
or x < 5 or x < 4
statements is true
Reverse the result, returns not(x < 5 and x <
not
Membership Operators Bitwise Operators
Operat Operat Examp
Description Example Name Description
or or le
Sets each bit to 1
Returns True & AND x&y
if both bits are 1
if a sequence
Sets each bit to 1
with the | OR if one of two bits x|y
in specified x in y is 1
value is
Sets each bit to 1
present in the ^ XOR if only one of two x^y
object bits is 1
Returns True ~ NOT Inverts all the bits ~x
if a sequence Shift left by
with the pushing zeros in
x not in Zero fill
not in specified <<
left shift
from the right and x << 2
y let the leftmost
value is not
Ternary
present Operators
in the bits fall off
object Shift right by
pushing copies of
Signed
the leftmost bit in
>> right x >> 2
from the left, and
shift
let the rightmost
bits fall off
OPERATORS PRECEDENCE

• Operator precedence describes the order in which


operations are performed.
• When multiple operators are present in an
expression, the ones with higher precedence are
evaluated first.
• In the case of operators with the same
precedence, their associativity comes into play,
determining the order of evaluation.
No. Operators Description Associativity
1 () Parentheses Left to right
x[index], x[index:inde
2 Subscription, slicing Left to right
x]
3 await x Await expression N/A
4 ** Exponentiation Right to left
5 +x, -x, ~x Positive, negative, bitwise NOT Right to left

Multiplication, matrix, division,


6 *, @, /, //, % Left to right
floor division, remainder
7 +, – Addition and subtraction Left to right
8 <<, >> Shifts Left to right
9 & Bitwise AND Left to right
10 ^ Bitwise XOR Left to right
11 | Bitwise OR Left to right
in, not in, is, is
Comparisons, membership
12 not, <, <=, >, >=, ! Left to Right
tests, identity tests
=, ==
13 not x Boolean NOT Right to left
14 and Boolean AND Left to right
15 or Boolean OR Left to right
16 if-else Conditional expression Right to left
17 lambda Lambda expression N/A
TYPE CONVERSION
• Theact of changing an object's data type is
known as type conversion.
• Python type conversion, also known as
typecasting or type coercion, is the process of
changing the data type of a value from one type
to another.
• This is a fundamental concept in Python,
allowing for operations and manipulations
involving different data types.
• Thereare two main types of type conversion in
Python –
• Python Implicit Type Conversion
• Python Explicit Type Conversion
• This occurs automatically when the Python interpreter
handles the conversion without explicit instructions
from the programmer.
• Python prevents Implicit Type Conversion from losing
data.
• It typically happens in situations where mixing different
data types in an expression, and Python converts the
smaller or less complex data type to the larger or more
complex one to prevent data loss.

• Explicit Type Conversion -


• In Explicit Type Conversion in Python, the data type is
manually changed by the user as per their requirement.
• With explicit type conversion, there is a risk of data loss
since we are forcing an expression to be changed in
some specific data type.
• We use the built-in functions like int(), float(), str(), etc
to perform explicit type conversion.
• This type of conversion is also called typecasting
because the user casts (changes) the data type of the
• int(a, base): This function converts any data type to an integer.
'Base' specifies the base in which the string is if the data type is a
string.
• float(): This function is used to convert any data type to a floating-
point number.
• Type conversion using ord(), hex(), oct()
• ord(): This function is used to convert a character to an integer.
• hex(): This function is to convert an integer to a hexadecimal string.
• oct(): This function is to convert an integer to an octal string.
• Type conversion using tuple(), set(), list()
• tuple(): This function is used to convert to a tuple.
• set(): This function returns the type after converting to set.
• list(): This function is used to convert any data type to a list type.
• Python code to demonstrate Type conversion using dict(),
complex(), str()
• dict(): This function is used to convert a tuple of order (key, value)
into a dictionary.
• str(): Used to convert an integer into a string.
• complex(real,imag) : This function converts real numbers to
complex(real,imag) number.
• Convert ASCII value to characters
• chr(number): This function converts a number to its corresponding
STATEMENT

•A statement in Python is an instruction to


perform a specific action.
• Itis the smallest unit or line of code that the
Python interpreter can execute.
• The token character NEWLINE is used to end a
statement in Python, denoting that each line in a
Python script includes a statement, helping
users achieve the desired output.
TYPES OF STATEMENTS
• Simple Statements • Python
• Multi-Line Statements Expression
• Conditional statements
Statements
• If • return statement
• if else Statement • pass statement
• if-elseif-else • break statement
Statement
• Nested If Statement • continue
• Loop Statements statement
• for loop • del statement
• while loop
• try-except
• import
statement
Multiple Line Statements
• Writing a long statement in a code is not feasible
or readable. Breaking a long line of code into
multiple lines makes is more readable.
• Using Backslashes (\)
• In Python, you can break a statement into multiple
lines using the backslash (\). This method is useful,
especially when we are working with strings or
mathematical operations.
• Example -
• sentence = "This is a very long sentence that we
want to " \
• "split over multiple lines for better
readability."
• print(sentence)
• # For mathematical operations
• total = 1 + 2 + 3 + \
• 4+5+6+\
• 7+8+9
Continuation of Statements in Python
• In Python, statements are typically written on
a single line.
• However, there are scenarios where writing a
statement on multiple lines can improve
readability or is required due to the length of
the statement.
• This continuation of statements over multiple
lines is supported in Python in various ways -
• Implicit Continuation -
• Python implicitly supports line continuation within
parentheses (), square brackets [], and curly braces
{}.
• This is often used in defining multi-line lists, tuples,
dictionaries, or function arguments.
• Explicit Continuation -
• You can use backslash '\' to indicate that a
statement should continue on the next line.
EXPRESSIONS
•A combination of operands and operators is
called an expression.
• The expression in Python produces some value
or result after being interpreted by the Python
interpreter.
• An expression in Python is a combination of
operators and operands.
• Following are the various types of Expressions –
• Constant Expressions
• Arithmetic Expressions
• Integral Expressions
• Floating Expressions
• Relational Expressions
• Logical Expressions
• Bitwise Expressions
• Combinational Expressions
• Constant Expressions - These are the expressions that have
constant values only.
• Arithmetic Expressions - An arithmetic expression is a
combination of numeric values, operators, and sometimes
parenthesis. The result of this type of expression is also a numeric
value. The operators used in these expressions are arithmetic
operators.
• Integral Expressions - These are the kind of expressions that
produce only integer results after all computations and type
conversions.
• Floating Expressions - These are the kind of expressions which
produce floating point numbers as result after all computations and
type conversions.
• Relational Expressions - In these types of expressions,
arithmetic expressions are written on both sides of relational
operator (> , < , >= , <=). Those arithmetic expressions are
evaluated first, and then compared as per relational operator and
produce a boolean output in the end. These expressions are also
called Boolean expressions.
• Logical Expressions - These are kinds of expressions that result
in either True or False. It basically specifies one or more conditions.
• Bitwise Expressions - These are the kind of expressions in which
computations are performed at bit level.
• Combinational Expressions - We can also use different types of
expressions in a single expression, and that will be termed as
USER INPUT
• input () function first takes the input from the user and
converts it into a string.
• The type of the returned object always will be <class ‘str’>.
• It does not evaluate the expression it just returns the
complete statement as String.
• How the input function works in Python -
• When input() function executes program flow will be stopped
until the user has given input.
• The text or message displayed on the output screen to ask a
user to enter an input value is optional i.e. the prompt, which
will be printed on the screen is optional.
• Whatever you enter as input, the input function converts it
into a string. if you enter an integer value still input() function
converts it into a string.
• Input taken from user needs to explicitly convert it into an
integer in your code using typecasting like “int(input())” ,
“float(input())”.
Taking Input from User in Python
• The input() function in Python is used to
take user input from the console.
• The program execution halts until the user
provides input and presses "Enter".
• The entered data is then returned as a
string.
Print Output in Python
• Printing output in Python is straightforward,
using the print() function.
• This function allows us to display text,
variables, and expressions on the console.
• Example -
• # Taking input from the user
• name = input("Please enter your name: ")
• # Print the input
Print Function Parameters
Paramet
Description Default
er
One or more values to print
*objects (can be strings, variables, –
etc.)
String inserted between ' ' (a
sep
values space)
String appended after the '\n'
end
last value (newline)
A file-like object (e.g., a file
file or sys.stdout) where the sys.stdout
output is sent
If True, the output is forcibly
flush False
flushed to the stream
Strings
• Python Strings are arrays of bytes
representing Unicode characters.
• In Python, there is no character data
type, a character is a string of length
one.
• It is represented by str class.
• Strings in Python can be created using
single quotes, double quotes, or even
triple quotes.
• We can access individual characters of a
String using index.
• Accessing string is possible in both ways,
Forward Direction as well as Backward
String Data Type
• String Slicing –
• Slicing is a way to extract portion of a string by
specifying the start and end indexes.
• The syntax for slicing is string[start:end],
where start starting index and end is stopping
index (excluded).
• String Immutability –
• Strings in Python are immutable.
• This means that they cannot be changed after
they are created.
• If we need to manipulate strings then we can
use methods like concatenation, slicing, or
formatting to create new strings based on the
original.
• Deleting a String -
• We cannot delete or remove the characters
from the string. But we can delete the entire
• Built In Functions for Strings –
• Refer Word File
String Operations
Op Description
It is known as concatenation operator used to join the strings
+
given either side of the operator.
It is known as repetition operator. It concatenates the multiple
*
copies of the same string.
It is known as slice operator. It is used to access the sub-
[]
strings of a particular string.
It is known as range slice operator. It is used to access the
[:]
characters from the specified range.
It is known as membership operator. It returns if a particular
in
sub-string is present in the specified string.
It is also a membership operator and does the exact reverse of
not in in. It returns true if a particular substring is not present in the
specified string.
It is used to specify the raw string. Raw strings are used in the
cases where we need to print the actual meaning of escape
r/R
characters such as "C://python". To define any string as a raw
string, the character r or R is followed by the string.
It is used to perform string formatting. It makes use of the
format specifiers used in C programming like %d or %f to map
%
their values in python. We will discuss how formatting is done
Escape Sequence Characters
Sr. Escape Description
Sequence
1. \newline It ignores the new line.
2. \\ Backslash
3. \' Single Quotes
4. \\'' Double Quotes
5. \a ASCII Bell
6. \b ASCII Backspace(BS)
7. \f ASCII Formfeed
8. \n ASCII Linefeed
9. \r ASCII Carriege Return(CR)
10. \t ASCII Horizontal Tab
11. \v ASCII Vertical Tab
12. \ooo Character with octal value
13 \xHH Character with hex value.
CONTROL FLOW
• Control flow in Python is the order in which the
Python interpreter executes statements in a
program.
• The Python interpreter reads a program one
line at a time, from left to right and top to
bottom.
• The interpreter executes operations and
functions in the order that it encounters them.
• Python program control flow is regulated by
various types of conditional statements, loops,
and function calls.
CONDITIONAL STATEMENTS
•A conditional statement in Python is a
statement that controls the flow of a
program based on a condition.
• It helps make decisions in the code, which
can make it easier to read and more
efficient.
• How it works -
• A conditional statement evaluates a condition
and decides whether to execute a block of code
• The condition can be based on variable values or
comparison results
• The program can react differently depending on
whether the condition is true or false
IF STATEMENTS
• if statement is the simplest decision-making
statement.
• Ifthe condition evaluates to True, the block of
code inside the if statement is executed.
IF….ELSE STATEMENT
• if…else statement is a control statement that helps
in decision-making based on specific conditions.
When the if condition is False.
• If the condition in the if statement is not true, the
else block will be executed.
• If Else in One-line- If we need to
execute a single statement inside
the if or else block then one-line
shorthand can be used.
• Example -
 number = -2
 #Ternary conditional to check if
number is positive or negative
 result = "Positive" if number
>= 0 else "Negative“
 print(result)
• Using Logical Operators with
If..Else - We can combine multiple
conditions using logical operators
such as and, or, and not.
• Example -
age = 25
experience = 10
# Using > & 'and' with IF..ELSE
if age > 23 and experience > 8:
print("Eligible.")
else:
IF…ELIF…ELSE STATEMENT
• if-elif-else statement in Python is used for multi-way
decision-making.
• This allows you to check multiple conditions
sequentially and execute a specific block of code
when a condition is True.
• If none of the conditions are true, the else block is
executed.
IF…ELIF…ELSE STATEMENT
LOOPING STATEMENT
• A loop is an instruction that
repeats multiple times as
long as some condition is
met.
• Type of Loops –
• For Loop - A for loop in
Python is used to iterate over
a sequence (list, tuple, set,
dictionary, and string).
• While Loop - The while loop
is used to execute a set of
statements as long as a
condition is true.
• Nested Loop - If a loop
exists inside the body of
another loop, it is called a
nested loop.
LOOPING STATEMENT
Python's for loop is designed to repeatedly execute a code block
while iterating through a list, tuple, dictionary, or other iterable
objects of Python. The process of traversing a sequence is known as
iteration. For Loop iterates until the final item of the sequence are
reached.

While loops are used in Python to iterate until a specified condition is


met.
FOR LOOP
• The range() Function - It is a built-in
Python method that fulfills the requirement
of providing a series for the for expression to
run over by following a particular pattern.
• Iteratingby Using Index of Sequence -
Another method of iterating through every
item is to use an index offset within the
sequence.
• Using else Statement with for Loop -
After the circuit has finished iterating over
the list, the else clause is combined with a
for Loop.
WHILE LOOP
• Instructions for using WHILE LOOP -
• The statements of the Python while loop are
dictated by indentation.
• The code block begins when a statement is
indented & ends with the very first unindented
statement.
• Any non-zero number in Python is interpreted
as boolean True. False is interpreted as None
and 0.
• Single Statement While Loop -
• Similar to the if statement syntax, if our while
clause consists of one statement, it may be
written on the same line as the while keyword.
INFINITE LOOP
• Aninfinite loop in Python is a loop that
continues to run without end.
• Thishappens when the loop's condition is
always true, or when the loop doesn't have
a terminating condition.
• Infinite
loops can be useful for programs
that need to run continuously, like server
applications.
• Theycan also be useful for real-time data
monitoring scripts.
• InPython, you can create an infinite loop
using the while statement.
NESTED LOOP

• Python programming language allows to use one


loop inside another loop which is called nested
loop.
• Python Nested Loops Syntax -
Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop
Statement inside Outer_loop
JUMPING STATEMENTS
• Jump statements are used to change the
flow of a program by transferring control
from one part to another.
• They can be used to exit loops, start new
iterations, or stop the execution of a
function.
• Python Uses following Jump Statements –
• Break Statement
• Continue Statement
• Pass Statement
BREAK STATEMENTS
• The break statement is the loop-control statement
used in Python to terminate a loop if a particular
external condition turns out to be true.
• As soon as the interpreter finds a break statement in
the code, it terminates the loop and transfers the
control to the immediately next statement to the
loop.
• This statement is almost always written in an if
statement in the loop's body and is also used in
switch-case statements to check a condition.
• Points to Remember -
• We cannot use a break statement without a loop. It raises an error.
• "SyntaxError:'break' outside loop".
• We can use break in switch-case statements.
• If the break statement is used in a nested loop inside the inner
loop, then the inner loop will be terminated.
• "break" is a reserved keyword in python.
• We cannot use labels, conditions, or other options with the break
CONTINUE STATEMENTS
•A continue statement is a jump statement that provides
us the loop control to completely skip or ignore an
iteration of the loop if a condition satisfies. It skips the
whole iteration and continues to the next iteration as its
name suggests.
• As soon as the interpreter finds a continue statement in
the code, it terminates the iteration and transfers the
control to the loop again to continue with the next
iteration.
• Points to Remember -
• "continue" is a reserved keyword in the python libraries.
• It is also written in an if statement inside the loop body.
• We cannot use a continue statement without a loop. It throws an
error:
• "SyntaxError:'continue' outside loop".
• If we use a continue statement in the inner loop of a nested loop,
then the inner loop iteration will be skipped. The outer loop won't
be affected.
• We cannot use labels, conditions, or other options with the
PASS STATEMENTS
• The pass statement is an interesting
statement, as when it gets executed
nothing happens.
• It plays the role of a placeholder. This
means that, if we want to write a piece of
code over there in the near future but we
cannot keep that space empty, then we
can use the pass statement.
• It is used to avoid getting an error from
keeping an empty space.
EXIT STATEMENT
• The exit() function in Python is used to exit or
terminate the current running script or program.
• Use it to stop the execution of the program at
any point.
• When the exit() function is called, the program
will immediately stop running and exit.
• The syntax of the exit() function is -
exit([status])
• status is an optional argument that represents the exit status of
the program, It can be an integer or a string. The exit status
value indicates the reason for program termination.
• If it's an integer, it should be in the range of 0 to 255
(inclusive).
• a status of 0 indicates successful execution.
• any non-zero status indicates an error or abnormal termination.
• If it's a string, it will be printed to the standard error stream
(stderr) before the program exits.
• If the status argument is omitted or not provided, the default
Examples of using the `status` parameter -
# Exit with a status code of 0 (successful
execution)
exit(0)
# Exit with a status code of 1 (indicating an error)
exit(1)
# Exit with a custom error message
exit("An error occurred. Exiting the
program.")
• https://www.toppr.com/guides/?s=python
• https://www.toppr.com/guides/python-guide/ref
erences/methods-and-functions/python-any/
• https://www.toppr.com/guides/python-guide/tut
orials/python-advanced-topics/python-example
s/
• https://www.naukri.com/code360/library/exit-in
-python

You might also like