python
python
compared to languages like Java and C++. conditional statements, loops, built-in data structures, Object-
Oriented Programming, Generators, Exception Handling, Python RegEx,
In the late 1980s, Guido van Rossum dreamed of developing Python. The first version of Python 0.9.0
was released in 1991. Since its release, Python started gaining popularity. According to reports, Python is
now the most popular programming language among developers because of its high demands in the tech
realm..
What is Python
Python Code:
print("Hello World!")
For example –
def func():
statement 1
statement 2
…………………
…………………
statement N
In the above example, the statements that are the same level to the right belong to the function.
Generally, we can use four whitespaces to define indentation.
Instead of Semicolon as used in other languages, Python ends its statements with a NewLine
character.
Python is a case-sensitive language, which means that uppercase and lowercase letters are treated
differently. For example, 'name' and 'Name' are two different variables in Python.
In Python, comments can be added using the '#' symbol. Any text written after the '#' symbol is
considered a comment and is ignored by the interpreter. This trick is useful for adding notes to
the code or temporarily disabling a code block. It also helps in understanding the code better by
some other developers.
'If', 'otherwise', 'for', 'while', 'try', 'except', and 'finally' are a few reserved keywords in Python
that cannot be used as variable names. These terms are used in the language for particular
reasons and have fixed meanings. If you use these keywords, your code may include errors, or
the interpreter may reject them as potential new Variables.
Python print() function is used to display output to the console or terminal. It allows us to display
text, variables and other data in a human readable format.
Syntax:
It takes one or more arguments separated by comma(,) and adds a 'newline' at the end by default.
Parameters:
object(s) - As many as you want data to display, will first converted into string and
printed to the console.
sep - Separates the objects by a separator passed, default value = " ".
end - Ends a line with a newline character
file - a file object with write method, default value = sys.stdout
Example:
# Displaying a string
print("Hello, World!")
Output:
Hello, World!
Name: Aman Age: 21
X = 5 y = 7 Sum = 12
Score: 85.75%
In this example, the print statement is used to print string, integer, and float values in a human
readable format.
Conditional Statements
Conditional statements help us to execute a particular block for a particular condition. In this
tutorial, we will learn how to use conditional expression to execute a different block of
statements. Python provides if and else keywords to set up logical conditions. The elif keyword
is also used as a conditional statement.
x = 10
y=5
if x > y:
print("x is greater than y")
else:
print("y is greater than or equal to x")
Output:
x is greater than y
In the above code, we have two variables, x, and y, with 10 and 5, respectively. Then we used an
if..else statement to check if x is greater than y or vice versa. If the first condition is true, the
statement "x is greater than y" is printed. If the first condition is false, the statement "y is greater
than or equal to x" is printed instead.
The if keyword checks the condition is true and executes the code block inside it. The code
inside the else block is executed if the condition is false. This way, the if..else statement helps us
to execute different blocks of code based on a condition.
Python Loops
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several times. For this purpose, the programming languages provide various
loops capable of repeating some specific code several times. Consider the following tutorial to
understand the statements in detail.
For Loop
Output:
While Loop
i=1
while i<5:
print(i, end=" ")
i += 1
Output:
1 2 3 4
In the above example code, we have demonstrated using two types of loops in Python - For loop
and While loop.
The For loop is used to iterate over a sequence of items, such as a list, tuple, or string. In the
example, we defined a list of fruits and used a for loop to print each fruit, but it can also be used
to print a range of numbers.
The While loop repeats a code block if the specified condition is true. In the example, we have
initialized a variable i to 1 and used a while loop to print the value of i until it becomes greater
than or equal to 6. The i += 1 statement is used to increment the value of i in each iteration.
Python offers four built-in data structures: lists, tuples, sets, and dictionaries that allow us to
store data in an efficient way. Below are the commonly used data structures in Python, along
with example code:
1. Lists
Lists are ordered collections of data elements of different data types.
Lists are mutable meaning a list can be modified anytime.
Elements can be accessed using indices.
They are defined using square bracket '[]'.
Example:
# Create a list
fruits = ['apple', 'banana', 'cherry']
print("fuirts[1] =", fruits[1])
# Modify list
fruits.append('orange')
print("fruits =", fruits)
num_list = [1, 2, 3, 4, 5]
# Calculate sum
sum_nums = sum(num_list)
print("sum_nums =", sum_nums)
Output:
fuirts[1] = banana
fruits = ['apple', 'banana', 'cherry', 'orange']
sum_nums = 15
2. Tuples
Tuples are also ordered collections of data elements of different data types, similar to
Lists.
Elements can be accessed using indices.
Tuples are immutable meaning Tuples can't be modified once created.
They are defined using open bracket '()'.
Example:
# Create a tuple
point = (3, 4)
x, y = point
print("(x, y) =", x, y)
Output:
(x, y) = 3 4
Tuple = ('apple', 'banana', 'cherry', 'orange')
3. Sets
Sets are unordered collections of immutable data elements of different data types.
Sets are mutable.
Elements can't be accessed using indices.
Sets do not contain duplicate elements.
They are defined using curly braces '{}'
Example:
# Create a set
set1 = {1, 2, 2, 1, 3, 4}
print("set1 =", set1)
Output:
set1 = {1, 2, 3, 4}
set2 = {'apple', 'cherry', 'orange', 'banana'}
4. Dictionaries
Dictionary are key-value pairs that allow you to associate values with unique keys.
They are defined using curly braces '{}' with key-value pairs separated by colons ':'.
Dictionaries are mutable.
Elements can be accessed using keys.
Example:
# Create a dictionary
person = {'name': 'Umesh', 'age': 25, 'city': 'Noida'}
print("person =", person)
print(person['name'])
# Modify Dictionary
person['age'] = 27
print("person =", person)
Output:
This section of the Python tutorial defines some important tools related to functional
programming, such as lambda and recursive functions. These functions are very efficient in
accomplishing complex tasks. We define a few important functions, such as reduce, map, and
filter. Python provides the functools module that includes various functional programming tools.
Visit the following tutorial to learn more about functional programming.
Recent versions of Python have introduced features that make functional programming more
concise and expressive. For example, the "walrus operator":= allows for inline variable
assignment in expressions, which can be useful when working with nested function calls or list
comprehensions.
Python Function
1. Lambda Function - A lambda function is a small, anonymous function that can take any number
of arguments but can only have one expression. Lambda functions are often used in functional
programming to create functions "on the fly" without defining a named function.
2. Recursive Function - A recursive function is a function that calls itself to solve a problem.
Recursive functions are often used in functional programming to perform complex computations
or to traverse complex data structures.
3. Map Function - The map() function applies a given function to each item of an iterable and
returns a new iterable with the results. The input iterable can be a list, tuple, or other.
4. Filter Function - The filter() function returns an iterator from an iterable for which the function
passed as the first argument returns True. It filters out the items from an iterable that do not
meet the given condition.
5. Reduce Function - The reduce() function applies a function of two arguments cumulatively to
the items of an iterable from left to right to reduce it to a single value.
6. functools Module - The functools module in Python provides higher-order functions that
operate on other functions, such as partial() and reduce().
7. Currying Function - A currying function is a function that takes multiple arguments and returns a
sequence of functions that each take a single argument.
8. Memoization Function - Memoization is a technique used in functional programming to cache
the results of expensive function calls and return the cached Result when the same inputs occur
again.
9. Threading Function - Threading is a technique used in functional programming to run multiple
tasks simultaneously to make the code more efficient and faster.
Python Modules
Python modules are the program files that contain Python code or functions. Python has two
types of modules - User-defined modules and built-in modules. A module the user defines, or our
Python code saved with .py extension, is treated as a user-define module.
Built-in modules are predefined modules of Python. To use the functionality of the modules, we
need to import them into our current working program.
Python modules are essential to the language's ecosystem since they offer reusable code and
functionality that can be imported into any Python program. Here are a few examples of several
Python modules, along with a brief description of each:
Math: Gives users access to mathematical constants and pi and trigonometric functions.
Datetime: Provides classes for a simpler way of manipulating dates, times, and periods.
OS: Enables interaction with the base operating system, including administration of processes
and file system activities.
Random: The random function offers tools for generating random integers and picking random
items from a list.
JSON: JSON is a data structure that can be encoded and decoded and is frequently used in
online APIs and data exchange. This module allows dealing with JSON.
Re: Supports regular expressions, a potent text-search and text-manipulation tool.
Collections: Provides alternative data structures such as sorted dictionaries, default dictionaries,
and named tuples.
NumPy: NumPy is a core toolkit for scientific computing that supports numerical operations on
arrays and matrices.
Pandas: It provides high-level data structures and operations for dealing with time series and
other structured data types.
Requests: Offers a simple user interface for web APIs and performs HTTP requests.
Files are used to store data in a computer disk. In this tutorial, we explain the built-in file object
of Python. We can open a file using Python script and perform various operations such as
writing, reading, and appending. There are various ways of opening a file. We are explained with
the relevant example. We will also learn to perform read/write operations on binary files.
Python's file input/output (I/O) system offers programs to communicate with files stored on a
disc. Python's built-in methods for the file object let us carry out actions like reading, writing,
and adding data to files.
The open() method in Python makes a file object when working with files. The name of the file
to be opened and the mode in which the file is to be opened are the two parameters required by
this function. The mode can be used according to work that needs to be done with the file, such
as "r" for reading, "w" for writing, or "a" for attaching.
After successfully creating an object, different methods can be used according to our work. If we
want to write in the file, we can use the write() functions, and if you want to read and write both,
then we can use the append() function and, in cases where we only want to read the content of
the file we can use read() function. Binary files containing data in a binary rather than a text
format may also be worked with using Python. Binary files are written in a manner that humans
cannot directly understand. The rb and wb modes can read and write binary data in binary files.
Python Exceptions
Whenever an exception occurs, the program stops the execution, and thus the other code is not
executed. Therefore, an exception is the run-time errors that are unable to handle to Python
script. An exception is a Python object that represents an error.
Python Exceptions are an important aspect of error handling in Python programming. When a
program encounters an unexpected situation or error, it may raise an exception, which can
interrupt the normal flow of the program.
In Python, exceptions are represented as objects containing information about the error,
including its type and message. The most common type of Exception in Python is the Exception
class, a base class for all other built-in exceptions.
To handle exceptions in Python, we use the try and except statements. The try statement is used
to enclose the code that may raise an exception, while the except statement is used to define a
block of code that should be executed when an exception occurs.
try:
x = int ( input ("Enter a number: "))
y = 10 / x
print ("Result:", y)
except ZeroDivisionError:
print ("Error: Division by zero")
except ValueError:
print ("Error: Invalid input")
Output:
Enter a number: 0
Error: Division by zero
In this code, we use the try statement to attempt to perform a division operation. If either of these
operations raises an exception, the matching except block is executed.
Python also provides many built-in exceptions that can be raised in similar situations. Some
common built-in exceptions include IndexError, TypeError, and NameError. Also, we can
define our custom exceptions by creating a new class that inherits from the Exception class.
The Python magic method is the special method that adds "magic" to a class. It starts and ends
with double underscores, for example, _init_ or _str_.
The built-in classes define many magic methods. The dir() function can be used to see the
number of magic methods inherited by a class. It has two prefixes and suffix underscores in the
method name.
Python magic methods are also known as dunder methods, short for "double underscore"
methods because their names start and end with a double underscore.
Magic methods are automatically invoked by the Python interpreter in certain situations, such
as when an object is created, compared to another object, or printed.
Magic methods can be used to customize the behavior of classes, such as defining how objects
are compared, converted to strings, or accessed as containers.
Some commonly used magic methods include init for initializing an object, str for converting an
object to a string, eq for comparing two objects for equality, and getitem and setitem for
accessing items in a container object.
For example, the str magic method can define how an object should be represented as a string.
Here's an example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
Output:
Vikas (22)
In this example, the str method is defined to return a formatted string representation of the
Person object with the person's name and age.
Another commonly used magic method is eq, which defines how objects should be compared for
equality. Here's an example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
point1 = Point(2, 3)
point2 = Point(3, 4)
point3 = Point(2, 3)
print(point1 == point2)
print(point1 == point3)
Output:
False
True
In this example, the eq method is defined to return True if two Point objects have the same x and
y coordinates and False otherwise.
Everything in Python is treated as an object, including integer values, floats, functions, classes,
and none. Apart from that, Python supports all oriented concepts. Below is a brief introduction to
the Oops concepts of Python.
Classes and Objects - Python classes are the blueprints of the Object. An object is a collection of
data and methods that act on the data.
Inheritance - An inheritance is a technique where one class inherits the properties of other
classes.
Constructor - Python provides a special method __init__() which is known as a constructor. This
method is automatically called when an object is instantiated.
Data Member - A variable that holds data associated with a class and its objects.
Polymorphism - Polymorphism is a concept where an object can take many forms. In Python,
polymorphism can be achieved through method overloading and method overriding.
Method Overloading - In Python, method overloading is achieved through default arguments,
where a method can be defined with multiple parameters. The default values are used if some
parameters are not passed while calling the method.
Method Overriding - Method overriding is a concept where a subclass implements a method
already defined in its superclass.
Encapsulation - Encapsulation is wrapping data and methods into a single unit. In Python,
encapsulation is achieved through access modifiers, such as public, private, and protected.
However, Python does not strictly enforce access modifiers, and the naming convention
indicates the access level.
Data Abstraction: A technique to hide the complexity of data and show only essential features
to the user. It provides an interface to interact with the data. Data abstraction reduces
complexity and makes code more modular, allowing developers to focus on the program's
essential features.
Python Oops Concepts - In Python, the object-oriented paradigm is to design the program using
classes and objects. The object is related to real-word entities such as book, house, pencil, etc.
and the class defines its properties and behaviours.
Python Objects and classes - In Python, objects are instances of classes and classes are
blueprints that defines structure and behaviour of data.
Python Constructor - A constructor is a special method in a class that is used to initialize the
object's attributes when the object is created.
Python Inheritance - Inheritance is a mechanism in which new class (subclass or child class)
inherits the properties and behaviours of an existing class (super class or parent class).
Python Polymorphism - Polymorphism allows objects of different classes to be treated as objects
of a common superclass, enabling different classes to be used interchangeably through a
common interface.
Python includes many advances and useful concepts that help the programmer solve complex
tasks. These concepts are given below.
Python Iterator
An iterator is simply an object that can be iterated upon. It returns one Object at a time. It can be
implemented using the two special methods, __iter__() and __next__().
Iterators in Python are objects that allow iteration over a collection of data. They process each
collection element individually without loading the entire collection into memory.
For example, let's create an iterator that returns the squares of numbers up to a given limit:
def __iter__(self):
return self
def __next__(self):
if self.n <= self.limit:
square = self.n ** 2
self.n += 1
return square
else:
raise StopIteration
numbers = Squares(5)
for n in numbers:
print(n)
Output:
0
1
4
9
16
25
In this example, we have created a class Squares that acts as an iterator by implementing the
__iter__() and __next__() methods. The __iter__() method returns the Object itself, and the
__next__() method returns the next square of the number until the limit is reached.
To learn more about the iterators, visit our Python Iterators tutorial.
Python Generators
Python generators produce a sequence of values using a yield statement rather than a return
since they are functions that return iterators. Generators terminate the function's execution while
keeping the local state. It picks up right where it left off when it is restarted. Because we don't
have to implement the iterator protocol thanks to this feature, writing iterators is made simpler.
Here is an illustration of a straightforward generator function that produces squares of numbers:
# Generator Function
def square_numbers(n):
for i in range(n):
yield i**2
Output:
0
1
4
9
16
Python Modifiers
Python Decorators are functions used to modify the behaviour of another function. They allow
adding functionality to an existing function without modifying its code directly. Decorators are
defined using the @ symbol followed by the name of the decorator function. They can be used
for logging, timing, caching, etc.
Here's an example of a decorator function that adds timing functionality to another function:
import time
from math import factorial
@time_it
def my_function(n):
time.sleep(2)
print(f"Factorial of {n} = {factorial(n)}")
my_function(25)
Output:
In the above example, the time_it decorator function takes another function as an argument and
returns a wrapper function. The wrapper function calculates the time to execute the original
function and prints it to the console. The @time_it decorator is used to apply the time_it function
to the my_function function. When my_function is called, the decorator is executed, and the
timing functionality is added.
First Python Program
In this Section, we will discuss the basic syntax of Python, we will run a simple program to print
Hello World on the console.
Python provides us the feature to execute the Python statement one by one at the interactive
prompt. It is preferable in the case where we are concerned about the output of each line of our
Python program.
o open the interactive mode, open the terminal (or command prompt) and type python (python3
in case if you have Python2 and Python3 both installed on your system).
It will open the following prompt where we can execute the Python statement and check their
impact on the console.
The interpreter prompt is best to run the single-line statements of the code. However, we cannot
write the code every-time on the terminal. It is not suitable to write multiple lines of code.
Using the script mode, we can write multiple lines code into a file which can be executed later.
For this purpose, we need to open an editor like notepad, create a file named and save it with .py
extension, which stands for "Python". Now, we will implement the above example using the
script mode.
1. print ("hello world"); #here, we have used print() function to print the message on the console.
To run this file named as first.py, we need to run the following command on the terminal.
Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will open a
new blank script in which we can write our code.
Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will display
the output to the shell.
The output will be shown as follows.
Step - 4: Apart from that, we can also run the file using the operating system terminal. But, we
should be aware of the path of the directory where we have saved our file.
Multi-line Statements
Multi-line statements are written into the notepad like an editor and saved it with .py extension.
In the following example, we have defined the execution of the multiple code lines using the
Python script.
Code:
Script File:
The script mode has few advantages and disadvantages as well. Let's understand the following
advantages of running code in script mode.
We have to save the code every time if we make any change in the code.
It can be tedious when we run a single or a few lines of code.
Python Variables
A variable is the name given to a memory location. A value-holding Python variable is also
known as an identifier.
Since Python is an infer language that is smart enough to determine the type of a variable, we do
not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both letters
and digits.
The name of the variable should be written in lowercase. Both Rahul and rahul are distinct
variables.
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
What are Python Functions?
Syntax
We will define a function that returns the argument number's square when called.
Output:
The square of the given number is: 36
In the Python programming language, all parameters are passed by reference. It shows that if we
modify the worth of contention within a capability, the calling capability will similarly mirror the
change. For instance,
Code
Output:
The names in the class, which have leading underscore (_) are for indicating to the other users
that the attribute or function is intended to be private in the program.
The users are recommended that they should use single underscore (_) for semiprivate and
double underscore (__) for fully private variables.
In the following example, we will show the difference between Single Underscore (_) and
Double Underscore (__) prefixes.
Example:
1. class UserClass():
2. def __init__(self):
3. self.__fully_private = "JavaTpoint"
4. self.__fully_private = "to"
5. self._semi_private = "Hello"
6. self._semi_private = "Say"
7. mc = UserClass()
8. print(mc._semi_private)
9. print(mc.__fully_private)
Output:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-4f3b78146b9f> in <module>
7 mc = UserClass()
8 print(mc._semi_private)
----> 9 print(mc.__fully_private)
in the above code, the user tried to access the fully private variables and in output, they will get
the error saying that the UserClass does not have any attribute called '__fully_private'.
Conclusion
the use of single underscore (_) and double underscore (__) in python with different example.
# Input Graph
graph = {
'A' : ['B','C'],
'B' : ['A','C','D'],
'C' : ['A','B','E'],
'D' : ['B','E'],
'E' : ['C','D']
}
# To store visited nodes.
visitedNodes = []
# To store nodes in queue
queueNodes = []
# function
def bfs(visitedNodes, graph, snode):
visitedNodes.append(snode)
queueNodes.append(snode)
print()
print("RESULT :")
while queueNodes:
s = queueNodes.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visitedNodes:
visitedNodes.append(neighbour)
queueNodes.append(neighbour)
# Main Code
snode = input("Enter Starting Node(A, B, C, D, or E) :").upper()
# calling bfs function
bfs(visitedNodes, graph, snode)