Python is a widely used programming language that offers several unique features and advantages compared to languages like Java and C++. Our Python tutorial thoroughly explains Python basics and advanced concepts, starting with installation, conditional statements, loops, built-in data structures, Object-Oriented Programming, Generators, Exception Handling, Python RegEx, and many other concepts. This tutorial is designed for beginners and working professionals.
What is Python
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.
Features of Python:
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.
Garbage Collected – Memory allocation and de-allocation are automatically managed. Programmers do not specifically need to manage the memory.
Purely Object-Oriented – It refers to everything as an object, including numbers and strings.
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 sectors and disciplines as a result.
Python has many web-based assets, open-source projects, and a vibrant community. Learning the language, working together on projects, and contributing to the Python ecosystem are all made very easy for developers.
Pause
Next
Mute
Current Time
3:55
/
Duration
18:10
Fullscreen
Because of its straightforward language framework, Python is easier to understand and write code in. This makes it a fantastic programming language for novices. Additionally, it assists seasoned programmers in writing clear and error-free code.
Python has many third-party libraries that can be used to make its functionality easier. These libraries cover many domains, for example, web development, scientific computing, data analysis, and more.
Java vs. Python
Python is an excellent choice for rapid development and scripting tasks. Whereas Java emphasizes a strong type system and object-oriented programming.
Here are some basic programs that illustrates key differences between them.
Printing ‘Hello World’
Python Code:
print(“Hello World!”)
Test it Now
Output:
Hello, World!
In Python, it is one line of code. It requires simple syntax to print ‘Hello World’
Java Code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World!”);
}
}
Output:
Hello, World!
In Java, we need to declare classes, method structures many other things.
While both programs give the same output, we can notice the syntax difference in the print statement.
In Python, it is easy to learn and write code. While in Java, it requires more code to perform certain tasks.
Python is dynamically typed, meaning we do not need to declare the variable Whereas Java is statistically typed, meaning we need to declare the variable type.
Python is suitable for various domains such as Data Science, Machine Learning, Web development, and more. Whereas Java is suitable for web development, mobile app development (Android), and more.
Python Basic Syntax
There is no use of curly braces or semicolons in Python programming language. It is an English-like language. But Python uses indentation to define a block of code. Indentation is nothing but adding whitespace before the statement when it is needed.
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.
History of Python
Python was created by Guido van Rossum. In the late 1980s, Guido van Rossum, a Dutch programmer, began working on Python while at the Centrum Wiskunde & Informatica (CWI) in the Netherlands. He wanted to create a successor to the ABC programming language that would be easy to read and efficient.
In February 1991, the first public version of Python, version 0.9.0, was released. This marked the official birth of Python as an open-source project. The language was named after the British comedy series “Monty Python’s Flying Circus”.
Python development has gone through several stages. In January 1994, Python 1.0 was released as a usable and stable programming language. This version included many of the features that are still present in Python today.
From the 1990s to the 2000s, Python gained popularity for its simplicity, readability, and versatility. In October 2000, Python 2.0 was released. Python 2.0 introduced list comprehensions, garbage collection, and support for Unicode.
In December 2008, Python 3.0 was released. Python 3.0 introduced several backward-incompatible changes to improve code readability and maintainability.
Throughout 2010s, Python’s popularity increased, particularly in fields like data science, machine learning, and web development. Its rich ecosystem of libraries and frameworks made it a favourite among developers.
The Python Software Foundation (PSF) was established in 2001 to promote, protect, and advance the Python programming language and its community.
Why learn Python?
Python provides many useful features to the programmer. These features make it the most popular and widely used language. We have listed below few-essential features of Python.
Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
Expressive Language: It allows programmers to express complex concepts in just a few lines of code or reduces Developer’s Time.
Interpreted Language: Python does not require compilation, allowing rapid development and testing. It uses Interpreter instead of Compiler.
Object-Oriented Language: It supports object-oriented programming, making writing reusable and modular code easy.
Open-Source Language: Python is open-source and free to use, distribute and modify.
Extensible: Python can be extended with modules written in C, C++, or other languages.
Learn Standard Library: Python’s standard library contains many modules and functions that can be used for various tasks, such as string manipulation, web programming, and more.
GUI Programming Support: Python provides several GUI frameworks, such as Tkinter and PyQt, allowing developers to create desktop applications easily.
Integrated: Python can easily integrate with other languages and technologies, such as C/C++, Java, and . NET.
Embeddable: Python code can be embedded into other applications as a scripting language.
Dynamic Memory Allocation: Python automatically manages memory allocation, making it easier for developers to write complex programs without worrying about memory management.
Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide range of problems.
Versatility: Python is a universal language in various domains such as web development, machine learning, data analysis, scientific computing, and more.
Large Community: Python has a vast and active community of developers contributing to its development and offering support. This makes it easy for beginners to get help and learn from experienced developers.
Career Opportunities: Python is a highly popular language in the job market. Learning Python can open up several career opportunities in data science, artificial intelligence, web development, and more.
High Demand: With the growing demand for automation and digital transformation, the need for Python developers is rising. Many industries seek skilled Python developers to help build their digital infrastructure.
Increased Productivity: Python has a simple syntax and powerful libraries that can help developers write code faster and more efficiently. This can increase productivity and save time for developers and organizations.
Big Data and Machine Learning: Python has become the go-to language for big data and machine learning. Python has become popular among data scientists and machine learning engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.
Where is Python used?
Python is a general-purpose, popular programming language, and it is used in almost every technical field. The various areas of Python use are given below.
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.
3D CAD Applications: Python can be used for 3D computer-aided design (CAD) applications through libraries such as Blender.
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 operations, web scraping, and data processing.
Python Popular Frameworks and Libraries
Python has wide range of libraries and frameworks widely used in various fields such as machine learning, artificial intelligence, web applications, etc. We define some popular frameworks and libraries of Python as follows.
Web development (Server-side) – Django Flask, Pyramid, CherryPy
GUIs based applications – Tkinter, PyGTK, PyQt, PyJs, etc.
Machine Learning – TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
Mathematics – NumPy, Pandas, etc.
BeautifulSoup: a library for web scraping and parsing HTML and XML
Requests: a library for making HTTP requests
SQLAlchemy: a library for working with SQL databases
Kivy: a framework for building multi-touch applications
Pygame: a library for game development
Pytest: a testing framework for Python Django
REST framework: a toolkit for building RESTful APIs
FastAPI: a modern, fast web framework for building APIs
Streamlit: a library for building interactive web apps for machine learning and data science
NLTK: a library for natural language processing
Python print() Function
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:
print(object(s), sep=separator, end=end, file=file, flush=flush)
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!”)
Displaying multiple values
name = “Aman”
age = 21
print(“Name:”, name, “Age:”, age)
Printing variables and literals
x = 5
y = 7
print(“x =”, x, “y =”, y, “Sum =”, x + y)
Printing with formatting
percentage = 85.75
print(“Score: {:.2f}%”.format(percentage))
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.
The print statement can be used for debugging, logging and to provide information to the user.
Python 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.
Example code for if..else 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.
We will learn about this in more detail in the further article for the Python tutorial.
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.
Python For Loop
fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
print(x, end=” “)
Test it Now
Output:
apple banana cherry
Python 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.
We will learn about them in the tutorial in detail.
Python Data Structures
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:
- 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
- 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)
Create another tuple
tuple_ = (‘apple’, ‘banana’, ‘cherry’, ‘orange’)
print(“Tuple =”, tuple_)
Output:
(x, y) = 3 4
Tuple = (‘apple’, ‘banana’, ‘cherry’, ‘orange’)
- 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)
Create another set
set2 = {‘apple’, ‘banana’, ‘cherry’, ‘apple’, ‘orange’}
print(“set2 =”, set2)
Output:
set1 = {1, 2, 3, 4}
set2 = {‘apple’, ‘cherry’, ‘orange’, ‘banana’}
- 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:
person = {‘name’: ‘Umesh’, ‘age’: 25, ‘city’: ‘Noida’}
Umesh
person = {‘name’: ‘Umesh’, ‘age’: 27, ‘city’: ‘Noida’}
These are just a few examples of Python’s built-in data structures. Each data structure has its own characteristics and use cases.
Python Functional Programming
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
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.
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.
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.
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.
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.
functools Module – The functools module in Python provides higher-order functions that operate on other functions, such as partial() and reduce().
Currying Function – A currying function is a function that takes multiple arguments and returns a sequence of functions that each take a single argument.
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.
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.
Python File I/O
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
An exception can be defined as an unusual condition in a program resulting in an interruption in the flow of the program.
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.
For example, consider the following code:
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.
Python CSV
A CSV stands for “comma separated values”, which is defined as a simple file format that uses specific structuring to arrange tabular data. It stores tabular data such as spreadsheets or databases in plain text and has a common format for data interchange. A CSV file opens into the Excel sheet, and the rows and columns data define the standard format.
We can use the CSV.reader function to read a CSV file. This function returns a reader object that we can use to repeat over the rows in the CSV file. Each row is returned as a list of values, where each value corresponds to a column in the CSV file.
For example, consider the following code:
import csv
with open(‘data.csv’, ‘r’) as file:
reader = csv.reader(file)
for row in reader:
print(row)
Here, we open the file data.csv in read mode and create a csv.reader object using the csv.reader() function. We then iterate over the rows in the CSV file using a for loop and print each row to the console.
We can use the CSV.writer() function to write data to a CSV file. It returns a writer object we can use to write rows to the CSV file. We can write rows by calling the writer () method on the writer object.
For example, consider the following code:
import csv
data = [ [‘Name’, ‘Age’, ‘Country’],
[‘Alice’, ’25’, ‘USA’],
[‘Bob’, ’30’, ‘Canada’],
[‘Charlie’, ’35’, ‘Australia’]
]
with open(‘data.csv’, ‘w’) as file:
writer = csv.writer(file)
for row in data:
writer.writerow(row)
In this program, we create a list of lists called data, where each inner list represents a row of data. We then open the file data.csv in write mode and create a CSV.writer object using the CSV.writer function. We then iterate over the rows in data using a for loop and write each row to the CSV file using the writer method.
Python Sending Mail
We can send or read a mail using the Python script. Python’s standard library modules are useful for handling various protocols such as PoP3 and IMAP. Python provides the smtplib module for sending emails using SMTP (Simple Mail Transfer Protocol). We will learn how to send mail with the popular email service SMTP from a Python script.
Python Magic Methods
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})"
person = Person(‘Vikas’, 22)
print(person)
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
def __eq__(self, other):
return self.x == other.x and self.y == other.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.
Python Oops Concepts
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.
To read the Oops concept in detail, visit the following resources.
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 Advance Topics
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 __init__(self, limit):
self.limit = limit
self.n = 0
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
Create a generator object
generator = square_numbers(5)
Print the values generated by the generator
for num in generator:
print(num)
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
Decorator to calculate time taken by
the function
def time_it(func):
def wrapper(*args, *kwargs): start = time.time() result = func(args, **kwargs)
end = time.time()
print(f”{func.name} took {end-start:.5f} seconds to run.”)
return result
return wrapper
@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.
Python MySQL
Python MySQL is a powerful relational database management system. We must set up the environment and establish a connection to use MySQL with Python. We can create a new database and tables using SQL commands in Python.
Environment Setup: Installing and configuring MySQL Connector/Python to use Python with MySQL.
Database Connection: Establishing a connection between Python and MySQL database using MySQL Connector/Python.
Creating New Database: Creating a new database in MySQL using Python.
Creating Tables: Creating tables in the MySQL database with Python using SQL commands.
Insert Operation: Insert data into MySQL tables using Python and SQL commands.
Read Operation: Reading data from MySQL tables using Python and SQL commands.
Update Operation: Updating data in MySQL tables using Python and SQL commands.
Join Operation: Joining two or more tables in MySQL using Python and SQL commands.
Performing Transactions: Performing a group of SQL queries as a single unit of work in MySQL using Python.
Other relative points include handling errors, creating indexes, and using stored procedures and functions in MySQL with Python.
Python MongoDB
Python MongoDB is a popular NoSQL database that stores data in JSON-like documents. It is schemaless and provides high scalability and flexibility for data storage. We can use MongoDB with Python using the PyMongo library, which provides a simple and intuitive interface for interacting with MongoDB.
Here are some common tasks when working with MongoDB in Python:
Environment Setup: Install and configure MongoDB and PyMongo library on your system.
Database Connection: Connect to a MongoDB server using the MongoClient class from PyMongo.
Creating a new database: Use the MongoClient Object to create a new database.
Creating collections: Create collections within a database to store documents.
Inserting documents: Insert new documents into a collection using the insert_one() or insert_many() methods.
Querying documents: Retrieve documents from a collection using various query methods like find_one(), find(), etc.
Updating documents: Modify existing documents in a collection using update_one() or update_many() methods.
Deleting documents: Remove documents from a collection using the delete_one() or delete_many() methods.
Aggregation: Perform aggregation operations like grouping, counting, etc., using the aggregation pipeline framework.
Indexing: Improve query performance by creating indexes on fields in collections.
There are many more advanced topics in MongoDB, such as data sharding, replication, and more, but these tasks cover the basics of working with MongoDB in Python.
Python SQLite
Relational databases are built and maintained using Python SQLite, a compact, serverless, self-contained database engine. Its mobility and simplicity make it a popular option for local or small-scale applications. Python has a built-in module for connecting to SQLite databases called SQLite3, enabling developers to work with SQLite databases without difficulties.
Python CGI
Python CGI is a technology for running scripts through web servers to produce dynamic online content. It offers a communication channel and a dynamic content generation interface for external CGI scripts and the web server. Python CGI scripts may create HTML web pages, handle form input, and communicate with databases. Python CGI enables the server to carry out Python scripts and provide the results to the client, offering a quick and effective approach to creating dynamic online applications.
Python CGI scripts may be used for many things, including creating dynamic web pages, processing forms, and interacting with databases. Since Python, a potent and popular programming language, can be utilized to create scripts, it enables a more customized and flexible approach to web creation. Scalable, safe, and maintainable online applications may be created with Python CGI. Python CGI is a handy tool for web developers building dynamic and interactive online applications.
Asynchronous Programming in Python
Asynchronous programming is a paradigm for computer programming that enables independent and concurrent operation of activities. It is frequently used in applications like web servers, database software, and network programming, where several tasks or requests must be handled concurrently.
Python has asyncio, Twisted, and Tornado among its libraries and frameworks for asynchronous programming. Asyncio, one of these, offers a simple interface for asynchronous programming and is the official asynchronous programming library in Python.
Coroutines are functions that may be halted and restarted at specific locations in the code and are utilized by asyncio. This enables numerous coroutines to operate simultaneously without interfering with one another. For constructing and maintaining coroutines, the library offers several classes and methods, including asyncio.gather(), asyncio.wait(), and asyncio.create_task().
Event loops, which are in charge of planning and operating coroutines, are another feature of asyncio. By cycling between coroutines in a non-blocking way, the event loop controls the execution of coroutines and ensures that no coroutine blocks another. Additionally, it supports timers and scheduling callbacks, which may be helpful when activities must be completed at specified times or intervals.
Python Concurrency
The term “concurrency” describes a program’s capacity to carry out several tasks at once, enhancing the program’s efficiency. Python offers several modules and concurrency-related methods, including asynchronous programming, multiprocessing, and multithreading. While multiprocessing involves running many processes simultaneously on a system, multithreading involves running numerous threads concurrently inside a single process.
The threading module in Python enables programmers to build multithreading. It offers classes and operations for establishing and controlling threads. Conversely, the multiprocessing module allows developers to design and control processes. Python’s asyncio module provides asynchronous programming support, allowing developers to write non-blocking code that can handle multiple tasks concurrently. Using these techniques, developers can write highperformance, scalable programs that can handle multiple tasks concurrently.
Python’s threading module enables the concurrent execution of several threads within a single process, which is helpful for I/O-bound activities.
For CPU-intensive operations like image processing or data analysis, multiprocessing modules make it possible to execute numerous processes concurrently across multiple CPU cores.
The asyncio module supports asynchronous I/O and permits the creation of single-threaded concurrent code using coroutines for high-concurrency network applications.
With libraries like Dask, PySpark, and MPI, Python may also be used for parallel computing. These libraries allow workloads to be distributed across numerous nodes or clusters for better performance.
Web Scrapping using Python
The process of web scraping is used to retrieve data from websites automatically. Various tools and libraries extract data from HTML and other online formats. Python is among the most widely used programming languages for web scraping because of its ease of use, adaptability, and variety of libraries.
We must take a few steps to accomplish web scraping using Python. We must first decide which website to scrape and what information to gather. Then, we can submit a request to the website and receive the HTML content using Python’s requests package. Once we have the HTML text, we can extract the needed data using a variety of parsing packages, like Beautiful Soup and lxml.
We can employ several strategies, like slowing requests, employing user agents, and using proxies, to prevent overburdening the website’s server. It is also crucial to abide by the terms of service for the website and respect its robots.txt file.
Data mining, lead creation, pricing tracking, and many more uses are possible for web scraping. However, as unauthorized web scraping may be against the law and unethical, it is essential to utilize it professionally and ethically.
Natural Language Processing (NLP) using Python
A branch of artificial intelligence (AI) called “natural language processing” (NLP) studies how computers and human language interact. Thanks to NLP, computers can now understand, interpret, and produce human language. Due to its simplicity, versatility, and strong libraries like NLTK (Natural Language Toolkit) and spaCy, Python is a well-known programming language for NLP.
For NLP tasks, including tokenization, stemming, lemmatization, part-of-speech tagging, named entity identification, sentiment analysis, and others, NLTK provides a complete library. It has a variety of corpora (big, organized text collections) for developing and evaluating NLP models. Another well-liked library for NLP tasks is spaCy, which offers quick and effective processing of enormous amounts of text. It enables simple modification and expansion and comes with pre-trained models for various NLP workloads.
NLP may be used in Python for various practical purposes, including chatbots, sentiment analysis, text categorization, machine translation, and more. NLP is used, for instance, by chatbots to comprehend and reply to user inquiries in a natural language style. Sentiment analysis, which may be helpful for brand monitoring, customer feedback analysis, and other purposes, employs NLP to categorize text sentiment (positive, negative, or neutral). Text documents are categorized using natural language processing (NLP) into pre-established categories for spam detection, news categorization, and other purposes.
Python is a strong and useful tool when analyzing and processing human language. Developers may carry out various NLP activities and create useful apps that can communicate with consumers in natural language with libraries like NLTK and spaCy.
Conclusion:
In this tutorial, we’ve looked at some of Python’s most important features and ideas, including variables, data types, loops, functions, modules, and more. More complex subjects, including web scraping, natural language processing, parallelism, and database connection, have also been discussed. You will have a strong basis to continue learning about Python and its applications using the information you have learned from this lesson.
Remember that practicing and developing code is the best method to learn Python. You may find many resources at javaTpoint to support your further learning, including documentation, tutorials, online groups, and more. You can master Python and use it to create wonderful things if you work hard and persist.
Prerequisite
Before learning Python, you must have the basic knowledge of programming concepts.
Audience
Our Python tutorial is designed to help beginners and professionals.
Problem
We assure that you will not find any problem in this Python tutorial. But if there is any mistake, please post the problem in contact form.
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost every domain of software development. Python makes its presence in every emerging field.
Here, we are specifying application areas where Python can be applied.
Python Applications
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One of Python web-framework named Django is used on Instagram. Python provides many useful frameworks, and these are given below:
Django and Pyramid framework(Use for heavy applications)
Flask and Bottle (Micro-framework)
Plone and Django CMS (Advance Content management)
2) Desktop GUI Applications
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any application. Python provides a Tk GUI library to develop a user interface. Some popular GUI libraries are given below.
Tkinter or Tk
wxWidgetM
Kivy (used for writing multitouch applications )
PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are computer program which are used commands to execute. This kind of application was more popular in the old generation of computers. Python can develop this kind of application very effectively. It is famous for having REPL, which means the Read-Eval-Print Loop that makes it the most suitable language for the command-line applications.
Python provides many free library or module which helps to build the command-line apps. The necessary IO libraries are used to read and write. It helps to parse argument and create console help text out-of-the-box. There are also advance libraries that can develop independent console apps.
4) Software Development
Python is useful for the software development process. It works as a support language and can be used to build control and management, testing, etc.
SCons is used to build control.
Buildbot and Apache Gumps are used for automated continuous compilation and testing.
Round or Trac for bug tracking and project management.
5) Scientific and Numeric
This is the era of Artificial intelligence where the machine can perform the task the same as the human. Python language is the most suitable language for Artificial intelligence or machine learning. It consists of many scientific and mathematical libraries, which makes easy to solve complex calculations.
Implementing machine learning algorithms require complex mathematical calculation. Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc. If you have some basic knowledge of Python, you need to import libraries on the top of the code. Few popular frameworks of machine libraries are given below.
SciPy
Scikit-learn
NumPy
Pandas
Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example of a business application. This kind of application requires extensively, scalability and readability, and Python provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business applications. Python provides a Tryton platform which is used to develop the business application.
7) Audio or Video-based Applications
Python is flexible to perform multiple tasks and can be used to create multimedia applications. Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The few multimedia libraries are given below.
Gstreamer
Pyglet
QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used to develop the 3D representation of a part of a system. Python can create a 3D CAD application by using the following functionalities.
Fandango (Popular )
CAMVOX
HeeksCNC
AnyCAD
RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
10) Image Processing Application
Python contains many libraries that are used to work with the image. The image can be manipulated according to our requirements. Some libraries of image processing are given below.
OpenCV
Pillow
SimpleITK
In this topic, we have described all types of applications where Python plays an essential role in the development of these applications. In the next tutorial, we will learn more concepts about Python.
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.
Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in the program. The standards to name an identifier are given underneath.
The variable’s first character must be an underscore or alphabet (_).
Every one of the characters with the exception of the main person might be a letter set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
White space and special characters (!, @, #, %, etc.) are not allowed in the identifier name. ^, &, *).
Identifier name should not be like any watchword characterized in the language.
Names of identifiers are case-sensitive; for instance, my name, and MyName isn’t something very similar.
Examples of valid identifiers: a123, _n, n_9, etc.
Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
Python doesn’t tie us to pronounce a variable prior to involving it in the application. It permits us to make a variable at the necessary time.
In Python, we don’t have to explicitly declare variables. The variable is declared automatically whenever a value is added to it.
The equal (=) operator is utilized to assign worth to a variable.
Object References
When we declare a variable, it is necessary to comprehend how the Python interpreter works. Compared to a lot of other programming languages, the procedure for dealing with variables is a little different.
Python is the exceptionally object-arranged programming language; Because of this, every data item is a part of a particular class. Think about the accompanying model.
print(“John”)
Output:
John
The Python object makes a integer object and shows it to the control center. We have created a string object in the print statement above. Make use of the built-in type() function in Python to determine its type.
type(“John”)
Output:
In Python, factors are an symbolic name that is a reference or pointer to an item. The factors are utilized to indicate objects by that name.
Let’s understand the following example
a = 50
Python Variables
In the above image, the variable a refers to an integer object.
Suppose we assign the integer value 50 to a new variable b.
a = 50
b = a
Python Variables
The variable b refers to the same object that a points to because Python does not create another object.
Let’s assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100
Python Variables
Python manages memory efficiently if we assign the same variable to two different values.
Object Identity
Every object created in Python has a unique identifier. Python gives the dependable that no two items will have a similar identifier. The object identifier is identified using the built-in id() function. consider about the accompanying model.
a = 50
b = a
print(id(a))
print(id(b))
Reassigned variable a
a = 500
print(id(a))
Output:
140734982691168
140734982691168
2822056960944
We assigned the b = a, an and b both highlight a similar item. The id() function that we used to check returned the same number. We reassign a to 500; The new object identifier was then mentioned.
Variable Names
The process for declaring the valid variable has already been discussed. Variable names can be any length can have capitalized, lowercase (start to finish, a to z), the digit (0-9), and highlight character(_). Take a look at the names of valid variables in the following example.
name = “Devansh”
age = 20
marks = 80.50
print(name)
print(age)
print(marks)
Output:
Devansh
20
80.5
Consider the following valid variables name.
name = “A”
Name = “B”
naMe = “C”
NAME = “D”
n_a_m_e = “E”
name = “F” name = “G”
name = “H”
na56me = “I”
print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, name, name,_name, na56me)
Output:
A B C D E D E F G F I
We have declared a few valid variable names in the preceding example, such as name, name, and so on. However, this is not recommended because it may cause confusion when we attempt to read code. To make the code easier to read, the name of the variable ought to be descriptive.
The multi-word keywords can be created by the following method.
Camel Case – In the camel case, each word or abbreviation in the middle of begins with a capital letter. There is no intervention of whitespace. For example – nameOfStudent, valueOfVaraible, etc.
Pascal Case – It is the same as the Camel Case, but here the first word is also capital. For example – NameOfStudent, etc.
Snake Case – In the snake case, Words are separated by the underscore. For example – name_of_student, etc.
Multiple Assignment
Multiple assignments, also known as assigning values to multiple variables in a single statement, is a feature of Python.
We can apply different tasks in two ways, either by relegating a solitary worth to various factors or doling out numerous qualities to different factors. Take a look at the following example.
- Assigning single value to multiple variables
Eg:
x=y=z=50
print(x)
print(y)
print(z)
Output:
50
50
50
- Assigning multiple values to multiple variables:
Eg:
a,b,c=5,10,15
print a
print b
print c
Output:
5
10
15
The values will be assigned in the order in which variables appear.
Python Variable Types
There are two types of variables in Python – Local variable and Global variable. Let’s understand the following variables.
Local Variable
The variables that are declared within the function and have scope within the function are known as local variables. Let’s examine the following illustration.
Example –
Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c = a + b
print(“The sum is:”, c)
Calling a function
add()
Output:
The sum is: 50
Explanation:
We declared the function add() and assigned a few variables to it in the code above. These factors will be alluded to as the neighborhood factors which have scope just inside the capability. We get the error that follows if we attempt to use them outside of the function.
add()
Accessing local variable outside the function
print(a)
Output:
The sum is: 50
print(a)
NameError: name ‘a’ is not defined
We tried to use local variable outside their scope; it threw the NameError.
Global Variables
Global variables can be utilized all through the program, and its extension is in the whole program. Global variables can be used inside or outside the function.
By default, a variable declared outside of the function serves as the global variable. Python gives the worldwide catchphrase to utilize worldwide variable inside the capability. The function treats it as a local variable if we don’t use the global keyword. Let’s examine the following illustration.
Example –
Declare a variable and initialize it
x = 101
Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = ‘Welcome To Javatpoint’
print(x)
mainFunction()
print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and give out a value to it. We then created a function and used the global keyword to access the declared variable within the function. We can now alter its value. After that, we gave the variable x a new string value and then called the function and printed x, which displayed the new value.
=
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax –
del
In the following example, we create a variable x and assign value to it. We deleted variable x, and print it, we get the error “variable x is not defined”. The variable x will no longer use in future.
Example –
Assigning a value to x
x = 6
print(x)
deleting a variable.
del x
print(x)
Output:
6
Traceback (most recent call last):
File “C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py”, line 389, in
print(x)
NameError: name ‘x’ is not defined
Maximum Possible Value of an Integer in Python
Python, to the other programming languages, does not support long int or float data types. It uses the int data type to handle all integer values. The query arises here. In Python, what is the maximum value that the variable can hold? Take a look at the following example.
Example –
A Python program to display that we can store
large numbers in Python
a = 10000000000000000000000000000000000000000000
a = a + 1
print(type(a))
print (a)
Output:
10000000000000000000000000000000000000000001
As we can find in the above model, we assigned a large whole number worth to variable x and really look at its sort. It printed class not long int. As a result, the number of bits is not limited, and we are free to use all of our memory.
There is no special data type for storing larger numbers in Python.
Print Single and Numerous Factors in Python
We can print numerous factors inside the single print explanation. The examples of single and multiple printing values are provided below.
Example – 1 (Printing Single Variable)
printing single value
a = 5
print(a)
print((a))
Output:
5
5
Example – 2 (Printing Multiple Variables)
a = 5
b = 6
printing multiple variables
print(a,b)
separate the variables by the comma
Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:
5 6
1 2 3 4 5 6 7 8
Basic Fundamentals:
This section contains the fundamentals of Python, such as:
i)Tokens and their types.
Python If-else statements
Decision making is the most important aspect of almost all the programming languages. As the name implies, decision making allows us to run a particular block of code for a particular decision. Here,
In python, decision making is performed by the following statements.
Statement
Description
If Statement
The if statement is used to test a specific condition. If the condition is true, a block of code (if-block) will be executed.
If – else Statement
The if-else statement is similar to if statement except the fact that, it also provides the block of the code for the false case of the condition to be checked. If the condition provided in the if statement is false, then the else statement will be executed.
Nested if Statement
Nested if statements enable us to use if ? else statement inside an outer if statement.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn’t allow the use of parentheses for the block level code. In Python, indentation is used to declare a block. If two statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All the statements of one block are intended at the same level indentation. We will see how the actual indentation takes place in decision making and other stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a block of code known as if-block. The condition of if statement can be any valid logical expression which can be either evaluated to true or false.
Python If-else statements
The syntax of the if-statement is given below.
if expression:
statement
Example 1
Simple Python program to understand the if statement
num = int(input(“enter the number:”))
Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
Here, we are checking the condition. If the condition is true, we will enter the block
print("The Given number is an even number")
Output:
enter the number: 10
The Given number is an even number
Example 2 : Program to print the largest of the three numbers.
Simple Python Program to print the largest of the three numbers.
a = int (input(“Enter a: “));
b = int (input(“Enter b: “));
c = int (input(“Enter c: “));
if a>b and a>c:
Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given a is largest");
if b>a and b>c:
Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given b is largest");
if c>a and c>b:
Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given c is largest");
Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest
The if-else statement
The if-else statement provides an else block combined with the if statement which is executed in the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
Python If-else statements
The syntax of the if-else statement is given below.
if condition:
#block of statements
else:
#another block of statements (else-block)
Example 1 : Program to check whether a person is eligible to vote or not.
Simple Python Program to check whether a person is eligible to vote or not.
age = int (input(“Enter your age: “))
Here, we are taking an integer num and taking input dynamically
if age>=18:
Here, we are checking the condition. If the condition is true, we will enter the block
print("You are eligible to vote !!");
else:
print(“Sorry! you have to wait !!”);
Output:
Enter your age: 90
You are eligible to vote !!
Example 2: Program to check whether a number is even or not.
Simple Python Program to check whether a number is even or not.
num = int(input(“enter the number:”))
Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
Here, we are checking the condition. If the condition is true, we will enter the block
print("The Given number is an even number")
else:
print(“The Given Number is an odd number”)
Output:
enter the number: 10
The Given number is even number
The elif statement
The elif statement enables us to check multiple conditions and execute the specific block of statements depending upon the true condition among them. We can have any number of elif statements in our program depending upon our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.
The syntax of the elif statement is given below.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Python If-else statements
Example 1
Simple Python program to understand elif statement
number = int(input(“Enter the number?”))
Here, we are taking an integer number and taking input dynamically
if number==10:
Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equals to 10")
elif number==50:
Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 50");
elif number==100:
Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 100");
else:
print(“The given number is not equal to 10, 50 or 100”);
Output:
Enter the number?15
The given number is not equal to 10, 50 or 100
Example 2
Simple Python program to understand elif statement
marks = int(input(“Enter the marks? “))
Here, we are taking an integer marks and taking input dynamically
if marks > 85 and marks <= 100:
Here, we are checking the condition. If the condition is true, we will enter the block
print(“Congrats ! you scored grade A …”)
elif marks > 60 and marks <= 85:
Here, we are checking the condition. If the condition is true, we will enter the block
print(“You scored grade B + …”)
elif marks > 40 and marks <= 60:
Here, we are checking the condition. If the condition is true, we will enter the block
print(“You scored grade B …”)
elif (marks > 30 and marks <= 40):
Here, we are checking the condition. If the condition is true, we will enter the block
print(“You scored grade C …”)
else:
print(“Sorry you are fail ?”)
Output:
Enter the marks? 89
Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for running the loops. The basic functionality of all the techniques is the same, although the syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
The following sorts of loops are available in the Python programming language.
Sr.No.
Name of the loop
Loop Type & Description
1
For loop
This type of loop executes a code block multiple times and abbreviates the code that manages the loop variable.
2
While loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
3
Nested loops
We can iterate a loop inside another loop.
Loop Control Statements
Statements used to control loops and change the course of iteration are called control statements. All the objects produced within the local scope of the loop are deleted when execution is completed.
Python provides the following control statements. We will discuss them later in detail.
Let us quickly go over the definitions of these loop control statements.
Sr.No.
Name of the control statement
Description
1
Break statement
This command terminates the loop’s execution and transfers the program’s control to the statement next to the loop.
2
Continue statement
This command skips the current iteration of the loop. The statements following the continue statement are not executed once the Python interpreter reaches the continue statement.
3
Pass statement
The pass statement is used when a statement is syntactically necessary, but no code is to be executed.
The for Loop
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.
Syntax of the for Loop
for value in sequence:
{ code block }
In this case, the variable value is used to hold the value of every item present in the sequence before the iteration begins until this particular iteration is completed.
Loop iterates until the final item of the sequence are reached.
Code
Python program to show how the for loop works
Creating a sequence which is a tuple of numbers
numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
variable to store the square of the number
square = 0
Creating an empty list
squares = []
Creating a for loop
for value in numbers:
square = value ** 2
squares.append(square)
print(“The list of squares is”, squares)
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
Using else Statement with for Loop
As already said, a for loop executes the code block until the sequence element is reached. The statement is written right after the for loop is executed after the execution of the for loop is complete.
Only if the execution is complete does the else statement comes into play. It won’t be executed if we exit the loop or if an error is thrown.
Here is a code to better understand if-else statements.
Code
Python program to show how if-else statements work
string = “Python Loop”
Initiating a loop
for s in a string:
# giving a condition in if block
if s == “o”:
print(“If block”)
# if condition is not satisfied then else block will be executed
else:
print(s)
Output:
P
y
t
h
If block
n
L
If block
If block
p
Now similarly, using else with for loop.
Syntax:
for value in sequence:
# executes the statements until sequences are exhausted
else:
# executes these statements when for loop is completed
Code
Python program to show how to use else statement with for loop
Creating a sequence
tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
Initiating the loop
for value in tuple_:
if value % 2 != 0:
print(value)
giving an else statement
else:
print(“These are the odd numbers present in the tuple”)
Output:
3
9
3
9
7
These are the odd numbers present in the tuple
The range() Function
With the help of the range() function, we may produce a series of numbers. range(10) will produce values between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step size is not specified, it defaults to 1.
Since it doesn’t create every value it “contains” after we construct it, the range object can be characterized as being “slow.” It does provide in, len, and getitem actions, but it is not an iterator.
The example that follows will make this clear.
Code
Python program to show the working of range() function
print(range(15))
print(list(range(15)))
print(list(range(4, 9)))
print(list(range(5, 25, 4)))
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
To iterate through a sequence of items, we can apply the range() method in for loops. We can use indexing to iterate through the given sequence by combining it with an iterable’s len() function. Here’s an illustration.
Code
Python program to iterate over a sequence with the help of indexing
tuple_ = (“Python”, “Loops”, “Sequence”, “Condition”, “Range”)
iterating over tuple_ using range() function
for iterator in range(len(tuple_)):
print(tuple_[iterator].upper())
Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
While Loop
While loops are used in Python to iterate until a specified condition is met. However, the statement in the program that follows the while loop is executed once the condition changes to false.
Syntax of the while loop is:
while :
{ code block }
All the coding statements that follow a structural command define a code block. These statements are intended with the same number of spaces. Python groups statements together with indentation.
Code
Python program to show how to use a while loop
counter = 0
Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print(“Python Loops”)
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Using else Statement with while Loops
As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has the same syntax.
Code
Python program to show how to use else statement with the while loop
counter = 0
Iterating through the while loop
while (counter < 10):
counter = counter + 3
print(“Python Loops”) # Executed untile condition is met
Once the condition of while loop gives False this statement will be executed
else:
print(“Code block inside the else statement”)
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
Single statement while Block
The loop can be declared in a single statement, as seen below. This is similar to the if-else block, where we can write the code block in a single line.
Code
Python program to show how to write a single statement while loop
counter = 0
while (count < 3): print(“Python Loops”)
Loop Control Statements
Now we will discuss the loop control statements in detail. We will see an example of each control statement.
Continue Statement
It returns the control to the beginning of the loop.
Code
Python program to show how the continue statement works
Initiating the loop
for string in “Python Loops”:
if string == “o” or string == “p” or string == “t”:
continue
print(‘Current Letter:’, string)
Output:
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
Python program to show how the break statement works
Initiating the loop
for string in “Python Loops”:
if string == ‘L’:
break
print(‘Current Letter: ‘, string)
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and empty control statements.
Code
Python program to show how the pass statement works
for a string in “Python Loops”:
pass
print( ‘Last Letter:’, string)
Output:
Python for loop
Python is a strong, universally applicable prearranging language planned to be easy to comprehend and carry out. It is allowed to get to because it is open-source. In this tutorial, we will learn how to use Python for loops, one of the most fundamental looping instructions in Python programming.
Introduction to for Loop in Python
Python frequently uses the Loop to iterate over iterable objects like lists, tuples, and strings. Crossing is the most common way of emphasizing across a series, for loops are used when a section of code needs to be repeated a certain number of times. The for-circle is typically utilized on an iterable item, for example, a rundown or the in-fabricated range capability. In Python, the for Statement runs the code block each time it traverses a series of elements. On the other hand, the “while” Loop is used when a condition needs to be verified after each repetition or when a piece of code needs to be repeated indefinitely. The for Statement is opposed to this Loop.
Syntax of for Loop
for value in sequence:
{loop body}
The value is the parameter that determines the element’s value within the iterable sequence on each iteration. When a sequence contains expression statements, they are processed first. The first element in the sequence is then assigned to the iterating variable iterating_variable. From that point onward, the planned block is run. Each element in the sequence is assigned to iterating_variable during the statement block until the sequence as a whole is completed. Using indentation, the contents of the Loop are distinguished from the remainder of the program.
Example of Python for Loop
Code
Pause
Next
Mute
Current Time
0:04
/
Duration
18:10
Fullscreen
Code to find the sum of squares of each element of the list using for loop
creating the list of numbers
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
initializing a variable that will store the sum
sum_ = 0
using for loop to iterate over the list
for num in numbers:
sum_ = sum_ + num ** 2
print(“The sum of squares is: “, sum_)
Output:
The sum of squares is: 774
The range() Function
Since the “range” capability shows up so habitually in for circles, we could erroneously accept the reach as a part of the punctuation of for circle. It’s not: 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 (typically serial integers). Mainly, they can act straight on sequences, so counting is unnecessary. This is a typical novice construct if they originate from a language with distinct loop syntax:
Code
my_list = [3, 5, 6, 8, 4]
for iter_var in range( len( my_list ) ):
my_list.append(my_list[iter_var] + 2)
print( my_list )
Output (3, 5, 6, 8, 4, 5, 7, 8, 10, 6)
Python break statement
The break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. In other words, we can say that break is used to abort the current execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition. The syntax of the break statement in Python is given below.
Syntax:
loop statements
break;
Example 1 : break statement with for loop
Code
break statement example
my_list = [1, 2, 3, 4]
count = 1
for item in my_list:
if item == 4:
print(“Item matched”)
count += 1
break
print(“Found at location”, count)
Output:
Item matched
Found at location 2
In the above example, a list is iterated using a for loop. When the item is matched with value 4, the break statement is executed, and the loop terminates. Then the count is printed by locating the item.
Example 2 : Breaking out of a loop early
Code
break statement example
my_str = “python”
for char in my_str:
if char == ‘o’:
break
print(char)
Output:
p
y
t
h
When the character is found in the list of characters, break starts executing, and iterating stops immediately. Then the next line of the print statement is printed.
Example 3: break statement with while loop
Code
break statement example
i = 0;
while 1:
print(i,” “,end=””),
i=i+1;
if i == 10:
break;
print(“came out of while loop”);
Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop
It is the same as the above programs. The while loop is initialised to True, which is an infinite loop. When the value is 10 and the condition becomes true, the break statement will be executed and jump to the later print statement by terminating the while loop.
Example 4 : break statement with nested loops
Code
break statement example
n = 2
while True:
i = 1
while i <= 10:
print(“%d X %d = %d\n” % (n, i, n * i))
i += 1
choice = int(input(“Do you want to continue printing the table? Press 0 for no: “))
if choice == 0:
print(“Exiting the program…”)
break
n += 1
print(“Program finished successfully.”)
Output:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table? Press 0 for no: 1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Do you want to continue printing the table? Press 0 for no: 0
Exiting the program…
Python String
Till now, we have discussed numbers as the standard data-types in Python. In this section of the tutorial, we will discuss the most popular data type in Python, i.e., string.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The computer does not understand the characters; internally, it stores manipulated character as the combination of the 0’s and 1’s.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the collection of Unicode characters.
Consider the following example in Python to create a string.
Syntax:
str = “Hi Python !”
Here, if we check the type of the variable str using a Python script
print(type(str)), then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means that Python doesn’t support the character data-type; instead, a single character written as ‘p’ is treated as the string of length 1.
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides triple-quotes to represent the string, but it is generally used for multiline string or docstrings.
Using single quotes
str1 = ‘Hello Python’
print(str1)
Using double quotes
str2 = “Hello Python”
print(str2)
Using triple quotes
str3 = ””’Triple quotes are generally used for
represent the multiline or
docstring”’
print(str3)
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example, The string “HELLO” is indexed as given in the below figure.
Python String
Consider the following example:
str = “HELLO”
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
It returns the IndexError because 6th index doesn’t exist
print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can use the : (colon) operator in Python to access the substring from the given string. Consider the following example.
Python String
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = ‘HELLO’ is given, then str[1:3] will always include str[1] = ‘E’, str[2] = ‘L’ and nothing else.
Consider the following example:
Given String
str = “JAVATPOINT”
Start Oth index to end
print(str[0:])
Starts 1th index to 4th index
print(str[1:5])
Starts 2nd index to 3rd index
print(str[2:4])
Starts 0th to 2nd index
print(str[:3])
Starts 4th to 6th index
print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The second rightmost index indicates -2, and so on. Consider the following image.
Python String
Consider the following example
str = ‘JAVATPOINT’
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
Reversing the given string
print(str[::-1])
print(str[-12])
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn’t support item assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are immutable in Python.
Consider the following example.
Example 1
str = “HELLO”
str[0] = “h”
print(str)
Output:
Traceback (most recent call last):
File “12.py”, line 2, in
str[0] = “h”;
TypeError: ‘str’ object does not support item assignment
However, in example 1, the string str can be assigned completely to a new content as specified in the following example.
Example 2
str = “HELLO”
print(str)
str = “hello”
print(str)
Output:
HELLO
hello
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from the string. But we can delete the entire string using the del keyword.
str = “JAVATPOINT”
del str[1]
Output:
TypeError: ‘str’ object doesn’t support item deletion
Now we are deleting entire string.
str1 = “JAVATPOINT”
del str1
print(str1)
Output:
NameError: name ‘str1’ is not defined
String Operators
Operator
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.
in
It is known as membership operator. It returns if a particular sub-string is present in the specified string.
not in
It is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string.
r/R
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 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 in python.
Example
Consider the following example to understand the real use of Python operators.
str = “Hello”
str1 = ” world”
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print(‘w’ in str) # prints false as w is not present in str
print(‘wo’ not in str1) # prints false as wo is present in str1.
print(r’C://python37′) # prints C://python37 as it is written
print(“The string str : %s”%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Python String Formatting
Escape Sequence
Let’s suppose we need to write the text as – They said, “Hello what’s going on?”- the given statement can be written in single quotes or double quotes but it will raise the SyntaxError as it contains both single and double-quotes.
Example
Consider the following example to understand the real use of Python operators.
str = “They said, “Hello what’s going on?””
print(str)
Output:
SyntaxError: invalid syntax
We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special character and it interpreted differently. The single quotes inside the string must be escaped. We can apply the same as in the double quotes.
Example –
using triple quotes
print(””’They said, “What’s there?””’)
escaping single quotes
print(‘They said, “What\’s going on?”‘)
escaping double quotes
print(“They said, \”What’s going on?\””)
Output:
They said, “What’s there?”
They said, “What’s going on?”
They said, “What’s going on?”
Python List
In Python, the sequence of various data types is stored in a list. A list is a collection of different kinds of values or items. Since Python lists are mutable, we can change their elements after forming. The comma (,) and the square brackets [enclose the List’s items] serve as separators.
Although six Python data types can hold sequences, the List is the most common and reliable form. A list, a type of sequence data, is used to store the collection of data. Tuples and Strings are two similar data formats for sequences.
Lists written in Python are identical to dynamically scaled arrays defined in other languages, such as Array List in Java and Vector in C++. A list is a collection of items separated by commas and denoted by the symbol [].
List Declaration
CodePauseNextMute
Current Time 0:09
/
Duration 18:10
Loaded: 4.40%Fullscreen
- # a simple list
- list1 = [1, 2, “Python”, “Program”, 15.9]
- list2 = [“Amy”, “Ryan”, “Henry”, “Emma”]
- # printing the list
- print(list1)
- print(list2)
- # printing the type of list
- print(type(list1))
- print(type(list2))
Output:
[1, 2, 'Python', 'Program', 15.9] ['Amy', 'Ryan', 'Henry', 'Emma'] < class ' list ' > < class ' list ' >
Characteristics of Lists
The characteristics of the List are as follows:
- The lists are in order.
- The list element can be accessed via the index.
- The mutable type of List is
- The rundowns are changeable sorts.
- The number of various elements can be stored in a list.
Ordered List Checking
Code
- # example
- a = [ 1, 2, “Ram”, 3.50, “Rahul”, 5, 6 ]
- b = [ 1, 2, 5, “Ram”, 3.50, “Rahul”, 6 ]
- a == b
Output:
False
The indistinguishable components were remembered for the two records; however, the subsequent rundown changed the file position of the fifth component, which is against the rundowns’ planned request. False is returned when the two lists are compared.
Code
- # example
- a = [ 1, 2, “Ram”, 3.50, “Rahul”, 5, 6]
- b = [ 1, 2, “Ram”, 3.50, “Rahul”, 5, 6]
- a == b
Output:
True
Records forever protect the component’s structure. Because of this, it is an arranged collection of things.
Let’s take a closer look at the list example.
Code
- # list example in detail
- emp = [ “John”, 102, “USA”]
- Dep1 = [ “CS”,10]
- Dep2 = [ “IT”,11]
- HOD_CS = [ 10,”Mr. Holding”]
- HOD_IT = [11, “Mr. Bewon”]
- print(“printing employee data …”)
- print(” Name : %s, ID: %d, Country: %s” %(emp[0], emp[1], emp[2]))
- print(“printing departments …”)
- print(“Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s”%( Dep1[0], Dep2[1], Dep2[0], Dep2[1]))
- print(“HOD Details ….”)
- print(“CS HOD Name: %s, Id: %d” %(HOD_CS[1], HOD_CS[0]))
- print(“IT HOD Name: %s, Id: %d” %(HOD_IT[1], HOD_IT[0]))
- print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))
Output:
printing employee data... Name : John, ID: 102, Country: USA printing departments... Department 1: Name: CS, ID: 11 Department 2: Name: IT, ID: 11 HOD Details .... CS HOD Name: Mr. Holding, Id: 10 IT HOD Name: Mr. Bewon, Id: 11 <class ' list '> <class ' list '> <class ' list '> <class ' list '> <class ' list '>
In the preceding illustration, we printed the employee and department-specific details from lists that we had created. To better comprehend the List’s concept, look at the code above.
List Indexing and Splitting
The indexing procedure is carried out similarly to string processing. The slice operator [] can be used to get to the List’s components.
The index ranges from 0 to length -1. The 0th index is where the List’s first element is stored; the 1st index is where the second element is stored, and so on.

We can get the sub-list of the list using the following syntax.
- list_varible(start:stop:step)
- The beginning indicates the beginning record position of the rundown.
- The stop signifies the last record position of the rundown.
- Within a start, the step is used to skip the nth element: stop.
The start parameter is the initial index, the step is the ending index, and the value of the end parameter is the number of elements that are “stepped” through. The default value for the step is one without a specific value. Inside the resultant Sub List, the same with record start would be available, yet the one with the file finish will not. The first element in a list appears to have an index of zero.
Consider the following example:
Code
- list = [1,2,3,4,5,6,7]
- print(list[0])
- print(list[1])
- print(list[2])
- print(list[3])
- # Slicing the elements
- print(list[0:6])
- # By default, the index value is 0 so its starts from the 0th element and go for index -1.
- print(list[:])
- print(list[2:5])
- print(list[1:6:2])
Output:
1 2 3 4 [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 7] [3, 4, 5] [2, 4, 6]
In contrast to other programming languages, Python lets you use negative indexing as well. The negative indices are counted from the right. The index -1 represents the final element on the List’s right side, followed by the index -2 for the next member on the left, and so on, until the last element on the left is reached.

Let’s have a look at the following example where we will use negative indexing to access the elements of the list.
Code
- # negative indexing example
- list = [1,2,3,4,5]
- print(list[-1])
- print(list[-3:])
- print(list[:-1])
- print(list[-3:-1])
Output:
5 [3, 4, 5] [1, 2, 3, 4] [3, 4]
Negative indexing allows us to obtain an element, as previously mentioned. The rightmost item in the List was returned by the first print statement in the code above. The second print statement returned the sub-list, and so on.
Updating List Values
Due to their mutability and the slice and assignment operator’s ability to update their values, lists are Python’s most adaptable data structure. Python’s append() and insert() methods can also add values to a list.
Consider the following example to update the values inside the List.
Code
- # updating list values
- list = [1, 2, 3, 4, 5, 6]
- print(list)
- # It will assign value to the value to the second index
- list[2] = 10
- print(list)
- # Adding multiple-element
- list[1:3] = [89, 78]
- print(list)
- # It will add value at the end of the list
- list[-1] = 25
- print(list)
Output:
[1, 2, 3, 4, 5, 6] [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25]
The list elements can also be deleted by using the del keyword. Python also provides us the remove() method if we do not know which element is to be deleted from the list.
Consider the following example to delete the list elements.
Code
- list = [1, 2, 3, 4, 5, 6]
- print(list)
- # It will assign value to the value to second index
- list[2] = 10
- print(list)
- # Adding multiple element
- list[1:3] = [89, 78]
- print(list)
- # It will add value at the end of the list
- list[-1] = 25
- print(list)
Output:
[1, 2, 3, 4, 5, 6] [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25]
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were working with the strings. The different operations of list are
- Repetition
- Concatenation
- Length
- Iteration
- Membership
Let’s see how the list responds to various operators.
1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on different occasions.
Code
- # repetition of list
- # declaring the list
- list1 = [12, 14, 16, 18, 20]
- # repetition operator *
- l = list1 * 2
- print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
- # concatenation of two lists
- # declaring the lists
- list1 = [12, 14, 16, 18, 20]
- list2 = [9, 10, 32, 54, 86]
- # concatenation operator +
- l = list1 + list2
- print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
3. Length
It is used to get the length of the list
Code
- # size of the list
- # declaring the list
- list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
- # finding length of the list
- len(list1)
Output:
9
4. Iteration
The for loop is used to iterate over the list elements.
Code
- # iteration of the list
- # declaring the list
- list1 = [12, 14, 16, 39, 40]
- # iterating
- for i in list1:
- print(i)
Output:
12 14 16 39 40
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
- # membership of the list
- # declaring the list
- list1 = [100, 200, 300, 400, 500]
- # true will be printed if value exists
- # and false if not
- print(600 in list1)
- print(700 in list1)
- print(1040 in list1)
- print(300 in list1)
- print(100 in list1)
- print(500 in list1)
Output:
False False False True True True
Iterating a List
A list can be iterated by using a for – in loop. A simple list containing four strings, which can be iterated as follows.
Code
- # iterating a list
- list = [“John”, “David”, “James”, “Jonathan”]
- for i in list:
- # The i variable will iterate over the elements of the List and contains each element in each iteration.
- print(i)
Output:
John David James Jonathan
Adding Elements to the List
The append() function in Python can add a new item to the List. In any case, the annex() capability can enhance the finish of the rundown.
Consider the accompanying model, where we take the components of the rundown from the client and print the rundown on the control center.
Code
- #Declaring the empty list
- l =[]
- #Number of elements will be entered by the user
- n = int(input(“Enter the number of elements in the list:”))
- # for loop to take the input
- for i in range(0,n):
- # The input is taken from the user and added to the list as the item
- l.append(input(“Enter the item:”))
- print(“printing the list items..”)
- # traversal loop to print the list items
- for i in l:
- print(i, end = ” “)
Output:
Enter the number of elements in the list:10 Enter the item:32 Enter the item:56 Enter the item:81 Enter the item:2 Enter the item:34 Enter the item:65 Enter the item:09 Enter the item:66 Enter the item:12 Enter the item:18 printing the list items.. 32 56 81 2 34 65 09 66 12 18
Removing Elements from the List
The remove() function in Python can remove an element from the List. To comprehend this idea, look at the example that follows.
Example –
Code
- list = [0,1,2,3,4]
- print(“printing original list: “);
- for i in list:
- print(i,end=” “)
- list.remove(2)
- print(“\nprinting the list after the removal of first element…”)
- for i in list:
- print(i,end=” “)
Output:
printing original list: 0 1 2 3 4 printing the list after the removal of first element... 0 1 3 4
Python List Built-in Functions
Python provides the following built-in functions, which can be used with the lists.
- len()
- max()
- min()
len( )
It is used to calculate the length of the list.
Code
- # size of the list
- # declaring the list
- list1 = [12, 16, 18, 20, 39, 40]
- # finding length of the list
- len(list1)
Output:
6
Max( )
It returns the maximum element of the list
Code
- # maximum of the list
- list1 = [103, 675, 321, 782, 200]
- # large element in the list
- print(max(list1))
Output:
782
Min( )
It returns the minimum element of the list
Code
- # minimum of the list
- list1 = [103, 675, 321, 782, 200]
- # smallest element in the list
- print(min(list1))
Output:
103
Let’s have a look at the few list examples.
Example: 1- Create a program to eliminate the List’s duplicate items.
Code
- list1 = [1,2,2,3,55,98,65,65,13,29]
- # Declare an empty list that will store unique values
- list2 = []
- for i in list1:
- if i not in list2:
- list2.append(i)
- print(list2)
Output:
[1, 2, 3, 55, 98, 65, 13, 29]
Python Tuples
In the following tutorial, we will understand the fundamentals of Tuples in the Python programming language.
Understanding the Tuples in Python
Tuple is one of the four primary data types in Python. It is a used for storing a collection of objects. A tuple is quite similar to a Python list in terms of indexing, nested objects, and repetition; however, the main difference between both is that the tuples in Python are immutable, unlike the Python list which is mutable.
The following is an example of a tuple.
Example:
- (“Suzuki”, “Audi”, “BMW”,” Skoda ) is a tuple.
Key Features of Python Tuple
- Tuples are an immutable data type, implying that the data elements of this data type cannot be changed after they are generated.
- Each data element in a tuple has a particular order that never changes as the tuples are ordered sequences.
Forming a Tuple:
All the objects-also known as “elements”-must be separated by a comma, enclosed in parenthesis (). Although parentheses are not required, they are recommended.
Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be contained in a tuple.
Let us consider the following example demonstrating the inclusion of different data types in a tuple:
Code:
- # Python program to show how to create a tuple
- # Creating an empty tuple
- emptyTuple = ()
- print(“Empty tuple: “, emptyTuple)
- # Creating a tuple having integers
- integerTuple = (3, 6, 7, 10, 16, 23)
- print(“Tuple with integers: “, integerTuple)
- # Creating a tuple having objects of different data types
- mixedTuple = (6, “Javatpoint”, 14.3)
- print(“Tuple with different data types: “, mixedTuple)
- # Creating a nested tuple
- nestedTuple = (“Javatpoint”, {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
- print(“A nested tuple: “, nestedTuple)
Output:
Empty tuple: () Tuple with integers: (3, 6, 7, 10, 16, 23) Tuple with different data types: (6, 'Javatpoint', 14.3) A nested tuple: ('Javatpoint', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Explanation:
In the above snippet of code, we have created four different tuples containing different types of elements. The first tuple is an empty tuple defined using the parentheses with no element in between. After that, we have defined an integer tuple consisting of 6 integer values between the parentheses separated by the commas. The third tuple is comprised of three objects of different data types – integer, string, and float. At last, we have defined a tuple as a different object, including another tuple.
Moreover, it is not necessary to declare and initialize a tuple using the parentheses. Let us consider the following example demonstrating the same.
Code:
- # Python program to create a tuple without using parentheses
- # Creating a tuple
- tupleWithoutParentheses = 6, 8.7, “Javatpoint”, [“Python”, “Tutorials”]
- # Displaying the tuple created
- print(tupleWithoutParentheses)
- # Checking the data type of object tupleWithoutParentheses
- print(type(tupleWithoutParentheses) )
- # Trying to modify tupleWithoutParentheses
- try:
- tupleWithoutParentheses[1] = 9.5
- except:
- print(“TypeError: Tuples are immutable data types and cannot be modified.”)
Output:
(6, 8.7, 'Javatpoint', ['Python', 'Tutorials']) <class 'tuple'> TypeError: Tuples are immutable data types and cannot be modified.
Explanation:
In the above snippet of code, we have defined a tuple containing several elements separated by the commas, without the use of parentheses and printed it for the users. For better clarity, we have returned its type using the type() method. We have also tried modifying the element of the tuple using the try and except blocks. As a result, the first line displays the elements of the tuples. The second line displays the type of the variable which is ‘Tuple’. At last, we can observe a TypeError implying the immutability of the tuples.
The development of a tuple from a solitary part may be complex. Essentially adding a bracket around the component is lacking. A comma must separate the element to be recognized as a tuple.
Let us consider another example illustration the importance of a comma in tuple.
Code:
- # Python program to show how to create a tuple having a single element
- # Creating a tuple without using comma
- singleTuple = (“Arnold”)
- print(“Type of the variable ‘singleTuple’ =>”, type(singleTuple)) # returns <class ‘str’>
- # Creating a tuple that has only one element
- singleTuple = (“Arnold”,)
- print(“Type of the variable ‘singleTuple’ =>”, type(singleTuple)) # returns <class ‘tuple’>
- # Creating a tuple without parentheses
- singleTuple = “Arnold”,
- print(“Type of the variable ‘singleTuple’ =>”, type(singleTuple)) # returns <class ‘tuple’>
Output:
Type of the variable 'singleTuple' => <class 'str'> Type of the variable 'singleTuple' => <class 'tuple'> Type of the variable 'singleTuple' => <class 'tuple'>
Accessing Tuple Elements
Now that we have understood the ways of initializing and declaring a tuple, it is time for us to understand how to access the objects or elements of a Tuple.
In Python, we can access any object of a tuple using indices. Let us discuss the tuple indexing in detail.
Indexing
The objects or elements of a tuple can be accessed by referring to the index number, inside of square brackets ‘[]’. Moreover, the indexing in tuple is as simple as in the case of lists, where the first element has an index value of 0 and ranges to the last element with index value of n – 1 for n number of elements in the tuple.
Thus, we can say that the indices of a tuple having five elements will range from 0 to 4. An Index Error will be raised in case we try to access an element from the tuple that exceeds the index range of that tuple. Therefore, an index value above 4 will be considered out of range in this scenario.
Furthermore, the index in Python accepts integer or slices only. This statement implies that it will raise a Type Error if we provide a floating-point data type as an index value.
Let us consider the following example illustrating how to access an element of a tuple using indexing:
Code:
- # Python program to show how to access tuple elements
- # Creating a tuple having six elements
- sampleTuple = (“Apple”, “Mango”, “Banana”, “Orange”, “Guava”, “Berries”)
- # accessing the elements of a tuple using indexing
- print(“First Element of the Given Tuple:”, sampleTuple[0])
- print(“Second Element of the Given Tuple:”, sampleTuple[1])
- print(“Third Element of the Given Tuple:”, sampleTuple[2])
- print(“Forth Element of the Given Tuple:”, sampleTuple[3])
- print(“Fifth Element of the Given Tuple:”, sampleTuple[4])
- print(“Sixth Element of the Given Tuple:”, sampleTuple[5])
- # trying to access element index more than the length of a tuple
- try:
- print(“Seventh Element of the Given Tuple:”, sampleTuple[6])
- except Exception as e:
- print(e)
- # trying to access elements through the index of floating data type
- try:
- print(“Accessing Second Element of the Given Tuple using floating-point index value:”, sampleTuple[1.0])
- except Exception as e:
- print(e)
- # Creating a nested tuple
- nestedTuple = (“Fruits”, [4, 6, 2, 6], (6, 2, 6, 7))
- # Accessing the index of a nested tuple
- print(nestedTuple[0][3])
- print(nestedTuple[1][1])
Output:
First Element of the Given Tuple: Apple Second Element of the Given Tuple: Mango Third Element of the Given Tuple: Banana Forth Element of the Given Tuple: Orange Fifth Element of the Given Tuple: Guava Sixth Element of the Given Tuple: Berries tuple index out of range tuple indices must be integers or slices, not float i 6
Explanation:
In the above snippet of code, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have then used the indexing to access each of the elements from the given tuple and printed them for the users. After that, we have tried accessing an ‘out-of-range’ index value from the tuple, i.e., 6. As a result, we can observe a raised exception indicating ‘tuple index out of range’. We have then attempted to access an element from the tuple using a floating-point value as the index number. As we can observe in the output, it has also raised an exception indicating ‘tuple indices must be integers or slices, not float’. We have then defined a nested tuple consisting of several elements. We have then used the indexing to access the different elements of the nested tuple.
Negative Indexing
Apart from indexing, the tuple’s objects in Python can be accessed using the negative indexing.
In negative indexing, the elements of a tuple are accessed using the negative integer values. This technique is used to access the elements from the end implying that the last element of the tuple is accessed with the index value of -1. Similarly, the second last element is accessed by the index value of -2, the third last element with -3, and so on.
Let us consider the following example illustrating the working of the negative indexing in respect to Python tuples:
Code:
- # Python program to show how negative indexing works in Python tuples
- # Creating a tuple
- sampleTuple = (“Apple”, “Mango”, “Banana”, “Orange”, “Guava”, “Berries”)
- # Printing elements using negative indices
- print(“Element at -1 index: “, sampleTuple[-1])
- print(“Element at -2 index: “, sampleTuple[-2])
- print(“Element at -3 index: “, sampleTuple[-3])
- print(“Element at -4 index: “, sampleTuple[-4])
- print(“Element at -5 index: “, sampleTuple[-5])
- print(“Element at -6 index: “, sampleTuple[-6])
- # Printing the range of elements using negative indices
- print(“Elements between -6 and -1 are: “, sampleTuple[-6:-1])
Output:
Element at -1 index: Berries Element at -2 index: Guava Element at -3 index: Orange Element at -4 index: Banana Element at -5 index: Mango Element at -6 index: Apple Elements between -6 and -1 are: ('Apple', 'Mango', 'Banana', 'Orange', 'Guava')
Explanation:
In the above snippet of code, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have then used the negative indexing to access the elements of the tuple from the end. We have also tried accessing the elements ranging from -6 to -1 using the slicing approach that we will learn in the following sections. As a result, we can observe the tuple of elements ranging between -6 and -1.
Slicing in Tuple
Slicing a Tuple is considered a common practice in Python and a general approach to deal with practical problems in programming. Slicing a tuple means dividing a tuple into smaller tuples with the help of indexing. In order to slice a tuple, we need to specify the starting and ending index value, that will return a new tuple with the specified objects.
We can slice a tuple using the colon ‘:’ operator separating the start and end index as shown below:
Syntax:
- tuple[start:end]
Let us consider the following example illustrating how to slice a tuple in Python:
Code:
- # Python program to show how slicing works in Python tuples
- # Creating a tuple
- sampleTuple = (“Apple”, “Mango”, “Banana”, “Orange”, “Guava”, “Berries”)
- # Using slicing to access elements of the tuple
- print(“Elements between indices 1 and 5: “, sampleTuple[1:5])
- # Using negative indexing in slicing
- print(“Elements between indices 0 and -3: “, sampleTuple[:-3])
- # Printing the entire tuple by using the default start and end values
- print(“Entire tuple: “, sampleTuple[:])
Output:
Elements between indices 1 and 5: ('Mango', 'Banana', 'Orange', 'Guava') Elements between indices 0 and -3: ('Apple', 'Mango', 'Banana') Entire tuple: ('Apple', 'Mango', 'Banana', 'Orange', 'Guava', 'Berries')
Explanation:
In the above snippet of code, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have printed the tuple of elements ranging from 1 to 5 using the slicing method as discussed earlier. We have then printed the elements ranging from 0 to -3 using the negative indexing in slicing. At last, we have printed the entire tuple using the colon ‘:’ operator only without specifying the start and end index values.
Deleting a Tuple
As we have already discussed, unlike lists, tuples are immutable data types meaning that we cannot update the objects of a tuple once it is created. Therefore, removing the elements of the tuple is also not possible. However, we can delete the entire tuple using the ‘del’ keyword as shown below.
Syntax:
- del tuple_name
Let us consider the following snippet of code illustrating the method of deleting a tuple with the help of the ‘del’ keyword.
Code:
- # Python program to show how to delete elements of a Python tuple
- # Creating a tuple
- sampleTuple = (“Apple”, “Mango”, “Banana”, “Orange”, “Guava”, “Berries”)
- # printing the entire tuple for reference
- print(“Given Tuple:”, sampleTuple)
- # Deleting a particular element of the tuple using the del keyword
- try:
- del sampleTuple[3]
- print(sampleTuple)
- except Exception as e:
- print(e)
- # Deleting the variable from the global space of the program using the del keyword
- del sampleTuple
- # Trying accessing the tuple after deleting it
- try:
- print(sampleTuple)
- except Exception as e:
- print(e)
Output:
Given Tuple: ('Apple', 'Mango', 'Banana', 'Orange', 'Guava', 'Berries') 'tuple' object doesn't support item deletion name 'sampleTuple' is not defined
Explanation:
In the above snippet of code, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have then printed the entire tuple for reference. After that, we have used the try and except blocks to delete a particular element from the tuple using the del keyword. As a result, an exception has been raised saying ‘tuple’ object doesn’t support item deletion. We have then used the del keyword to delete the entire tuple and tried printing it. As a result, we can observe another exception saying name ‘sampleTuple’ is not defined.
Changing the Elements in Tuple
Once we create a tuple, it is impossible for us to change its elements due its immutable nature. However, there is a way to update the elements of a tuple. We can convert the tuple into a list, change the list, and convert the list back into a tuple.
Let us consider the following example illustrating the method of changing the elements in tuple.
Code:
- # Python program to demonstrate the approach of changing the element in the tuple
- # creating a tuple
- fruits_tuple = (“mango”, “orange”, “banana”, “apple”, “papaya”)
- # printing the tuple before update
- print(“Before Changing the Element in Tuple…”)
- print(“Tuple =”, fruits_tuple)
- # converting the tuple into the list
- fruits_list = list(fruits_tuple)
- # changing the element of the list
- fruits_list[2] = “grapes”
- print(“Converting”, fruits_tuple[2], “=>”, fruits_list[2])
- # converting the list back into the tuple
- fruits_tuple = tuple(fruits_list)
- # printing the tuple after update
- print(“After Changing the Element in Tuple…”)
- print(“Tuple =”, fruits_tuple)
Output:
Before Changing the Element in Tuple... Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya') Converting banana => grapes After Changing the Element in Tuple... Tuple = ('mango', 'orange', 'grapes', 'apple', 'papaya')
Explanation:
In the above snippet of code, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have convert the tuple into a list using the list() method. We have then changed the element at index 2 of the list to ‘grapes’ and used the tuple() method to convert the update list back to the tuple. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element at index 2 also changed from ‘banana’ to ‘grapes’ respectively.
Adding Elements to a Tuple
Since Tuple is an immutable data type, it does not have the built-in append() method to add the elements. However, there are few ways we can use in order to add an element to a tuple.
Converting the Tuple into a List
In order to add a new element to a tuple, we can follow a similar approach we used while changing the element in a tuple. The approach follows the steps discussed below:
Step 1: Convert the Tuple into a List.
Step 2: Add the required element to the list using the append() method.
Step 3: Convert the List back into the Tuple.
Let us consider the following snippet of code, demonstrating the same.
Code:
- # Python program to demonstrate an approach of adding the element in the tuple by converting it into a list
- # creating a tuple
- fruits_tuple = (“mango”, “orange”, “banana”, “apple”, “papaya”)
- # printing the tuple before update
- print(“Before Adding a New Element in Tuple…”)
- print(“Original Tuple =”, fruits_tuple)
- # converting the tuple into the list
- fruits_list = list(fruits_tuple)
- # changing the element of the list
- fruits_list.append(“blueberry”)
- print(“Adding New Element -> ‘blueberry’”)
- # converting the list back into the tuple
- fruits_tuple = tuple(fruits_list)
- # printing the tuple after update
- print(“After Adding a New Element in Tuple…”)
- print(“Updated Tuple =”, fruits_tuple)
Output:
Before Adding a New Element in Tuple... Original Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya') Adding New Element -> 'blueberry' After Adding a New Element in Tuple... Updated Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya', 'blueberry')
Explanation:
In the above snippet of code, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have convert the tuple into a list using the list() method. We have then added a new element ‘blueberry’ in the list using the append() method. After that, we have used the tuple() method to convert the update list back to the tuple. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element ‘blueberry’ has been added to the given tuple respectively.
Adding a Tuple to a Tuple
In Python, we are allowed to add multiple tuples to tuples. Therefore, if we want to insert a new element to a tuple, we can follow the steps as shown below:
Step 1: Create a new Tuple with the element(s) we want to add.
Step 2: Adding the new tuple to the existing tuple.
Let us consider the following example, illustrating the same.
Code:
- # Python program to demonstrate an approach of adding the element in the tuple by adding a new tuple to the existing one
- # creating a tuple
- fruits_tuple = (“mango”, “orange”, “banana”, “apple”, “papaya”)
- # printing the tuple before update
- print(“Before Adding a New Element in Tuple…”)
- print(“Original Tuple =”, fruits_tuple)
- # creating a new tuple consisting new element(s)
- temp_tuple = (“pineapple”, )
- # adding the new tuple to the existing tuple
- # fruits_tuple = fruits_tuple + temp_tuple
- fruits_tuple += temp_tuple
- # printing the tuple after update
- print(“Adding New Element -> ‘pineapple’”)
- print(“After Adding a New Element in Tuple…”)
- print(“Updated Tuple =”, fruits_tuple)
Output:
Before Adding a New Element in Tuple... Original Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya') Adding New Element -> 'pineapple' After Adding a New Element in Tuple... Updated Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya', 'pineapple')
Explanation:
In the above snippet of code, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have created a new tuple consisting of another element ‘blueberry’. After that, we have added the new tuple to the existing tuple using the ‘+’ operator. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element ‘pineapple’ has been added to the given tuple respectively.
Unpacking Tuples
While initializing a tuple, we generally assign objects to it. This process is known as ‘packing’ a tuple.
However, Python offers us an accessibility to extract the objects back into variables. This process of extracting the objects from a tuple and assign them to different variables is known as ‘unpacking’ a tuple.
Let us consider the following example illustrating the way of unpacking a tuple in Python.
Code:
- # Python program to demonstrate an approach of unpacking a tuple
- # creating a tuple (Packing a Tuple)
- fruits_tuple = (“mango”, “orange”, “banana”, “apple”, “papaya”)
- # printing the given tuple for reference
- print(“Given Tuple :”, fruits_tuple)
- # unpacking a tuple
- (varOne, varTwo, varThree, varFour, varFive) = fruits_tuple
- # printing the results
- print(“First Variable :”, varOne)
- print(“Second Variable :”, varTwo)
- print(“Third Variable :”, varThree)
- print(“Fourth Variable :”, varFour)
- print(“Fifth Variable :”, varFive)
Output:
Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya') First Variable : mango Second Variable : orange Third Variable : banana Fourth Variable : apple Fifth Variable : papaya
Explanation:
In the above snippet of code, we have created a tuple of five elements – mango, orange, banana, apple, and papaya. We have printed the initialized tuple for reference. After that, we have unpacked the tuple by assigning each element of the tuple at right to their corresponding variables at left. At last, we have printed the values of different initialized variables. As a result, the tuple is unpacked successfully, and the values are assigned to the variables.
Note:While unpacking a tuple, the number of variables on left-hand side should be equal to the number of elements in a given tuple. In case, the variables do not match the size of the tuple, we can use an asterisk ‘*’ in order to store the remaining elements as a list.
Let us consider the following example.
Code:
- # Python program to demonstrate an approach of unpacking a tuple
- # creating a tuple (Packing a Tuple)
- fruits_tuple = (“mango”, “orange”, “banana”, “apple”, “papaya”)
- # printing the given tuple for reference
- print(“Given Tuple :”, fruits_tuple)
- # unpacking a tuple
- # here, we are using * to store the remaining elements of the tuple in a list
- (varOne, varTwo, *varThree) = fruits_tuple
- # printing the results
- print(“First Variable :”, varOne)
- print(“Second Variable :”, varTwo)
- print(“Third Variable :”, varThree)
Output:
Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya') First Variable : mango Second Variable : orange Third Variable : ['banana', 'apple', 'papaya']
Explanation:
In the above snippet of code, we have created a tuple of five elements – mango, orange, banana, apple, and papaya. We have printed the initialized tuple for reference. After that, we have unpacked the tuple by assigning each element of the tuple at right to their corresponding variables at left. Since, this time the number of variables is less than the number of elements in the tuple, we have used asterisk ‘*’ in order to store the remaining elements of the tuple in a list. At last, we have printed the values of different initialized variables. As a result, the tuple is unpacked successfully, and the values are assigned to the variables. Here, we can also observe that the third variable is initialized as a list storing the remaining elements of the tuple.
Looping Tuples
Python offers different ways to loop through a tuple. Some of these ways are as follows:
- Using ‘for’ loop
- Using ‘while’ loop
Let us discuss these approaches in the following sections.
Looping through a Tuple using ‘for’ Loop
Python ‘for’ loop allow us to iterate through a sequence (tuple, list, etc.) giving access to their elements.
Let us consider the following example illustrating the use of ‘for’ loop to iterate through a given tuple.
Code:
- # Python program to loop through a tuple using the ‘for’ loop
- # creating a tuple
- fruits_tuple = (“mango”, “orange”, “banana”, “apple”, “papaya”, “cherry”, “strawberry”, “guava”, “pineapple”, “watermelon”)
- # printing the given tuple for reference
- print(“Given Tuple :”, fruits_tuple)
- print(“Elements of the Tuple:”)
- # iterating through the tuple
- for fruit in fruits_tuple:
- # printing the element
- print(fruit)
Output:
Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya', 'cherry', 'strawberry', 'guava', 'pineapple', 'watermelon') Elements of the Tuple: mango orange banana apple papaya cherry strawberry guava pineapple watermelon
Explanation:
In the above snippet of code, we have created a tuple containing some elements and printed it for reference. We have then used the ‘for’ loop to iterate through each element of tuple and printed them. As a result, the elements of the tuple are printed successfully.
We can also iterate through the given tuple by referring to their indices. This can be done by implementing the range() and len() methods.
Let us consider the following snippet of code illustrating the use of these methods to iterate through a given tuple.
Code:
- # Python program to loop through a tuple using the ‘for’ loop
- # creating a tuple
- fruits_tuple = (“mango”, “orange”, “banana”, “apple”, “papaya”, “cherry”, “strawberry”, “guava”, “pineapple”, “watermelon”)
- # printing the given tuple for reference
- print(“Given Tuple :”, fruits_tuple)
- print(“Elements of the Tuple:”)
- # iterating through the tuple
- for i in range(len(fruits_tuple)):
- # printing the element
- print(i + 1, “-“, fruits_tuple[i])
Output:
Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya', 'cherry', 'strawberry', 'guava', 'pineapple', 'watermelon') Elements of the Tuple: 1 - mango 2 - orange 3 - banana 4 - apple 5 - papaya 6 - cherry 7 - strawberry 8 - guava 9 - pineapple 10 - watermelon
Explanation:
In the above snippet of code, we have created a tuple containing some elements and printed it for reference. We have then used the ‘for’ loop and set the range to the size of the tuple using the len() method inside the range() method to iterate through the index values of the tuple. At last, we have printed the elements of tuple by accessing the iterated indices. As a result, the elements of the tuple are printed successfully.
Looping through a Tuple using ‘while’ Loop
Python ‘while’ loop also allow us to iterate through elements of a given sequence (tuple, list, etc.)
By initializing the starting point and using the len() method to determine the size of the tuple, we can loop the way through the elements of the tuple by referring to their indices. Remember to increment the index value by 1 after each iteration.
Let us consider the following example illustrating the use of ‘while’ loop to iterate through a given tuple.
Code:
- # Python program to loop through a tuple using the ‘while’ loop
- # creating a tuple
- fruits_tuple = (“mango”, “orange”, “banana”, “apple”, “papaya”, “cherry”, “strawberry”, “guava”, “pineapple”, “watermelon”)
- # printing the given tuple for reference
- print(“Given Tuple :”, fruits_tuple)
- print(“Elements of the Tuple:”)
- # initializing an iterable with 0
- i = 0
- # using the while loop to iterate through the tuple
- while i < len(fruits_tuple):
- # printing the element of the tuple
- print(i + 1, “-“, fruits_tuple[i])
- # incrementing the index value by 1
- i += 1
Output:
Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya', 'cherry', 'strawberry', 'guava', 'pineapple', 'watermelon')
Elements of the Tuple:
1 - mango
2 - orange
3 - banana
4 - apple
5 - papaya
6 - cherry
7 - strawberry
8 - guava
9 - pineapple
10 - watermelon
Python List Vs Tuple
This tutorial will study the major differences between lists and tuples and how to handle these two data structures.
Lists and tuples are types of data structures that hold one or more than one objects or items in a predefined order. We can contain objects of any data type in a list or tuple, including the null data type defined by the None Keyword.
What is a List?
In other programming languages, list objects are declared similarly to arrays. Lists don't have to be homogeneous all the time, so they can simultaneously store items of different data types. This makes lists the most useful tool. The list is a kind of container data Structure of Python that is used to hold numerous pieces of data simultaneously. Lists are helpful when we need to iterate over some elements and keep hold of the items.
What is a Tuple?
A tuple is another data structure to store the collection of items of many data types, but unlike mutable lists, tuples are immutable. A tuple, in other words, is a collection of items separated by commas. Because of its static structure, the tuple is more efficient than the list.
Play
Next
Mute
Current Time
0:00
/
Duration
18:10
Fullscreen
Backward Skip 10s
Play Video
Forward Skip 10s
Differences between Lists and Tuples
In most cases, lists and tuples are equivalent. However, there are some important differences to be explored in this article.
List and Tuple Syntax Differences
The syntax of a list differs from that of a tuple. Items of a tuple are enclosed by parentheses or curved brackets (), whereas items of a list are enclosed by square brackets [].
Example Code
# Python code to show the difference between creating a list and a tuple
list_ = [4, 5, 7, 1, 7]
tuple_ = (4, 1, 8, 3, 9)
print("List is: ", list_)
print("Tuple is: ", tuple_)
Output:
List is: [4, 5, 7, 1, 7]
Tuple is: (4, 1, 8, 3, 9)
We declared a variable named list_, which contains a certain number of integers ranging from 1 to 10. The list is enclosed in square brackets []. We also created a variable called tuple_, which holds a certain number of integers. The tuple is enclosed in curly brackets (). The type() method in Python returns the data type of the data structure or object passed to it.
Example Code
# Code to print the data type of the data structure using the type() function
print( type(list_) )
print( type(tuple_) )
Output:
<class 'list'>
<class 'tuple'>
Mutable List vs. Immutable Tuple
An important difference between a list and a tuple is that lists are mutable, whereas tuples are immutable. What exactly does this imply? It means a list's items can be changed or modified, whereas a tuple's items cannot be changed or modified.
We can't employ a list as a key of a dictionary because it is mutable. This is because a key of a Python dictionary is an immutable object. As a result, tuples can be used as keys to a dictionary if required.
Let's consider the example highlighting the difference between lists and tuples in immutability and mutability.
Example Code
# Updating the element of list and tuple at a particular index
# creating a list and a tuple
list_ = ["Python", "Lists", "Tuples", "Differences"]
tuple_ = ("Python", "Lists", "Tuples", "Differences")
# modifying the last string in both data structures
list_[3] = "Mutable"
print( list_ )
try:
tuple_[3] = "Immutable"
print( tuple_ )
except TypeError:
print( "Tuples cannot be modified because they are immutable" )
Output:
['Python', 'Lists', 'Tuples', 'Mutable']
Tuples cannot be modified because they are immutable
We altered the string of list_ at index 3 in the above code, which the Python interpreter updated at index 3 in the output. Also, we tried to modify the last index of the tuple in a try block, but since it raised an error, we got output from the except block. This is because tuples are immutable, and the Python interpreter raised TypeError on modifying the tuple.
Size Difference
Since tuples are immutable, Python allocates bigger chunks of memory with minimal overhead. Python, on the contrary, allots smaller memory chunks for lists. The tuple would therefore have less memory than the list. If we have a huge number of items, this makes tuples a little more memory-efficient than lists.
For example, consider creating a list and a tuple with the identical items and comparing their sizes:
Example Code
# Code to show the difference in the size of a list and a tuple
#creating a list and a tuple
list_ = ["Python", "Lists", "Tuples", "Differences"]
tuple_ = ("Python", "Lists", "Tuples", "Differences")
# printing sizes
print("Size of tuple: ", tuple_.__sizeof__())
print("Size of list: ", list_.__sizeof__())
Output:
Size of tuple: 28
Size of list: 52
Available Functions
Tuples have fewer built-in functions than lists. We may leverage the in-built function dir([object] to access all the corresponding methods for the list and tuple.
Example Code
# printing directory of list
dir(list_)
Output:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Example Code
# Printing directory of a tuple
print( dir(tuple_), end = ", " )
Output:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
As we can observe, a list has many more methods than a tuple. With intrinsic functions, we can perform insert and pop operations and remove and sort items from the list not provided in the tuple.
Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they are capable of imitating real-world data arrangements where a certain value exists for a given key.
The data is stored as key-value pairs using a Python dictionary.
This data structure is mutable
The components of dictionary were made using keys and values.
Keys must only have one component.
Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values can be any Python object. The keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers. Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally unordered.
Creating the Dictionary
Curly brackets are the simplest way to generate a Python dictionary, although there are other approaches as well. With many key-value pairs surrounded in curly brackets and a colon separating each key from its value, the dictionary can be built. (:). The following provides the syntax for defining the dictionary.
Pause
Next
Mute
Current Time
0:13
/
Duration
18:10
Fullscreen
Syntax:
Dict = {"Name": "Gayle", "Age": 25}
In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of an immutable object.
Let's see an example to create a dictionary and print its content.
Code
Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}
Python provides the built-in function dict() method which is also used to create the dictionary.
The empty curly braces {} is used to create empty dictionary.
Code
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Rinku'), (2, Singh)])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output
Empty Dictionary:
{}
Create Dictionary by using dict():
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
Dictionary with each item as a pair:
{4: 'Rinku', 2: 'Singh'}
Accessing the dictionary values
To access data contained in lists and tuples, indexing has been studied. The keys of the dictionary can be used to obtain the values because they are unique from one another. The following method can be used to access dictionary values.
Code
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output
ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO
Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result as given by the indexing.
Adding Dictionary Values
The dictionary is a mutable data type, and utilising the right keys allows you to change its values. Dict[key] = value and the value can both be modified. An existing value can also be updated using the update() method.
Note: The value is updated if the key-value pair is already present in the dictionary. Otherwise, the dictionary's newly added keys.
Let's see an example to update the dictionary values.
Example - 1:
Code
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)
Output
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}
Updated key value:
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}
Example - 2:
Code
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Output
<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter the details of the new employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Code
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.
The last print statement in the above code, it raised an error because we tried to print the Employee dictionary that already deleted.
Deleting Elements using pop() Method
A dictionary is a group of key-value pairs in Python. You can retrieve, insert, and remove items using this unordered, mutable data type by using their keys. The pop() method is one of the ways to get rid of elements from a dictionary. In this post, we'll talk about how to remove items from a Python dictionary using the pop() method.
The value connected to a specific key in a dictionary is removed using the pop() method, which then returns the value. The key of the element to be removed is the only argument needed. The pop() method can be used in the following ways:
Code
# Creating a Dictionary
Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = Dict1.pop(2)
print(Dict1)
Output
Python OOPs Concepts
Like other general-purpose programming languages, Python is also an object-oriented language since its beginning. It allows us to develop applications using an Object-Oriented approach. In Python, we can easily create and use classes and objects.
An 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. The oops concept focuses on writing the reusable code. It is a widespread technique to solve the problem by creating objects.
Major principles of object-oriented programming system are given below.
Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Class
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.
Pause
Next
Mute
Current Time
0:10
/
Duration
18:10
Fullscreen
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the function source code.
When we define a class, it needs to create an object to allocate the memory. Consider the following example.
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two attributes modelname and year. We have created a c1 object to access the class attribute. The c1 object will allocate memory for these values. We will learn more about class and object in the next tutorial.
Method
The method is a function that is associated with an object. In Python, a method is not unique to class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which simulates the real-world concept of inheritance. It specifies that the child object acquires all the properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of another class. The new class is known as a derived class or child class, and the one whose properties are acquired is known as a base class or parent class.
It provides the re-usability of the code.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means shape. By polymorphism, we understand that one task can be performed in different ways. For example - you have a class animal, and all animals speak. But they speak differently. Here, the "speak" behavior is polymorphic in a sense and depends on the animal. So, the abstract "animal" concept does not actually "speak", but specific animals (like dogs and cats) have a concrete implementation of the action "speak".
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names to things so that the name captures the core of what a function or a whole program does.
Creating the table
In this section of the tutorial, we will create the new table Employee. We have to mention the database name while establishing the connection object.
We can create the new table by using the CREATE TABLE statement of SQL. In our database PythonDB, the table Employee will have the four columns, i.e., name, id, salary, and department_id initially.
The following query is used to create the new table Employee.
> create table Employee (name varchar(20) not null, id int primary key, salary float not null, Dept_Id int not null)
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Creating a table with name Employee having four columns i.e., name, id, salary, and department id
dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null primary key, salary float not null, Dept_id int not null)")
except:
myconn.rollback()
myconn.close()
Creating table
Now, we may check that the table Employee is present in the database.
Pause
Next
Mute
Current Time
0:05
/
Duration
18:10
Fullscreen
Alter Table
Sometimes, we may forget to create some columns, or we may need to update the table schema. The alter statement used to alter the table schema if required. Here, we will add the column branch_name to the table Employee. The following SQL query is used for this purpose.
alter table Employee add branch_name varchar(20) not null
Consider the following example.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#adding a column branch name to the table Employee
cur.execute("alter table Employee add branch_name varchar(20) not null")
except:
myconn.rollback()
myconn.close()
Creating the table
Python MongoDB Connectivity
To create connection between Python programming language and MongoDB database, we need to first install pymongo driver. Here, we are creating an example that connects to the database and performs basic database operations.
This example includes the following steps:
1) Install Driver
- $ pip install pymongo
2) Create Python File
// connect.py
- from pymongo import MongoClient # import mongo client to connect
- import pprint
- # Creating instance of mongoclient
- client = MongoClient()
- # Creating database
- db = client.javatpoint
- employee = {“id”: “101”,
- “name”: “Peter”,
- “profession”: “Software Engineer”,
- }
- # Creating document
- employees = db.employees
- # Inserting data
- employees.insert_one(employee)
- # Fetching data
- pprint.pprint(employees.find_one())
3) Execute Python Script
This script prints the inserted record on the console.
4) Enter into Mongo Shell
Now, enter into MongoDB database shell to see the created database and collection.
We can use following command to enter into the database.
- $ mongo
5) Check Databases
The following command is used to show available databases.
- > show dbs
6) Check Collection
The following command is used to show available collection into the database.
- > show collections
7) Access Records
We can see the stored records in particular collection. The following command is used to show the record.
- > db.employees.find()
Connect SQLite with Python
First you have to install Python and SQLite on your syatem.
Install Python
Use the following code:
sudo apt-get update
sudo apt-get upgrade python
SQLite Connect sqlite with python 1
Press y and installation will be completed within seconds.
Install SQLite
Installation steps
type in the following command:
sudo apt-get install sqlite3 libsqlite3-dev
After installation check installation, sqlite terminal will give you a prompt and version info ?
sqlite3
Go to desired folder and create database:
sqlite3 database.db
It’ll create database.db in the folder you’ve given the command.
To check if your database is created, use the following command in sqlite3 terminal:
.databases
Note: To connect SQLite with Python, you do not need to install the connection module separately because its being shipped by default along with Python version 2.5.x onwards.
SQLite with Python
Create a python file “connect.py”, having the following code:
!/usr/bin/python
import sqlite3
conn = sqlite3.connect(‘javatpoint.db’)
print “Opened database successfully”;
Execute the following statement on command prompt:
python connect.py
SQLite Connect sqlite with python 2
Now connection is created with the javatpoint database. Now you can create a table.
Create a table
Create a table “Employees” within the database “javatpoint”.
Create a python file “createtable.py”, having the following code:
!/usr/bin/python
import sqlite3
conn = sqlite3.connect(‘javatpoint.db’)
print “Opened database successfully”;
conn.execute(””’CREATE TABLE Employees
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);”’)
print “Table created successfully”;
conn.close()
Execute the following statement on command prompt:
python createtable.py
SQLite Connect sqlite with python 3
A table “Employees” is created in the “javatpoint” database.
Insert Records
Insert some records in “Employees” table.
Create a python file “connection.py”, having the following code:
!/usr/bin/python
import sqlite3
conn = sqlite3.connect(‘javatpoint.db’)
print “Opened database successfully”;
conn.execute(“INSERT INTO Employees (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, ‘Ajeet’, 27, ‘Delhi’, 20000.00 )”);
conn.execute(“INSERT INTO Employees (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (2, ‘Allen’, 22, ‘London’, 25000.00 )”);
conn.execute(“INSERT INTO Employees (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (3, ‘Mark’, 29, ‘CA’, 200000.00 )”);
conn.execute(“INSERT INTO Employees (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (4, ‘Kanchan’, 22, ‘Ghaziabad ‘, 65000.00 )”);
conn.commit()
print “Records inserted successfully”;
conn.close()
Execute the following statement on command prompt:
python connection.py
SQLite Connect sqlite with python 4
Records are inserted successfully.
Select Records
Now you can fetch and display your records from the table “Employees” by using SELECT statement.
Create a python file “select.py”, having the following code:
!/usr/bin/python
import sqlite3
conn = sqlite3.connect(‘javatpoint.db’)
data = conn.execute(“select * from Employees”);
for row in data:
print “ID = “, row[0]
print “NAME = “, row[1]
print “ADDRESS = “, row[2]
print “SALARY = “, row[3], “\n”
conn.close();
Execute the following statement on command prompt:
python select.py
Leave a Reply