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

Python Notes

Uploaded by

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

Python Notes

Uploaded by

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

Python Programming

Introduction
Python is one of the most popular programming languages today, known for its simplicity and ease
of use. It was created by Guido van Rossum and released in 1991.
Features of Python:
1. Python is object-oriented programming that supports polymorphism, abstraction, inheritance,
encapsulation, etc.
2. Indentation: Indentation is one of the greatest feature in python.
3. Free and open source
4. Large development community
5. Wide application: web development, Machine Learning, Data science, software development,
etc.

Python Character Set:


A character set is a set of valid characters acceptable by a programming language in scripting. In this
case, we are talking about the Python programming language. So, the Python character set is a valid set of
characters recognized by the Python language. These are the characters we can use during writing a script in
Python. Python supports all ASCII / Unicode characters including:

· Alphabets: All capital (A-Z) and small (a-z) alphabets.

· Digits: All digits 0-9.

· Special Symbols: Python supports all kinds of special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _ + –
={}[]\.

· White Spaces: White spaces like tab space, blank space, newline, and carriage return.

Other: All ASCII and UNICODE characters are supported by Python which constitutes the Python character
set.

Tokens:
A token is the smallest individual unit in a Python program. All statements and instructions in
a program are built with tokens. The various tokens in Python are:

Keywords:
Keywords are words with special meaning or significance in a programming language. They
can’t be used as variable names, function names, or any other random purpose. They are used for
their special features. In Python, we have 3 keywords: try, False, True, class, break, continue, and, as,
assert, while, for, in, raise, except, or, not, if, elif, print, import, etc.

Identifiers:
Identifiers are the names given to any variable, function, class, list, methods, etc. for their
identification. Python is a case-sensitive language with some rules and regulations to name an
identifier.

Literals or Values:
Literals are the fixed values or data items used in a source code. Python supports different
types of literals such as:
String Literals: The text written in single, double, or triple quotes represents the string
literals in Python. For example: “Computer Science”, ‘sam’, etc. We can also use triple quotes to
write multi-line strings.

# String Literals
a = 'Hello'
b = "World"
c = '''This is a
String Literal'''

# Driver code
print(a)
print(b)
print(c)

Character Literals: Character literal is also a string literal type in which the character is
enclosed in single or double-quotes.
# Character Literals
a = 'G'
b = "W"

# Driver code
print(a)
print(b)

Numeric Literals: These are the literals written in form of numbers. Python supports the
following numerical literals:
● Integer Literal: It includes both positive and negative numbers along with 0. It doesn’t
include fractional parts. It can also include binary, decimal, octal, hexadecimal literal.
● Float Literal: It includes both positive and negative real numbers. It also includes
fractional parts.
● Complex Literal: It includes a+bi numeral, here a represents the real part and b
represents the complex part.

# Numeric Literals
a = 5
b = 10.3
c = -17

# Driver code
print(a)
print(b)
print(c)

Boolean Literals: Boolean literals have only two values in Python. These are True and False.

# Boolean Literals
a=3
b = (a == 3)
c = True + 10

# Driver code
print(a, b, c)

Special Literals: Python has a special literal ‘None’. It is used to denote nothing, no values,
or the absence of value.

# Special Literals
var = None
print(var)

Literals Collections: Literals collections in python includes list, tuple, dictionary, and sets.
● List: It is a list of elements represented in square brackets with commas in between.
These variables can be of any data type and can be changed as well.
● Tuple: It is also a list of comma-separated elements or values in round brackets. The
values can be of any data type but can’t be changed.
● Dictionary: It is the unordered set of key-value pairs.
● Set: It is the unordered collection of elements in curly braces ‘{}’.
# Literals collections my_dict = {1:'one', 2:'two',
# List 3:'three'}
my_list = [23, "geek", 1.2, 'data']
# Set
# Tuple my_set = {1, 2, 3, 4}
my_tuple = (1, 2, 3, 'hello')
# Driver code
# Dictionary print(my_list)
print(my_tuple)
print(my_dict) print(my_set)

Operators:
These are the tokens responsible to perform an operation in an expression. The variables on
which operation is applied are called operands. Operators can be unary or binary. Unary operators
are the ones acting on a single operand like complement operator, etc. While binary operators need
two operands to operate.

Punctuators:
These are the symbols that used in Python to organize the structures, statements, and expressions.
Some of the Punctuators are: [ ] { } ( ) @ -= += *= //= **== = , etc.

Python Indentation
Python indentation refers to adding white space before a statement to a particular block of code. In other
words, all the statements with the same space to the left, belong to the same code block.

Python Data Types:


Python Data types are the classification or categorization of data items. It represents the kind
of value that tells what operations can be performed on a particular data. Since everything is an
object in Python programming, Python data types are classes and variables are instances (objects) of
these classes. The following are the standard or built-in data types in Python:

● Numeric
● Sequence Type
● Boolean
● Set
● Dictionary
● Binary Types( memoryview , bytearray , bytes )
Numeric Data Types in Python:
The numeric data type in Python represents the data that has a numeric value. A numeric
value can be an integer, a floating number, or even a complex number. These values are defined as
Python int , Python float , and Python complex classes in Python .

1. Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
2. Float – This 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.
3. Complex Numbers – A complex number is represented by a complex class. It is specified as
(real part) + (imaginary part)j . For example – 2+3j

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))

Sequence Data Types in Python


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
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection
of one or more characters put in a single quote, double-quote, or triple-quote. In Python, there
is no character data type Python, a character is a string of length one. It is represented by str
class.
Creating String
Strings in Python can be created using single quotes, double quotes, or even triple
quotes.

print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square
brackets [ ].
thislist = ["apple", "banana", "cherry"]
print(thislist)

Tuple Data Type


Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable i.e. tuples cannot be
modified after it is created. It is represented by a tuple class.

Boolean Data Type in Python


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). However 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.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw
an error.
a = True
print(type(a))
b = False
print(type(b))

Set Data Type in Python


In Python Data Types, a Set is an unordered collection of data types 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.
Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values, used to store data values like
a map, unlike other Python Data Types that hold only a single value as an element, a Dictionary
holds a key: value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.
Type Conversion:
Python defines type conversion functions to directly convert one data type to another which is useful
in day-to-day and competitive programming. This article is aimed at providing information about certain
conversion functions.
The act of changing an object’s data type is known as type conversion. The Python interpreter automatically
performs Implicit Type Conversion. Python prevents Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit type conversion, sometimes
referred to as type casting. When type casting, data loss could happen if the object is forced to conform to a
particular data type.
There are two types of Type Conversion in Python:
● Implicit Type Conversion
● Explicit Type Conversion
Implicit Type Conversion:
In Implicit type conversion of data types in Python, the Python interpreter automatically converts one
data type to another without any user involvement.

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.
● 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.
● 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.
● 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.
● 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.
● chr(number): This function converts a number to its corresponding ASCII character.

Keywords in Python
Python Keywords are some predefined and reserved words in Python that have special meanings.
Keywords are used to define the syntax of the coding. The keyword cannot be used as an identifier, function,
or variable name. All the keywords in Python are written in lowercase except True and False. There are 35
keywords in Python 3.11.

In Python, there is an inbuilt keyword module that provides an iskeyword() function that can be used
to check whether a given string is a valid keyword or not. Furthermore, we can check the name of the
keywords in Python by using the kwlist attribute of the keyword module.

Rules for Keywords in Python


● Python keywords cannot be used as identifiers.
● All the keywords in Python should be in lowercase except True and False.

Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a
combination of character digits and an underscore. They are case-sensitive i.e., ‘num’ and ‘Num’ and
‘NUM’ are three different identifiers in python. It is a good programming practice to give meaningful names
to identifiers to make the code understandable.
We can also use the Python string isidentifier() method to check whether a string is a valid identifier
or not.
Rules for Naming Python Identifiers
● It cannot be a reserved python keyword.
● It should not contain white space.
● It can be a combination of A-Z, a-z, 0-9, or underscore.
● It should start with an alphabet character or an underscore ( _ ).
● It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Python Operators
Operators in general are used to perform operations on values and variables. These are standard
symbols used for logical and arithmetic operations. In this article, we will look into different types of Python
operators.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.

Types of Operators in Python


1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators
7. Membership Operators

1. Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.

The precedence of Arithmetic Operators in Python is as follows:


● P – Parentheses
● E – Exponentiation
● M – Multiplication (Multiplication and division have the same precedence)
● D – Division
● A – Addition (Addition and subtraction have the same precedence)
● S – Subtraction

There are two types of division operators:


● Float division(/)
● Floor division(//)
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are
integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that
both integer and floating-point divisions return accurate results. For example, ’10/2′ results in
‘5.0’, and ‘-10/2’ results in ‘-5.0’.

Integer division( Floor division)


The quotient returned by this operator is dependent on the argument being passed. If any of
the numbers is float, it returns output in float. It is also known as Floor division because, if
any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python
operators. It provides results as follows: ’10//3′ equals ‘3’, ‘-5//2’ equals ‘-3’, ‘5.0//2′ equals
‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer division returns the largest integer less than or equal
to the division result.

2. Comparison Operators
In Python Comparison of Relational operators compares the values. It either returns True or
False according to the condition.

Precedence of Comparison Operators in Python


In Python, the comparison operators have lower precedence than the arithmetic operators. All
the operators within comparison operators have the same precedence order.
3. Logical Operators
Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It
is used to combine conditional statements.

Precedence of Logical Operators in Python


The precedence of Logical Operators in Python is as follows:

● Logical not
● logical and
● logical or

4. Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to
operate on binary numbers.
Precedence of Bitwise Operators in Python
The precedence of Bitwise Operators in Python is as follows:
● Bitwise NOT
● Bitwise Shift
● Bitwise AND
● Bitwise XOR
● Bitwise OR

5. Assignment Operators
Python Assignment operators are used to assign values to the variables.
6. Identity Operators
In Python, is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal do not imply that they
are identical.

7. Membership Operators
In Python, in and not in are the membership operators that are used to test whether a value or
variable is in a sequence.
Presence and Associativity of Operators:

Comments in Python:
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the
program.
Types of Comments in Python
There are three types of comments in Python:
● Single line Comments
● Multiline Comments
● String Literals
● Docstring Comments
1. Single-Line Comments
● Python single-line comment starts with the hashtag symbol (#) with no white spaces
and lasts till the end of the line.
● If the comment exceeds one line then put a hashtag on the next line and continue the
Python Comment.
● Python’s single-line comments are proved useful for supplying short explanations for
variables, function declarations, and expressions. See the following code snippet
demonstrating single line comment:

2. Multiline Comments
Unlike languages such as C++ and Java, Python doesn't have a dedicated method to write
multi-line comments.

However, we can achieve the same effect by using the hash (#) symbol at the beginning of
each line.

We can also use multiline strings as comments like:

3. String Literals
Python ignores the string literals that are not assigned to a variable so we can use these string
literals as Python Comments.
4. Docstring Comments
● Python docstring is the string literals with triple quotes that are appeared right after
the function.
● It is used to associate documentation that has been written with Python modules,
functions, classes, and methods.
● It is added right below the functions, modules, or classes to describe what they do. In
Python, the docstring is then made available via the __doc__ attribute.
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:

Quotes Inside Quotes


You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:

Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Slicing Strings
You can return a range of characters by using the slice syntax.
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from
start to end.
Specify the start index and the end index, separated by a colon, to return a part of the string.

Get the characters from position 2 to position 5 (not included):

Slice From the Start:


By leaving out the start index, the range will start at the first character:

Slice To the End:


By leaving out the end index, the range will go to the end:

Negative Indexing
Use negative indexes to start the slice from the end of the string:

String Concatenation:
To concatenate, or combine, two strings you can use the + operator.
Modify Strings Using STRING METHODS:
Python has a set of built-in methods that you can use on strings.

Python has a set of built-in functions.

Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii characters
with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified
object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute
(property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each
item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by
default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ property of an object
zip() Returns an iterator, from two or more iterators

String Format
we can combine strings and numbers by using f-strings or the format() method!

Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
Object Oriented Programming(OOPs):
In Python object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in
programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc.
in the programming. The main concept of object-oriented Programming (OOPs) or oops concepts in Python
is to bind the data and the functions that work together as a single unit so that no other part of the code can
access this data.
Why OOP’s
In the real world, we deal with and process objects, such as student, employee, invoice, car,
etc. Objects are not only data and not only functions, but combination of both. Each real-world
object has attributes and behavior associated with it.

OOPs Concepts in Python


● Class in Python
● Objects in Python
● Polymorphism in Python
● Encapsulation in Python
● Inheritance in Python
● Data Abstraction in Python
● Class in Python
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.
● Classes are created by keyword class.
● Attributes are the variables that belong to a class.
● Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute

● Objects in Python
In object oriented programming Python, The object is an entity that has a state and behavior
associated with it. It may be any real-world object like a mouse, keyboard, chair, table, pen,
etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects.
More specifically, any single integer or any single string is an object.
An object consists of:
● State: It is represented by the attributes of an object. It also reflects the properties of
an object.
● Behavior: It is represented by the methods of an object. It also reflects the response of
an object to other objects.
● Identity: It gives a unique name to an object and enables one object to interact with
other objects.
The Python self
● Class methods must have an extra first parameter in the method definition. We do not
give a value for this parameter when we call the method, Python provides it
● If we have a method that takes no arguments, then we still have to have one argument.
● This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self
is about.
The Python __init__ Method
The __init__ method is similar to constructors in C++ and Java. It is run as soon
as an object of a class is instantiated. The method is useful to do any
initialization you want to do with your object. Now let us define a class and
create some objects using the self and __init__ method.

● Polymorphism in Python
In object oriented Programming Python, Polymorphism simply means having many forms.

● Encapsulation in Python
In Python object oriented programming, Encapsulation is one of the fundamental concepts in
object-oriented programming (OOP). It describes the idea of wrapping data and the methods
that work on data within one unit. This puts restrictions on accessing variables and methods
directly and can prevent the accidental modification of data. To prevent accidental change, an
object’s variable can only be changed by an object’s method. Those types of variables are
known as private variables. It is used to restrict access to methods and variables. In
encapsulation, code and data are wrapped together w

A class is an example of encapsulation as it encapsulates all the data that is member


functions, variables, etc.

● Inheritance in Python
In Python object oriented Programming, Inheritance is the capability of one class to derive or
inherit the properties from another class. The class that derives properties is called the
derived class or child class and the class from which the properties are being derived is called
the base class or parent class. The benefits of inheritance are:

It represents real-world relationships well.


It provides the reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all the
subclasses of B would automatically inherit from class A.
Types of Inheritance
1) Single Inheritance: Single-level inheritance enables a derived class to inherit
characteristics from a single-parent class.
2) Multilevel Inheritance: Multi-level inheritance enables a derived class to inherit
properties from an immediate parent class which in turn inherits properties from his
parent class.
3) Hierarchical Inheritance: Hierarchical-level inheritance enables more than one derived
class to inherit properties from a parent class.
4) Multiple Inheritance: Multiple-level inheritance enables one derived class to inherit
properties from more than one base class.
● Data Abstraction in Python
It hides unnecessary code details from the user. Also, when we do not want to give out
sensitive parts of our code implementation and this is where data abstraction came.

Data Abstraction in Python can be achieved by creating abstract classes.

Conditional Statements:
Conditional Statements are statements in Python that provide a choice for the control flow based on a
condition. It means that the control flow of the Python program will be decided based on the
outcome of the condition. Now let us see how Conditional Statements are implemented in Python.

1. If Conditional Statement in Python


If the simple code of block is to be performed if the condition holds then the if statement is
used. Here the condition mentioned holds then the code of the block runs otherwise not.
2. If else Conditional Statements in Python
In a conditional if Statement the additional block of code is merged as an else statement
which is performed when if condition is false.

3. Nested if..else Conditional Statements in Python


Nested if..else means an if-else statement inside another if statement. Or in simple words
first, there is an outer if statement, and inside it another if – else statement is present and such
type of statement is known as nested if statement. We can use one if or else if statement
inside another if or else if statements.

4. If-elif-else Conditional Statements in Python


The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final “else” statement will be
executed.

5. Ternary Expression Conditional Statements in Python


The Python ternary Expression determines if a condition is true or false and then returns the
appropriate value in accordance with the result. The ternary Expression is useful in cases
where we need to assign a value to a variable based on a simple condition, and we want to
keep our code more concise — all in just one line of code.

Python range() function:


The Python range() function returns a sequence of numbers, in a given range. The most common use of it is
to iterate sequences on a sequence of numbers using Python loops.
● range (stop) takes one argument.
● range (start, stop) takes two arguments.

● range (start, stop, step) takes three arguments.

range() in for Loop


The range() function is commonly used in for loop to iterate the loop a certain number of times. For
example,
Loops In Python:
A loop is an instruction that repeats multiple times as long as some condition is met.
Indentation is significant in Python. It is used to define a block of code; without indentation, the program
will show an error.

For Loop:
For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python,
there is “for in” loop which is similar to foreach loop in other languages. Let us learn how to use for loops in
Python for sequential traversals with examples.
While Loop:
In Python, a while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
Using else Statement with for Loop in Python
We can also combine else statement with for loop like in while loop. But as there is no
condition in for loop based on which the execution will terminate so the else block will be
executed immediately after for block finishes execution.

In this code, the ‘for' loop iterates over a list and prints each element, just like in the previous
example. However, after the loop is finished, the “else” block is executed. So, in this case, it
will print “Inside Else Block” once the loop completes.

Nested Loops:
Python programming language allows to use one loop inside another loop which is called nested loop.
Following section shows few examples to illustrate the concept.
Loop Control Statements:

Loop control statements change execution from their normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed. Python supports the following control
statements.

Continue Statement
The continue statement in Python returns the control to the beginning of the loop.
BreakContinue Statement
The break statement terminates the loop immediately when it's encountered.
Pass Statement:
In Python programming, the pass statement is a null statement which can be used as a placeholder for future
code.

Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future.
In such cases, we can use the pass statement.

You might also like