👋About this Course
Are you ready to take your Python programming skills to the next level? Whether you’re a beginner just starting out or an experienced programmer looking to improve your expertise, this course is designed to help you achieve your goals.
Throughout the course, we’ll cover everything you need to know to become proficient in Python programming. We’ll start with an introduction to Python and the basics of programming. From there, we’ll explore Python data types and the fundamentals of object-oriented programming (OOP), including classes, inheritance, and polymorphism.
As you progress through the course, you’ll master advanced Python concepts, including decorators, generators, and multithreading. We’ll also cover Python GUI programming using Tkinter, as well as networking with Python through sockets.
And that’s not all! We’ll update this course regularly with new sections and content, so you can continue to learn and grow your skills over time.
By the end of this course, you’ll have the knowledge and skills to build your own Python applications, work with Python libraries, and pursue a career in Python programming.
So what are you waiting for? Let’s get started on your Python programming journey today!
If you’re interested in staying updated on my latest projects, tutorials, and insights, follow me on social media! You can find me on Telegram (@securnerd), LinkedIn (@Codelivly), and Instagram (@securnerd).
Join me on this journey as we explore the world of Python programming together. Let’s get started!
💡What is Python?
In this section, we will provide a brief overview of what Python is, its history and background, its popularity and industry use cases, as well as its key features and advantages. By the end of this s
Python is a versatile and powerful programming language that has become increasingly popular in recent years. What sets Python apart from other languages is its simplicity, readability, and ease of use.
At its core, Python is a high-level programming language that is used to build a wide range of applications, from simple scripts to complex web applications and machine learning algorithms. Python’s syntax is designed to be simple and easy to read, making it accessible to developers of all skill levels.
History and Background of Python
Python has an intriguing history that dates back to the late 1980s. It was created by Guido van Rossum, a Dutch programmer, who named it after his favorite TV show, Monty Python’s Flying Circus. This quirky name was fitting for a language that was created to be fun and easy to learn.
Guido van Rossum started working on Python in December 1989 while working at the National Research Institute for Mathematics and Computer Science in the Netherlands. His goal was to create a new scripting language that was more powerful and easier to use than existing languages like Perl.
Python was first released in 1991 and quickly gained popularity among developers due to its easy-to-learn syntax and readability. In 1994, the first version of Python 1.0 was released, which included new features such as lambda, map, filter, and reduce. These features made it easier for developers to write complex programs in fewer lines of code.
Over the years, Python has continued to evolve and grow in popularity. In 2000, Python 2.0 was released, which included features like list comprehensions and a garbage collector. Python 3.0 was released in 2008, which included major changes to the language, such as removing deprecated features and improving Unicode support.
Today, Python is one of the most popular programming languages in the world, used for a wide range of applications, from web development to data analysis and machine learning. Its popularity is due in part to its ease of use and versatility, as well as its large community of developers who contribute to its development and support.
Python’s popularity and industry use cases
Python’s popularity has grown tremendously in recent years, and it is now one of the most widely used programming languages in the world. One of the main reasons for its popularity is its versatility, making it useful in a variety of industries and applications, including cybersecurity.
Python is widely used in cybersecurity due to its ease of use, flexibility, and availability of powerful libraries and frameworks. One popular use case of Python in cybersecurity is for penetration testing, where ethical hackers use Python scripts to identify vulnerabilities in computer systems and networks. The popular penetration testing framework, Metasploit, is written in Python.
Python is also used in the development of security tools and scripts, such as network scanners, intrusion detection systems, and password-cracking tools. Python libraries like Scapy, Nmap, and PyCrypto are commonly used in the development of these tools.
In the finance industry, Python is used for fraud detection and prevention. Financial institutions use Python to build fraud detection models that can identify and flag suspicious transactions in real time. Python libraries like Pandas and Scikit-learn are used for data preprocessing and machine learning algorithms for fraud detection.
Python is also popular in the gaming industry, where it is used to create game engines and develop game logic. Popular games like Civilization IV, Battlefield 2, and EVE Online have all been developed using Python.
The scientific research community also heavily relies on Python for data analysis and visualization. Scientists and researchers use Python to analyze data from experiments, visualize scientific data, and simulate complex systems.
In the web development industry, Python is used to develop web applications, frameworks, and content management systems. Popular web frameworks like Django and Flask are built using Python.
Python is also used in the education industry for teaching cybersecurity concepts to students. Many universities and schools have started teaching Python to students as part of their cybersecurity curriculum, due to its ease of use and accessibility.
Python’s versatility and powerful libraries and frameworks make it a top choice for cybersecurity professionals, developers, and organizations around the world. Its use cases in cybersecurity range from penetration testing to fraud detection and prevention and its popularity is only expected to continue growing.
Key features and advantages of Python
Python is a versatile and dynamic programming language that has been gaining popularity rapidly over the years. Here are some key features and advantages that make Python stand out from other programming languages:
- Simple and Easy to Learn: Python’s syntax is simple and easy to learn, making it accessible to beginners who want to learn programming. Its clean and readable code makes it easy for developers to understand and maintain.
- Large Standard Library: Python’s extensive standard library provides developers with a wide range of modules and functions, making it easier to write complex programs with fewer lines of code.
- Cross-Platform Compatibility: Python code can be run on multiple platforms like Windows, Linux, and macOS, without any modification.
- Dynamically Typed: Python is a dynamically typed language, meaning that variables don’t need to be declared before use. This makes Python more flexible and easier to use for certain types of applications.
- Strong Community Support: Python has a large and active community of developers who contribute to the language’s development, support, and documentation. This community-driven approach ensures that Python is always evolving and improving.
- Extensive Third-Party Libraries: Python has a vast ecosystem of third-party libraries and frameworks, such as NumPy, Pandas, and TensorFlow, that make it easier for developers to build complex applications.
- Interpreted Language: Python is an interpreted language, meaning that code is executed line-by-line by the interpreter. This makes it easier to debug and test code.
- Versatility: Python can be used for a wide range of applications, including web development, machine learning, data analysis, scientific computing, and more.
Whether you are a beginner or an experienced developer, Python is a great language to learn and use. With its simplicity, readability, and versatility, Python is sure to become an essential tool in your programming arsenal. So why not give it a try and see what amazing things you can build with Python?
😌Why Learn Python?
In this section, we will explore the many reasons why Python is a valuable skill to have in today’s job market. We will cover its wide range of use cases and applications, its versatility and ease …
Learning Python is a valuable investment in your personal and professional growth, providing you with a wide range of career opportunities and a powerful toolset for solving complex problems in various industries.
Career opportunities and job prospects
The demand for Python developers is on the rise, and there are abundant job opportunities available in various industries.
- High demand: Python is one of the most in-demand programming languages, with a growing number of job opportunities across various industries. According to Indeed, Python is the second-most in-demand programming language in the US, with over 70,000 job openings in 2021.
- Data Science and Machine Learning: Python is the go-to language for data science and machine learning, with a range of powerful libraries and frameworks like Pandas, NumPy, and TensorFlow. Python developers can work on projects like natural language processing, computer vision, and recommendation systems.
- Web Development: Python’s versatility makes it a popular choice for web development, with frameworks like Django and Flask. Python developers can build robust, scalable, and high-performance web applications.
- Automation: Python is widely used for automation, from simple tasks like file handling to complex tasks like web scraping and network automation. Python developers can automate repetitive tasks, freeing up time to focus on more complex projects.
- Robotics: Python is increasingly being used in robotics, with libraries like PyRobot and Robot Operating System (ROS). Python developers can work on projects like autonomous drones and robotic arms.
- Startups and Entrepreneurship: Python’s ease of use and versatility make it a popular choice for startups and entrepreneurs, who can quickly build and test MVPs (minimum viable products) with Python.
Use cases and applications of Python
From data science and machine learning to web development and automation, Python has a diverse range of applications that make it a powerful tool for solving complex problems.
- Data Science: Python is the go-to language for data science, with libraries like Pandas and NumPy for data manipulation and analysis, and Scikit-learn for machine learning. Python is used for tasks like data visualization, predictive modeling, and data mining.
- Web Development: Python is widely used for web development, with frameworks like Django and Flask. Python developers can build robust, scalable, and high-performance web applications.
- Automation: Python is a popular choice for automation, from simple tasks like file handling to complex tasks like web scraping and network automation. Python developers can automate repetitive tasks, freeing up time to focus on more complex projects.
- Scientific Computing: Python is used extensively in scientific computing, with libraries like SciPy and SymPy. Python developers can work on projects like numerical simulation, optimization, and symbolic math.
- Machine Learning: Python is widely used for machine learning, with libraries like TensorFlow and PyTorch. Python developers can work on projects like natural language processing, computer vision, and recommendation systems.
- Finance: Python is increasingly being used in finance, with libraries like Pandas and NumPy for data analysis and visualization, and libraries like Zipline for backtesting trading algorithms. Python developers can work on projects like portfolio optimization and risk management.
- Gaming: Python is used in the gaming industry for tasks like game development, scripting, and AI. Python developers can work on projects like game engines, bots, and simulations.
Versatility and ease of use
Python’s versatility and ease of use make it a popular choice for developers across various industries. Its simplicity, wide range of libraries, platform independence, and strong community support make it easier for developers to build complex projects quickly and efficiently.
- Easy to Learn: Python has a simple and concise syntax, making it easy for beginners to learn. Its readability and clean code make it a popular choice for teaching programming to beginners.
- Versatile: Python can be used for a variety of tasks, including web development, data analysis, automation, machine learning, scientific computing, and gaming. Its versatility makes it a popular choice for developers across various industries.
- Large Standard Library: Python has a large standard library that provides developers with a wide range of built-in functions and modules, making it easier to perform common tasks like file handling, string operations, and network programming.
- Third-Party Libraries: Python has a vast ecosystem of third-party libraries and frameworks that extend its functionality, including NumPy, Pandas, TensorFlow, Django, and Flask. These libraries make it easier for developers to build complex applications and projects.
- Platform-Independent: Python is platform-independent, meaning that code written on one platform (e.g., Windows) can be run on another platform (e.g., Linux) without any modifications. This makes it easier for developers to write cross-platform applications.
- Interpreted Language: Python is an interpreted language, meaning that it does not need to be compiled like other programming languages. This makes it easier and faster for developers to test and debug their code.
- Community Support: Python has a large and active community of developers who contribute to its development and support. This community provides resources like tutorials, documentation, and forums, making it easier for developers to learn and troubleshoot.
Community support and resources
Python’s strong community support and resources make it easier for developers to learn, use, and improve their Python skills. From online tutorials and forums to conferences and open-source libraries, there are many resources available for developers to get help and build exciting projects using Python.
- Large and Active Community: Python has a large and active community of developers who contribute to its development and support. The community includes contributors from various backgrounds and expertise, making it easier for developers to get help and advice on various aspects of Python.
- Tutorials and Documentation: Python has an extensive range of tutorials and documentation available for free online. These resources make it easier for developers to learn and use Python, with topics ranging from basic programming concepts to advanced libraries and frameworks.
- Online Forums and Communities: Python has many online forums and communities where developers can ask questions and get help from other developers. Some popular online communities include Stack Overflow, Reddit’s /r/learnpython, and Python’s official mailing lists.
- Conferences and Events: Python has numerous conferences and events held worldwide, where developers can network, learn, and share their knowledge and experiences. Some of the most popular Python conferences include PyCon US, EuroPython, and PyData.
- Open-Source Libraries and Frameworks: Python has a vast ecosystem of open-source libraries and frameworks developed by the community. These libraries and frameworks make it easier for developers to build complex projects quickly and efficiently, with popular examples including NumPy, Pandas, Django, and Flask.
- Online Courses and Bootcamps: Python has many online courses and bootcamps available for developers who want to learn Python or improve their skills. Some popular online course providers include Udemy, Coursera, and Codecademy.
🥰Python Installation and Setup
Ready to embark on your Python journey? The first step is to get the Python environment up and running on your computer. While this may seem daunting at first, fear not! Installing and setting up Python is a straightforward process that can be done in just a few simple steps. In this section, we will guide you through the process of installing and setting up Python on your machine, whether you’re using Windows, macOS, or Linux. By the end of this section, you’ll be ready to start writing your first Python program and exploring the vast world of Python programming.
Downloading and Installing Python
Before we can start writing Python code, we need to install the Python interpreter on our computer. Luckily, installing Python is a breeze! In this section, we’ll walk you through the process of downloading and installing Python on your machine. Whether you’re on Windows, macOS, or Linux, we’ve got you covered. Once you’ve completed the installation process, you’ll be ready to take your first steps into the world of Python programming.
a. Windows
Ready to dive into the world of Python programming on your Windows machine? Great! Here, we’ll take you through the process of downloading and installing Python on your Windows computer. So, buckle up, and let’s get started!
- Go to the official Python website at www.python.org/downloads.
- Click on the “Download Python” button.
- Scroll down and click on the “Windows” button to download the Windows installer.
- Once the download is complete, open the installer by double-clicking on the downloaded file (e.g. “python-3.10.0-amd64.exe”).
- In the Python installer, check the “Add Python 3.x to PATH” option. This will ensure that the Python interpreter and pip (Python’s package manager) are added to your system’s PATH variable, allowing you to easily run Python programs and install packages from the command prompt.
- Click “Install Now” to start the installation process.
- Wait for the installer to complete the installation. This may take a few minutes.
- Once the installation is complete, click on the “Close” button to exit the installer.
- To verify that Python is installed correctly, open the Command Prompt (Windows Key + R, then type “cmd” and hit enter) and type “python” followed by the Enter key. You should see the Python interpreter start up and print its version information.
- Congratulations! You’ve successfully installed Python on your Windows machine and are ready to start coding.
Note: The steps may vary slightly depending on the version of Python you are installing. Always refer to the official documentation for the specific version of Python you are installing.
b. macOS
Are you a proud owner of a shiny Mac computer? Then you’re in luck! Installing Python on macOS is a breeze. In this section, we’ll walk you through the process of downloading and installing Python on your Mac. By the end of this section, you’ll be ready to start writing Python code on your sleek and stylish machine.
- Go to the official Python website at www.python.org/downloads.
- Click on the “Download Python” button.
- Scroll down and click on the “macOS” button to download the macOS installer.
- Once the download is complete, open the downloaded file (e.g. “python-3.10.0-macosx10.9.pkg”) by double-clicking on it.
- In the installer, select “Install for all users” and enter your admin password when prompted.
- Click “Continue” and follow the instructions on the screen to complete the installation.
- Once the installation is complete, open the Terminal app (Applications > Utilities > Terminal).
- Type “python3” followed by the Enter key to start the Python interpreter. You should see the Python version information printed in the terminal.
- Congratulations! You’ve successfully installed Python on your Mac and are ready to start coding.
Note: The steps may vary slightly depending on the version of Python you are installing. Always refer to the official documentation for the specific version of Python you are installing.
c. Linux
Ah, Linux – the ultimate playground for software enthusiasts and developers. If you’re running Linux on your machine, you’re in for a treat – installing Python on Linux is a straightforward process. In this section, we’ll walk you through the steps to download and install Python on your Linux distribution. So, grab a cup of coffee, and let’s get started!”
- Open up your terminal application. This can usually be found in your Applications menu or by pressing Ctrl + Alt + T.
- In the terminal, type “sudo apt-get update” followed by the Enter key. This will update the package list on your system.
- Next, type “sudo apt-get install python3” followed by the Enter key. This will install Python 3, the latest version of Python, on your system.
- Wait for the installation to complete. This may take a few minutes.
- Once the installation is complete, type “python3” in the terminal followed by the Enter key to start the Python interpreter. You should see the Python version information printed in the terminal.
- Congratulations! You’ve successfully installed Python on your Linux machine and are ready to start coding.
As Mentioned Earlier always refer to the official documentation for the specific version of Python you are installing.
Setting Up the Python Development Environment
To start writing Python code, you need to set up your development environment. This includes installing an integrated development environment (IDE) or a text editor and configuring it to work with Python. Additionally, you’ll need to install packages and libraries that will help you write efficient and effective code. In this section, we’ll guide you through the necessary steps to set up your Python development environment, including installing an IDE or text editor, configuring it for Python, and setting up virtual environments. Let’s get started!
Installing an IDE (Integrated Development Environment)
An integrated development environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. In other words, it’s a one-stop shop for all your Python development needs. There are several IDEs available for Python, but we’ll focus on some of the most popular ones in this section.
We’ll guide you through the process of installing PyCharm and Visual Studio Code on your machine. These IDEs have unique features and functionalities that cater to different types of Python developers, so you can choose the one that best suits your needs.
Let’s get started with installing an IDE and taking your Python development experience to the next level!
a. PyCharm
PyCharm is one of the most popular IDEs for Python development. It is developed by JetBrains and provides developers with a comprehensive set of tools for code analysis, debugging, and testing. In this section, we’ll guide you through the process of installing PyCharm on your machine.
- First, go to the PyCharm website (https://www.jetbrains.com/pycharm/) and click on the ‘Download’ button for the Community Edition (which is free).
- Once the download is complete, double-click on the downloaded file to start the installation process.
- Follow the instructions in the installer to install PyCharm. You can choose to install PyCharm for all users or just for your user account.
- Once the installation is complete, launch PyCharm from your Applications folder (on macOS) or the Start menu (on Windows).
- When PyCharm opens, you’ll be prompted to create a new project. Choose a location for your project and select the Python interpreter that you want to use.
Congratulations, you’ve successfully installed PyCharm! Let’s see the installation of VS code
b. VS Code
Visual Studio Code is a popular free and open-source text editor that provides support for many programming languages, including Python. It has a user-friendly interface and a wide range of extensions and plugins that allow you to customize your development environment. In this section, we’ll guide you through the process of installing Visual Studio Code on your machine.
- First, go to the Visual Studio Code website (https://code.visualstudio.com/) and click on the ‘Download’ button for your operating system.
- Once the download is complete, double-click on the downloaded file to start the installation process.
- Follow the instructions in the installer to install Visual Studio Code. You can choose to install Visual Studio Code for all users or just for your user account.
- Once the installation is complete, launch Visual Studio Code from your Applications folder (on macOS) or the Start menu (on Windows).
Congratulations, you’ve successfully installed Visual Studio Code and configured it for Python development! Now it’s time to start writing some code.
Configuring the IDE for Python Development
a. PYcharm
PyCharm is a powerful IDE that provides a range of tools for Python development, including code completion, debugging, and testing. In this section, we’ll guide you through the process of configuring PyCharm for Python development.
- Open PyCharm and create a new project by clicking on ‘Create New Project’ on the welcome screen. Choose a name and location for your project.
- Once your project is created, PyCharm will prompt you to create a virtual environment. A virtual environment is a self-contained Python environment that allows you to install packages and dependencies for your project without affecting the global Python installation on your system. Click on ‘Create’ to create a new virtual environment.
- Next, you’ll need to configure the Python interpreter that you want to use for your project. Click on ‘File’ > ‘Settings’ (on Windows) or ‘PyCharm’ > ‘Preferences’ (on macOS) to open the settings window. Click on ‘Project: <your project name>’ > ‘Project Interpreter’.
- Click on the gear icon and choose ‘Add…’. Select ‘Virtualenv Environment’ and choose the virtual environment that you created in step 2.
- Once you’ve added your virtual environment, you can install packages and dependencies for your project using PyCharm’s package manager. To open the package manager, click on ‘File’ > ‘Settings’ (on Windows) or ‘PyCharm’ > ‘Preferences’ (on macOS) and choose ‘Project: <your project name>’ > ‘Project Interpreter’. Click on the ‘+’ icon to install new packages.
Congratulations, you’ve successfully configured PyCharm for Python development!
b. VS code
VS Code is a popular code editor that provides a range of tools for Python development, including code completion, debugging, and testing. In this section, we’ll guide you through the process of configuring VS Code for Python development.
- Install the Python extension for VS Code by opening the extensions panel (Ctrl+Shift+X on Windows or Cmd+Shift+X on macOS) and searching for ‘Python’. Click ‘Install’ to install the extension.
- Once the extension is installed, you can create a new Python file by clicking on ‘File’ > ‘New File’ and saving the file with a ‘.py’ extension.
- You’ll need to configure the Python interpreter that you want to use for your project. Click on the gear icon on the bottom left corner of the VS Code window and choose ‘Python: Select Interpreter’. If you have multiple Python installations on your system, choose the interpreter that you want to use for your project.
- You can now start writing Python code in VS Code. The Python extension provides a range of features to help you write code more efficiently, including code completion, linting, and debugging.
- To install packages and dependencies for your project, you can use the integrated terminal in VS Code. Open a terminal by clicking on ‘Terminal’ > ‘New Terminal’ and use the ‘pip’ command to install packages. For example, to install the ‘numpy’ package, you can run ‘pip install numpy’.
Congratulations, you’ve successfully configured VS Code for Python development!
Writing Your First Code
In the entire Project, We will be using VS code as our IDE. Now it’s time to start writing some code.
Absolutely! Now that you have installed and configured VS Code for Python development, you are ready to start writing some code. Here are the basic steps to get started:
- Open VS Code and create a new Python file by clicking on ‘File’ > ‘New File’ and saving the file with a ‘.py’ extension.
- Start writing your Python code in the file. For example, you can write a simple ‘Hello, World!’ program:
Copy
print('Hello, World!')
- Save the file by clicking on ‘File’ > ‘Save’ or using the keyboard shortcut (Ctrl+S on Windows or Cmd+S on macOS).
- To run the code, you can use the integrated terminal in VS Code. Open a terminal by clicking on ‘Terminal’ > ‘New Terminal’ and run the Python file by typing ‘python’ followed by the name of the file. For example, if your file is named ‘hello.py’, you can run it by typing:
Copy
python hello.py
- The output of your program will be displayed in the terminal.
Here, you have successfully written and executed your first Python program in VS Code! From here, you can continue to write more complex programs using the features provided by the Python extension, such as code completion, debugging, and testing.
Using the Command Line Interface (CLI)
The Command Line Interface (CLI) is another way to write and execute Python code and can be a useful tool for more advanced users or for running Python scripts in a server environment. Here are the basic steps for using the CLI:
- Open a command prompt or terminal on your computer.
- Navigate to the directory where your Python file is saved using the
cd
command. For example, if your file is saved in theDocuments
folder, you can navigate to that folder by typing:
Copy
cd Documents
- Once you are in the correct directory, you can execute your Python script by typing
python
followed by the name of the file. For example, if your file is namedmy_script.py
, you can execute it by typing:
Copy
python my_script.py
- The output of your program will be displayed in the command prompt or terminal.
Using the CLI can be a powerful way to run Python scripts, but it requires some basic knowledge of command-line operations. If you are new to using the command line, it may be helpful to start with the VS Code integrated terminal before moving on to the CLI.
Virtual Environments
Virtual environments are a way to create isolated Python environments for different projects, which can be useful for managing dependencies and avoiding conflicts between different packages. Here are the basic steps for setting up and using a virtual environment:
- Install the
virtualenv
package by running the commandpip install virtualenv
in your terminal or command prompt. - Create a new directory for your project, and navigate to that directory in your terminal or command prompt.
- Create a new virtual environment by running the command
virtualenv env
, whereenv
is the name of your environment. - Activate the virtual environment by running the command
source env/bin/activate
on Linux/MacOS, orenv\Scripts\activate
on Windows. - Once your virtual environment is activated, you can install any packages or dependencies you need using the
pip
command. These packages will be installed only in the virtual environment, and will not affect the global Python installation on your computer. - When you are done working on your project, you can deactivate the virtual environment by running the command
deactivate
.
Using virtual environments can help you manage dependencies more easily and avoid conflicts between different packages. It’s a good practice to use virtual environments for each new project you start and to keep your dependencies organized and up-to-date.
😨Basic Syntax
Python syntax refers to the rules and conventions that govern how Python code is written and interpreted. These rules determine how code should be structured, what characters can be used to represent different types of data, how statements and expressions should be organized, and so on.
Understanding and following Python syntax is essential for writing effective, efficient, and readable code. Properly structured code makes it easier to understand and debug, helps prevent errors and bugs, and can improve code performance.
Python syntax includes rules for naming variables, defining functions and classes, using indentation to denote code blocks, and using various keywords and operators to perform specific actions.
By following Python syntax guidelines and best practices, programmers can write efficient, well-structured code that is easy to understand and maintain.
First Python Program
To create a Python program, you can use any text editor such as Notepad, Notepad++, Sublime Text, or any Python IDE (Integrated Development Environment) like PyCharm, Spyder, or Jupyter Notebook.
Here’s an example of a simple Python program that prints “Hello, World!” on the screen:
print("Hello, World!")
To run this program, save it with a .py
extension, and then execute the following command in the terminal or command prompt:
python hello_world.py
This will run the Python interpreter and execute the code in the file. The output will be:
Hello, World!
This is a very basic example, but it demonstrates the basic structure of a Python program. The print()
function is used to output text to the console, and the code is executed line by line, from top to bottom.
Example: Python Statements
an example of Python statements:
# This is a comment
# Assigning values to variables
x = 5
y = 10
# Performing arithmetic operations
z = x + y
print(z)
# Using conditional statements
if z > 10:
print("Z is greater than 10")
else:
print("Z is less than or equal to 10")
# Defining a function
def greet(name):
print("Hello, " + name + "!")
# Calling the function
greet("John")
In this example, we assign values to variables x
and y
, perform arithmetic operations to calculate z
, use a conditional statement to determine whether z
is greater than 10, define a function greet
that takes a parameter name
and prints a greeting message, and finally calls the greet
function with an argument "John"
.
Example: Multiple Statements in a Single Line
In Python, it is possible to write multiple statements in a single line using a semicolon (;) to separate them. However, it is generally not recommended as it can make the code less readable.
print('Hello \
World!') # a multi-line statement
Hello World!
print('Hello') \
print(' World!') # two statement in one logical line
SyntaxError: invalid syntax
As mentioned earlier, while it is possible to write multiple statements in a single line like this, it is generally not recommended as it can make the code harder to read and understand. It is better to write each statement on a separate line.
Indentation in Python
In Python, indentation is used to indicate a block of code. Unlike other programming languages that use braces or other symbols to define blocks of code, Python uses indentation to group statements into blocks. The amount of indentation must be consistent within a block, and typically four spaces are used for each level of indentation.
For example, in the following code snippet, the block of code inside the if statement is indented:
x = 10
if x > 5:
print("x is greater than 5")
If the indentation is not correct, Python will raise an IndentationError. It is important to be consistent with indentation throughout the entire program.
Python Syntax Identifiers
In Python, an identifier is a name given to a variable, function, class, module, or any other object. It is used to uniquely identify an object in the program.
Some rules for naming identifiers in Python are:
- The first character of the identifier must be a letter or an underscore (_).
- The rest of the characters in the identifier can be letters, numbers, or underscores.
- Identifiers are case-sensitive.
- Reserved words or keywords cannot be used as identifiers.
- The length of the identifier is not restricted.
Here are some examples of valid and invalid identifiers in Python:
Valid Identifiers:
- variable_name
- _underscore
- ClassName
- function_name_2
Invalid Identifiers:
- 2variable (cannot start with a number)
- class (reserved keyword)
- my-function (cannot contain hyphens)
- if (reserved keyword)
😳Comments
In Python, comments are used to explain the code and make it more understandable to other programmers. Comments can be added to a single line or multiple lines of code. They are ignored by the Python interpreter during runtime and are only meant to be read by humans.
To add a single-line comment, use the hash (#) symbol followed by the comment. For example:Copy
# This is a single-line comment
To add a multi-line comment, use triple quotes (”’) to enclose the comment. For example:Copy
'''
This is a multi-line comment.
It can span across multiple lines.
'''
It’s good practice to add comments to your code, especially when working on large projects with other programmers. They can help explain what the code is doing, why it’s doing it, and any potential issues or edge cases to be aware of.
😛Variables
In programming, a variable is a container (storage area) to hold data. For example:
code = 21
Here, code is the variable storing the value 21.
In Python, variables are used to store data values that can be used in our program. A variable is a container that holds a value, such as a number or a string. The value stored in a variable can be changed or updated during the execution of the program.
Creating a Variable:
In Python, variables can be created simply by assigning a value to a name. For example, to create a variable called x
and assign it the value of 5, we can do the following:
x = 5
Variable Naming Rules:
When creating variables in Python, there are some rules to follow. Here are some guidelines to keep in mind:
- Variable names must start with a letter or underscore (_).
- Variable names can only contain letters, numbers, and underscores (_).
- Variable names are case-sensitive.
- Variable names should be descriptive and not too long.
Assigning Values to Variables:
In Python, we can assign values to variables using the assignment operator (=). For example:
pythonCopy codex = 5
y = "Hello, world!"
We can also assign multiple variables at once, separating them with commas:
pythonCopy codex, y, z = 1, 2, 3
Variable Data Types:
In Python, variables can hold values of different data types, such as numbers, strings, lists, tuples, and more. The type of a variable is determined by the value assigned to it.
pythonCopy codex = 5 # integer
y = 3.14 # float
z = "Hello" # string
a = [1, 2, 3] # list
b = (4, 5, 6) # tuple
c = {"name": "John", "age": 30} # dictionary
Variable Scope:
In Python, variables have a scope, which refers to the part of the program where the variable is accessible. Variables can have either a global scope or a local scope. A global variable is accessible throughout the entire program, while a local variable is only accessible within a specific function or block of code.
x = 5 # global variable
def my_function():
y = 3 # local variable
print(x) # global variable accessible within function
print(y) # local variable accessible within function
my_function()
print(x) # global variable accessible outside function
print(y) # error - local variable not accessible outside function
Variables are an essential concept in Python programming, allowing us to store and manipulate data values. Understanding how to create, name, assign values to, and access variables will be crucial in building more complex Python programs.
😺Keywords and Identifiers
In Python, keywords and identifiers are used to define and manipulate variables, functions, and other programming elements.
Python Keywords
Keywords in Python are predefined reserved words that have specific meanings and purposes. These words cannot be used as variable or function names because they have a special meaning in the Python language.
Python Keywords List
False | await | else | import | pass |
---|---|---|---|---|
None | break | except | in | raise |
True | class | finally | is | return |
and | continue | for | lambda | try |
as | def | from | nonlocal | while |
assert | del | global | not | with |
async | elif | if | or | yield |
It is important to remember that these keywords have a specific meaning in Python and cannot be used as variable or function names.
Python Identifiers
In Python, an identifier is a name given to a variable, function, class, module, or other object. An identifier can be made up of letters, digits, and underscores (_), and must begin with either a letter or an underscore. Identifiers are case-sensitive, which means that my_variable
and My_Variable
are different identifiers.
Here are some examples of valid identifiers in Python:
x
my_var
My_Var
myVar
my_var_1
_my_var
Here are some examples of invalid identifiers:
2myvar (starts with a digit)
my-var (contains a hyphen)
my var (contains a space)
my@var (contains a special character)
It’s important to choose meaningful and descriptive names for your identifiers, to make your code more readable and understandable.
Rules for Naming an Identifier
- The first character of an identifier must be a letter or an underscore (_).
- The rest of the identifier can contain letters, digits, and underscores.
- Identifiers are case-sensitive, which means that
my_variable
andMy_Variable
are different identifiers. - Python keywords cannot be used as identifiers.
- Identifiers should be descriptive and meaningful, to make your code more readable and understandable.
- Identifiers cannot start with a digit.
Following these rules will help ensure that your identifiers are valid and easy to understand.
Some Valid and Invalid Identifiers in Python
Valid Identifiers:
- my_variable
- MY_VARIABLE
- _my_variable
- my_variable_1
- myVariable
- var_1
Invalid Identifiers:
- 1_variable (starts with a digit)
- my-variable (contains a dash, which is not allowed)
- import (a Python keyword)
- break (a Python keyword)
- while (a Python keyword)
- my variable (contains a space, which is not allowed)
It’s important to follow the rules for naming identifiers in Python to avoid errors in your code.
☺️Input and Output
In this tutorial, we will learn simple ways to display output to users and take input from users in Python with the help of examples
In Python, you can take input from the user using the input()
function and output data using the print()
function. These are the two most commonly used functions for basic input and output operations in Python.
Python input()
input()
function is a built-in function in Python that reads a line from the user and returns it as a string.
Syntax:
Copy
input([prompt])
The input()
the function takes one optional parameter prompt
, which is a string that is displayed to the user before they enter the input.
Parameters:
prompt
(optional): A string that is displayed to the user before they enter the input. If this parameter is not provided, the function waits for the user to input any value.
Return Value:
The input()
function returns the user input as a string.
Here is an example of using the input()
function:
name = input("What is your name? ")
print("Hello, " + name + "!")
In this example, the input()
function prompts the user to enter their name, which is stored in the name
variable. The print()
function then outputs a personalized greeting to the user.
Note that the value returned by input()
is always a string, so if you need to perform numeric operations on the input, you must convert it to the appropriate data type (e.g. using the int()
or float()
functions).Copy
age = int(input("What is your age? "))
print("You will be " + str(age + 10) + " in 10 years.")
In this example, the input()
function prompts the user to enter their age, which is converted to an integer using the int()
function. The program then adds 10 to the user’s age and prints the result as a string using the str()
function.
Example 1: Python Print Statement
Here’s an example of the Python print()
statement:
# Simple print statement
print("Hello, World!")
# Print with a variable
message = "Welcome to Python Programming!"
print(message)
# Print with multiple values
name = "John"
age = 25
print("My name is", name, "and I am", age, "years old.")
Output:
Hello, World!
Welcome to Python Programming!
My name is John and I am 25 years old.
Python Output
In Python, the print()
function is used to output values to the console. The print()
function can take one or more values separated by commas as arguments, which it then outputs to the console.
Here’s an example:
print("Hello, world!")
This code will output Hello, world!
to the console. You can also pass in multiple values to print()
by separating them with commas:
name = "Alice"
age = 25
print("My name is", name, "and I am", age, "years old.")
This code will output My name is Alice and I am 25 years old.
to the console.
You can also use escape sequences to format the output. For example, to output a newline character, use the escape sequence:
print("First line\nSecond line")
This code will output:
First line
Second line
There are many other escape sequences you can use, such as for a tab character and \\
to output a backslash. You can also use string formatting to format the output in a more structured way.
Syntax of print()
The syntax of the print()
function in Python is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
objects
: zero or more objects to be printed.sep
: separator between the objects. It is optional, and the default value is a single-space character' '
.end
: end string after the last object is printed. It is also optional, and the default value is a newline character'\n'
.file
: the object where the printed output will be sent. It is optional, and the default value is the standard outputsys.stdout
.flush
: a boolean value indicating whether to flush the stream. It is optional, and the default value isFalse
.
The print()
function can take multiple arguments separated by a comma and print them one after the other. The values can be of any data type, including strings, numbers, and variables.
For example:
print("Hello, World!")
print(42)
print("My name is", "John", "Doe")
Output:
Hello, World!
42
My name is John Doe
Output formatting
Output formatting refers to how the output of a program is presented to the user. In Python, the built-in print()
function allows you to format the output in various ways.
One way to format output is by using string formatting. Python provides a number of ways to format strings, such as using the %
operator, the format()
method, and f-strings.
Another way to format output is by using escape characters. Escape characters are special characters that allow you to include non-printable characters in your output, such as newlines, tabs, and backslashes.
Here’s an example of using string formatting with the %
operator:
name = "John"
age = 30
print("My name is %s and I am %d years old." % (name, age))
Output:
My name is John and I am 30 years old.
And here’s an example of using f-strings:
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
Output:
My name is John and I am 30 years old.
You can also use escape characters to format your output. For example, you can use to insert a newline character, to insert a tab character, and \\
to insert a backslash:
print("First line\nSecond line")
print("Tabbed\toutput")
print("Backslash \\")
Output:
First line
Second line
Tabbed output
Backslash \
Output formatting can make your program’s output more readable and easier to understand, especially when dealing with large amounts of data.
😶Operators
Python operators are the symbols that allow us to perform different types of operations on variables and values. They are the building blocks of any programming language, and Python is no exception. Python provides a wide range of operators that can be used to perform arithmetic, logical, comparison, assignment, and bitwise operations.
Understanding the different types of operators is crucial to writing efficient and error-free code in Python. In this section, we will explore the different types of operators available in Python and learn how to use them effectively in our programs. So buckle up and get ready to dive into the world of Python operators!
I. Arithmetic Operators
Arithmetic operators are used in Python to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and more. These operators are used on numeric data types such as integers, floats, and complex numbers.
Python provides the following arithmetic operators:
Operator | Name | Example | Result |
---|---|---|---|
+ | Addition | 2 + 3 | 5 |
– | Subtraction | 5 – 2 | 3 |
* | Multiplication | 3 * 4 | 12 |
/ | Division | 10 / 2 | 5 |
% | Modulus | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
// | Floor Division | 10 // 3 | 3 |
The floor division (//) operator returns the largest integer that is less than or equal to the division result.
a. Addition
Addition is one of the most basic arithmetic operations in Python. It is denoted by the +
symbol and is used to add two numbers or concatenate two strings. For example, if we want to add two numbers x
and y
together, we can use the +
an operator like this:
x = 5
y = 3
sum = x + y
print(sum) # Output: 8
Similarly, if we want to concatenate two strings a
and b
, we can use the +
an operator like this:
a = "Hello"
b = "World"
concatenation = a + " " + b
print(concatenation) # Output: Hello World
In both cases, the +
an operator performs the desired operation and returns a new value that we can assign to a variable or use directly.
b. Subtraction
The subtraction operator (-) is used to subtract one value from another. It takes two operands and returns the difference between them. For example, 5 - 3
will return 2, and 10.5 - 3.2
will return 7.3.
In Python, the subtraction operator can also be used with variables. For example:
a = 5
b = 3
c = a - b
print(c) # Output: 2
Note that the subtraction operator can also be used with negative numbers. For example, 5 - (-3)
will return 8.
c. Multiplication
Multiplication is a mathematical operation that is represented by the symbol *
in Python. It is used to find the product of two or more values. Here’s an example:
a = 10
b = 5
c = a * b
print(c) # Output: 50
In the above example, we have two variables a
and b
with values 10
and 5
respectively. We multiply these two variables using the *
operator and store the result in the variable c
. Finally, we print the value of c
which is 50
(the product of a
and b
).
d. Division
In Python, the /
an operator is used for division. It returns the quotient (result of division) in the form of a float, even if both the operands are integers. If you want to get the quotient as an integer, you can use the //
operator, which performs floor division.
Here’s an example:
a = 10
b = 3
# Floating point division
c = a / b
print(c) # Output: 3.3333333333333335
# Integer division
d = a // b
print(d) # Output: 3
In the example above, we divide a
by b
using both the /
and //
operators. The result of the floating point division is stored in c
, which is a float, while the result of the integer division is stored in d
, which is an integer.
d. Modulus
The modulus operator returns the remainder of the division operation between two operands. It is represented by the percentage sign %
.
For example, the expression 9 % 4
returns 1
because when 9 is divided by 4, the remainder is 1.
Here is an example code snippet:
a = 9
b = 4
result = a % b
print(result)
Output:
1
e. Exponentiation
Exponentiation is another arithmetic operator in Python represented by the double asterisk symbol (**). It raises the first operand to the power of the second operand.
Syntax:
base ** exponent
Here, the base
is the first operand, and the exponent
is the second operand.
Example:
2 ** 3 # Output: 8
In the above example, 2 is raised to the power of 3, which results in 8.
f. Floor Division
Floor Division operator in Python is represented by two forward slashes //
and it returns the quotient of the division operation rounding down to the nearest integer. For example, the floor division of 7 // 3
would be 2
since 3
goes into 7
two whole times with 1
left over.
Here’s an example of using a floor division operator:
a = 10
b = 3
result = a // b
print(result) # output: 3
In the above example, we have defined two variables a
and b
, and then used floor division operator //
to divide a
by b
. Since a
is 10
and b
is 3
, the result of a // b
is 3
.
II. Comparison Operators
Comparison operators, also known as relational operators, are used to compare two values or operands. In Python, comparison operators always return a boolean value – either True or False.
There are six comparison operators in Python:
- Equal to (==)
- Not equal to (!=)
- Greater than (>)
- Less than (<)
- Greater than or equal to (>=)
- Less than or equal to (<=)
These operators are used in conditional statements and loops to test whether a certain condition is true or false.
a. Equal to (==)
The equal to an operator (==
) is a comparison operator used to compare the equality of two operands. It returns True
if the values of the two operands are equal, otherwise, it returns False
.
Here’s an example:
x = 5
y = 10
z = 5
print(x == y) # False
print(x == z) # True
In this example, the first comparison returns False
because x
is not equal to y
. The second comparison returns True
because x
is equal to z
.
b. Not equal to (!=)
In Python, the “not equal to” operator is represented by the exclamation mark followed by an equal sign (!=). It is a binary operator and is used to compare two values. The operator returns True
if the values are not equal and False
if they are equal.
Here’s an example of using the “not equal to” operator in Python:
x = 10
y = 5
if x != y:
print("x is not equal to y")
else:
print("x is equal to y")
Output:
vbnetCopy codex is not equal to y
c. Greater than (>)
The greater than operator (>
) is used to check if the left operand is greater than the right operand. It returns True
if the left operand is greater than the right operand, otherwise, it returns False
. Here is an example:
x = 5
y = 3
print(x > y) # Output: True
In the example above, x
is greater than y
, so the expression x > y
returns True
.
d. Less than (<)
In Python, the less-than-operator <
is used to compare two operands. It returns True
if the left operand is less than the right operand, and False
otherwise.
Here’s an example:
x = 5
y = 10
if x < y:
print("x is less than y")
else:
print("x is not less than y")
Output:Copy
x is less than y
In this example, x
is less than y
, so the if
statement evaluates to True
, and the first print statement is executed.
e. Greater than or equal to (>=)
The greater than or equal to an operator (>=) is used to compare two values. It returns True if the left operand is greater than or equal to the right operand, and False otherwise.
For example:
honx = 5
y = 3
print(x >= y) # Output: True
print(y >= x) # Output: False
In this example, the first print statement returns True because x
(which is 5) is greater than or equal to y
(which is 3). The second print statement returns False because y
is less than x
.
f. Less than or equal to (<=)
The “Less than or equal to” operator is represented by the symbol “<=”. It is used to check if one value is less than or equal to another value.
For example, in the expression “5 <= 10”, the operator “<=” checks if 5 is less than or equal to 10. Since this is true, the expression evaluates to True. However, in the expression “10 <= 5”, the operator “<=” checks if 10 is less than or equal to 5. Since this is false, the expression evaluates to False.
Here’s an example code snippet demonstrating the use of the “<=” operator:
x = 5
y = 10
if x <= y:
print("x is less than or equal to y")
else:
print("x is greater than y")
This code will output “x is less than or equal to y”, since 5 is indeed less than or equal to 10.
III. Logical Operators
Python Logical Operators are used to combine two or more conditions and perform logical operations on them. The following are the three logical operators in Python:
- and
- or
- not
These operators are used to perform logical operations on the operands and return a Boolean value.
- The ‘and’ operator returns True if both operands are True, otherwise, it returns False.
- The ‘or’ operator returns True if either of the operands is True, otherwise, it returns False.
- The ‘not’ operator returns the opposite of the operand.
Let’s look at depth with some examples to understand how these operators work.
a. AND
The and
operator returns True if both operands are true and returns False if either one of the operands is false.
Here’s the truth table for the and
operator:
Operand 1 | Operand 2 | Result |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Here’s an example code snippet:
x = 5
y = 10
z = 15
if x < y and x < z:
print("x is the smallest number")
In this example, the and
operator is used to check if x
is smaller than both y
and z
. If this condition is true, then the statement “x is the smallest number” is printed.
b. OR
The OR operator in Python is represented by or
. It is a logical operator that returns True
if at least one of the operands is True
, and False
otherwise. Here are the possible truth tables for the OR operator:
Operand 1 | Operand 2 | Result |
---|---|---|
False | False | False |
False | True | True |
True | False | True |
True | True | True |
Here’s an example of using the OR operator in Python:
x = 5
y = 10
z = 15
if x > y or x > z:
print("x is greater than y or z")
else:
print("x is not greater than y or z")
In this example, x
is not greater than y
or z
, so the output will be x is not greater than y or z
.
c. NOT
The NOT operator is a unary operator that negates the value of its operand. In Python, the NOT operator is represented by the keyword “not”.
The NOT operator returns True if its operand is False, and vice versa. Here’s an example:
x = True
print(not x) # Output: False
In this example, the value of x
is True. However, the NOT operator negates the value of x
and returns False.
IV. Assignment Operators
Have you ever wanted to quickly assign or modify a value in Python without writing a lot of code? That’s where assignment operators come in handy! They allow you to perform an operation on a variable and assign the result back to the same variable in a single step. In this section, we will explore the different types of assignment operators in Python.
a. Simple Assignment Operator
The simple assignment operator in Python is denoted by the equal sign “=” and is used to assign a value to a variable. The syntax for simple assignments is:
variable = value
where variable
is the name of the variable and value
is the value to be assigned to the variable.
For example, the following code assigns the value 10
to the variable x
:
x = 10
After executing this code, the variable x
will have the value 10
.
b. Arithmetic Assignment Operators
Arithmetic assignment operators are a shorthand way of performing arithmetic operations and assignments at the same time. These operators include:
+=
: adds the value of the right operand to the value of the left operand and assigns the result to the left operand.-=
: subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.*=
: multiplies the value of the left operand by the value of the right operand and assigns the result to the left operand./=
: divides the value of the left operand by the value of the right operand and assigns the result to the left operand.%=
: computes the modulus of the value of the left operand and the value of the right operand, and assigns the result to the left operand.//=
: performs floor division on the value of the left operand and the value of the right operand, and assigns the result to the left operand.**=
: raises the value of the left operand to the power of the value of the right operand, and assigns the result to the left operand.
These operators can be used with numeric values and variables of numeric types, such as integers and floating-point numbers.
Example:
x = 10
x += 5 # equivalent to x = x + 5
print(x) # Output: 15
y = 7
y *= 3 # equivalent to y = y * 3
print(y) # Output: 21
z = 8
z //= 3 # equivalent to z = z // 3
print(z) # Output: 2
In each of the above examples, the arithmetic operation and the assignment operation are performed at the same time using the shorthand arithmetic assignment operator.
c. Bitwise Assignment Operators
Bitwise assignment operators are used to perform a bitwise operation on a variable and then assign the result to the same variable. The bitwise assignment operators include:
&=
: Performs a bitwise AND operation on the variable and the value on the right, then assigns the result to the variable.|=
: Performs a bitwise OR operation on the variable and the value on the right, then assigns the result to the variable.^=
: Performs a bitwise XOR operation on the variable and the value on the right, then assigns the result to the variable.<<=
: Performs a left shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.>>=
: Performs a right shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.
d. Logical Assignment Operators
There are no specific “Logical Assignment Operators” in Python, as the logical operators and
, or
, and not
are already used for combining and negating boolean expressions. However, it is possible to use logical operators in combination with assignment operators to create compound expressions, such as x += y or z
, which assigns the value of y
to x
if y
is truthy, or the value of z
otherwise.
e. Comparison Assignment Operators
There is no such thing as “Comparison Assignment Operators”. The term “comparison operator” refers to operators that compare two values and return a boolean value (True or False), while “assignment operator” refers to operators that assign a value to a variable.
However, there are shorthand ways to perform a comparison and assign the result to a variable in a single line of code. For example:
x = 10 if a > b else 20
: This assigns the value 10 tox
ifa > b
is True, otherwise it assigns the value 20.x += 1 if a == b else 2
: This adds 1 tox
ifa == b
is True, otherwise, it adds 2.x *= 2 if a < b else 3
: This multipliesx
by 2 ifa < b
is True, otherwise, it multiplies it by 3.
V. Bitwise Operators
Bitwise operators are used to manipulate the individual bits of binary numbers. In Python, bitwise operators can be applied to integers. The bitwise operators take two operands and operate on them bit by bit to produce a result. There are six bitwise operators in Python: AND, OR, XOR, NOT, left shift, and right shift. These operators are commonly used in low-level programming, such as device driver development and network packet processing.
a. Bitwise AND
The bitwise AND operator is represented by the &
symbol in Python. It performs a logical AND operation on each corresponding bit of its operands. If both bits are 1, the resulting bit is 1. Otherwise, the resulting bit is 0.
For example:
a = 10 # binary representation: 1010
b = 6 # binary representation: 0110
c = a & b # binary representation: 0010 (decimal value: 2)
In this example, a
and b
are two integers represented in binary. The &
operator is used to perform a bitwise AND operation on the two numbers, resulting in the binary number 0010
, which is equivalent to the decimal number 2. The resulting value is assigned to the variable c
.
b. Bitwise OR
Bitwise OR is another binary operator that operates on two integers and performs a bitwise OR operation on their binary representations. The resulting binary representation is converted back to an integer.
The syntax for the bitwise OR operator is the pipe symbol |
. For example, a | b
performs a bitwise OR operation on a
and b
.
Here’s an example:
a = 60 # binary representation: 0011 1100
b = 13 # binary representation: 0000 1101
c = a | b # binary representation: 0011 1101
print(c) # output: 61
In the above example, the binary OR operation on a
and b
results in 0011 1101
, which is equal to 61 in decimal representation.
c. Bitwise XOR
Bitwise XOR (exclusive OR) operator is represented by the symbol ^
in Python. The operator returns a binary number that has a 1 in each bit position where the corresponding bits of either but not both operands are 1.
For example, let’s say we have two variables a = 13
and b = 17
. The binary representation of 13 is 1101
and the binary representation of 17 is 10001
. Now, let’s perform the bitwise XOR operation on these two variables:
a = 13 # binary representation: 1101
b = 17 # binary representation: 10001
c = a ^ b # binary representation: 11000
In the above example, the resulting binary number is 11000
, which is equivalent to the decimal number 24
. Therefore, the value of the variable c
will be 24
.
Here is another example that demonstrates the use of bitwise XOR:Copy
a = 0b1010 # decimal representation: 10
b = 0b1100 # decimal representation: 12
c = a ^ b # decimal representation: 6
In this example, we first define a
and b
as binary numbers using the 0b
prefix. We then perform the bitwise XOR operation on these two numbers and store the result in c
. The resulting binary number is 0b110
, which is equivalent to the decimal number 6
. Therefore, the value of the variable c
will be 6
.
d. Bitwise NOT
Bitwise NOT is a unary operator in Python that flips the bits of a number. It is represented by the tilde (~) symbol. When applied to a binary number, the Bitwise NOT operator returns the complement of the number.
For example:
x = 7 # Binary: 0000 0111
y = ~x # Binary: 1111 1000
print(bin(y)) # Output: -0b1000 (in two's complement form)
In the above code, the value of x
is 7, which is represented in binary as 0000 0111. When we apply the Bitwise NOT operator (~) to x
, it flips all the bits of the number, resulting in 1111 1000. The output is in two’s complement form, which is the way negative numbers are represented in binary.
VI. Membership Operators
Membership operators are used to test if a sequence is present in an object. In Python, we have two membership operators:
in
: Evaluates to True if the sequence is present in the object.not in
: Evaluates to True if the sequence is not present in the object.
These operators are typically used with strings, lists, tuples, and sets to check if a certain element or a sequence of elements is present in them.
For example:
fruits = ['apple', 'banana', 'orange']
if 'apple' in fruits:
print('Yes, apple is in the list')
else:
print('No, apple is not in the list')
if 'watermelon' not in fruits:
print('Yes, watermelon is not in the list')
else:
print('No, watermelon is in the list')
Output:
Yes, apple is in the list
Yes, watermelon is not in the list
VII. Identity Operators
Identity Operators are used to compare the memory locations of two objects. There are two identity operators in Python:
is
– ReturnsTrue
if both variables are the same object.is not
– ReturnsTrue
if both variables are not the same object.
For example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # True because x and z are the same object
print(x is y) # False because x and y are not the same object
print(x == y) # True because the values of x and y are the same
print(x is not z) # False because x and z are the same object
print(x is not y) # True because x and y are not the same object
In this example, x
and y
have the same values, but they are not the same object. z
is assigned the same memory location as x
, so x
and z
are the same object. The is
operator returns True
when comparing x
and z
, but False
when comparing x
and y
. The is not
operator returns False
when comparing x
and z
, but True
when comparing x
and y
.
✨Flow Control
In this section, we will discuss various aspects of Python flow control, including conditional statements, loops, and function calls. We will explore how to use these tools to control the flow of …
Python Flow Control refers to the order in which the code is executed in a program. It is used to control the execution of statements and allows the program to execute different code blocks based on certain conditions. In Python, flow control is achieved using conditional statements, loops, and function calls. Understanding flow control is essential for writing efficient and effective programs.
1. Python if…else Statement
The if…else statement is one of the most commonly used control structures in Python. It allows you to execute a block of code based on a condition. The condition is evaluated to be either True or False, and the code block is executed only if the condition is True. If the condition is False, the code block is skipped or another block of code is executed instead. This provides a way to control the flow of execution in a Python program.
In Python, there are three forms of the if...else
statement.
if
statementif...else
statementif...elif...else
statement
a. Python if statement
In Python, the if
statement is used to perform a certain action only when a certain condition is true. It allows us to control the flow of the program based on the evaluation of an expression that returns a Boolean value (True
or False
). If the expression is true, then the code inside the if
block will be executed, otherwise, the code inside the if
block will be skipped.
Here’s the general syntax of the if
statement:
if expression:
statement(s)
The expression
is a condition that is evaluated and returns a Boolean value (True
or False
). The statement(s)
that follow the if
block is executed only if the expression
is evaluated to True
.
For example, let’s say we want to print a message if a number is greater than 5. We can use the if
statement as follows:
num = 8
if num > 5:
print("The number is greater than 5")
In this example, if the value of the variable num
is greater than 5, then the message “The number is greater than 5” will be printed. Otherwise, nothing will be printed.
b. Python if…else Statement
The if...else
statement in Python allows you to execute a block of code if a certain condition is met and a different block of code if that condition is not met. It is a fundamental part of programming and can be used to make decisions and control the flow of your program.
The basic syntax for the if...else
statement in Python is as follows:
if condition:
# code to be executed if condition is True
else:
# code to be executed if condition is False
In this statement, the condition
is evaluated as either True
or False
. If it is True
, the block of code indented under the if
a statement is executed. If it is False
, the block of code indented under the else
a statement is executed instead.
The if...else
statement evaluates the given condition
:
- the code inside
if
is executed - the code inside
else
is skipped
If the condition evaluates to False
,
- the code inside
else
is executed - the code inside
if
is skipped
Here’s an example of a Python if…else statement:
num = int(input("Enter a number: "))
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
In this example, the user is prompted to enter a number. The number is then checked to see if it’s even or odd using the modulus operator (%). If the number is even (i.e., its remainder when divided by 2 is 0), the program prints a message saying so. Otherwise, it prints a message saying the number is odd. The if
a statement is followed by the else
statement, which is executed if the condition in the if
statement is False
.
c. Python if…elif…else Statement
The Python if…elif…else statement is used when we need to test multiple conditions and execute a different block of code depending on which condition is true. The elif stands for “else if”, and allows us to check additional conditions if the first condition is not met. The else statement is executed if none of the if or elif conditions are true.
The basic syntax of the if…elif…else statement in Python is:
if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition2 is true
elif condition3:
# code to execute if condition3 is true
else:
# code to execute if none of the conditions are true
Note that you can have any number of elif statements, depending on how many conditions you need to check. Also note that the else statement is optional.
Here is an Example Python if…elif…else Statement
number = 0
if number > 0:
print("Positive number")
elif number == 0:
print('Zero')
else:
print('Negative number')
print('This statement is always executed')
OutputCopy
Zero
This statement is always executed
In the above example, we have created a variable named number with the value 0. Here, we have two condition expressions:
Here, both the conditions evaluate to False
. Hence the statement inside the body of else
is executed.
2. Python for Loop
In Python, a for loop is a control flow statement that is used to iterate over a sequence of elements. It allows you to execute a block of code repeatedly for a specific number of times or for each element in a sequence. The for loop is commonly used for tasks like iterating over a list, string, tuple, or range of numbers. In this section, we will explore the different ways you can use a for loop in Python.
The syntax of the for
loop is:
for val in sequence:
# statement(s)
Here, val
accesses each item of the sequence on each iteration. Loop continues until we reach the last item in the sequence.
a. Using a for Loop with a Sequence
In Python, the for
loop is used to iterate over a sequence of elements. The sequence can be a string, a list, a tuple, or any other iterable object. The basic syntax for a for
loop is as follows:
for element in sequence:
# code block to be executed
The loop iterates through each element in the sequence and executes the code block. The loop continues until all the elements in the sequence have been processed.
Let’s take a look at an example of using a for
loop with a list of numbers:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
In this example, the for
loop iterates through each number in the list numbers
and prints it to the console. The output would be:
1
2
3
4
5
The loop stops when it reaches the end of the list, which is after processing the number 5.
Note that the loop variable (num
in this example) takes on the value of each element in the sequence in turn, and the code block is executed once for each value of the loop variable.
b. Using the range() Function in for Loops
The range()
function in Python generates a sequence of numbers. It can be used in for loops to iterate a certain number of times.
The basic syntax of the range()
function is:
range(start, stop, step)
Here,
start
(optional) is the starting value of the sequence. The default value is 0.stop
is the ending value of the sequence (exclusive).step
(optional) is the difference between each number in the sequence. The default value is 1.
Let’s see some examples of using range()
in for loops.
- Printing the numbers from 0 to 9:
Copy
for i in range(10):
print(i)
- Printing the even numbers from 0 to 10:
Copy
for i in range(0, 11, 2):
print(i)
- Printing the numbers from 10 to 1:
Copy
for i in range(10, 0, -1):
print(i)
- Summing up the numbers from 1 to 10:
Copy
total = 0
for i in range(1, 11):
total += i
print(total)
These are just a few examples, but you can use the range() function in many different ways to generate the sequence of values that you need for your loop.
c. Nested for Loops
In Python, it is possible to have a for loop inside another for loop. This is called a nested for loop. The inner loop will be executed completely for each iteration of the outer loop.
The syntax for a nested for loop is as follows:
for outer_var in outer_sequence:
# execute outer loop code here
for inner_var in inner_sequence:
# execute inner loop code here
Here, outer_sequence
is the sequence for the outer loop and inner_sequence
is the sequence for the inner loop.
Let’s see an example of a nested for loop that prints out the multiplication table from 1 to 10:Copy
for i in range(1, 11):
for j in range(1, 11):
print(i * j, end='\t')
print()
In this example, the outer loop iterates over the numbers from 1 to 10, and for each iteration, the inner loop iterates over the numbers from 1 to 10 and prints out the product of i
and j
. The end='\t'
argument in the print statement is used to separate the numbers with tabs instead of newlines. Finally, a new line is printed after each iteration of the inner loop to move to the next row of the multiplication table.
c. Using the break and continue Statements in for Loops
In Python, the break
and continue
statements can be used inside for loops to control the flow of execution.
The break
statement is used to exit a loop early, regardless of whether the loop has finished iterating over all of its elements. When the break
statement is encountered inside a loop, the loop is terminated immediately and program execution continues with the next statement after the loop.
The continue
statement is used to skip to the next iteration of a loop, without executing any remaining statements in the current iteration. When the continue
statement is encountered inside a loop, the loop immediately skips to the next iteration, without executing any remaining statements in the current iteration.
Let’s see some examples of using break
and continue
in for loops.
Example 1: Using break statement
fruits = ["apple", "banana", "cherry", "kiwi", "orange"]
for fruit in fruits:
if fruit == "cherry":
break
print(fruit)
Output:
apple
banana
In this example, the break
statement is used to exit the loop when the variable fruit
takes the value "cherry"
. The loop terminates at that point, and the remaining fruits "kiwi"
and "orange"
are not printed.
Example 2: Using continue statement
fruits = ["apple", "banana", "cherry", "kiwi", "orange"]
for fruit in fruits:
if fruit == "cherry":
continue
print(fruit)
Output:
apple
banana
kiwi
orange
In this example, the continue
statement is used to skip the "cherry"
fruit, and the remaining fruits "apple"
, "banana"
, "kiwi"
, and "orange"
are printed.
These are just some basic examples of how to use break
and continue
statements in for loops. Depending on the specific use case, you may need to use more complex logic in combination with these statements to achieve the desired behavior.
3. Python while Loop
A while loop in Python repeatedly executes a block of code as long as a certain condition is true. The loop continues until the condition becomes false.
The syntax of a while loop in Python is as follows:Copy
while condition:
# code to execute while condition is true
The code inside the while loop will keep executing as long as the condition is true. When the condition becomes false, the loop exits and control moves to the next statement after the while loop.
It’s important to make sure that the condition inside the while loop will eventually become false, otherwise, the loop will run infinitely and the program will become unresponsive.
Here’s an example of a while loop in Python:
# Using a while loop to print numbers 1 to 5
count = 1
while count <= 5:
print(count)
count += 1
This code will output:
1
2
3
4
5
In this example, the while loop is used to print the numbers 1 to 5. The loop starts with count
variable initialized to 1. The loop continues to execute as long as the value of count
is less than or equal to 5. Inside the loop, the value of count
is printed to the console, and then count
is incremented by 1 using the +=
operator. This process continues until the value of count
is greater than 5, at which point the loop exits.
a. Using a while Loop with the break and continue Statements
In addition to the basic while loop structure, we can also use the break
and continue
statements to control the flow of the loop.
The break
statement is used to exit a loop prematurely, regardless of the loop’s condition. For example:
i = 0
while i < 5:
print(i)
if i == 3:
break
i += 1
Output:
0
1
2
3
In the example above, the break
statement is used to exit the loop when i
is equal to 3, so the loop only runs 4 times instead of 5.
On the other hand, the continue
statement is used to skip over a specific iteration of the loop and move on to the next one. For example:
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
In the example above, the continue
statement is used to skip over the iteration where i
is equal to 3, so it is not printed in the output.
b. Using the else Statement with a while Loop
The else
statement can also be used with a while
loop in Python. It is executed when the loop condition becomes false. This means that the code inside the else
block will be executed after the while
loop has completed all of its iterations.
Here is an example:
i = 1
while i <= 5:
print(i)
i += 1
else:
print("Loop is finished")
In this example, the while
loop will iterate five times and print the values of i
from 1 to 5. After the loop finishes, the else
block will be executed and it will print the message “Loop is finished”.
If the while
loop is terminated prematurely by a break
statement, the else
block will not be executed.
Here’s an example that demonstrates this:
i = 1
while i <= 5:
if i == 3:
break
print(i)
i += 1
else:
print("Loop is finished")
In this example, the while
loop will iterate three times and print the values of i
from 1 to 2. When i
becomes 3, the break
the statement is executed, which terminates the loop prematurely. Since the loop was terminated by a break
statement, the else
a block is not executed.
4. Python break and continue
In Python, the break
and continue
statements are used to alter the normal flow of a loop.
- The
break
statement is used to terminate the loop entirely and continue with the next statement after the loop. - The
continue
statement is used to skip the current iteration of the loop and move on to the next iteration.
a. Python break Statement
The break
statement in Python is used to terminate the execution of a loop (for loop, while loop) prematurely. When a break
statement is encountered inside a loop, the loop is exited and the control is transferred to the next statement following the loop.
Here’s the basic syntax of a break
statement:
while condition:
# some code
if some_condition:
break
# some more code
In the above example, the break
statement is used to exit the while loop prematurely when the condition some_condition
is satisfied.
Similarly, the break
statement can also be used inside a for loop:
for variable in sequence:
# some code
if some_condition:
break
# some more code
In the above example, the break
statement is used to exit the for loop prematurely when the condition some_condition
is satisfied.
b. Python continues Statement
The continue
statement is another flow control statement in Python that is used inside loops (for loop or while loop). It is used to skip over a part of the loop’s code block for a specific condition and then continue with the next iteration of the loop.
When the continue
a statement is encountered inside the loop, the code execution jumps back to the beginning of the loop’s code block and starts the next iteration, ignoring the remaining code in the current iteration.
Here is the syntax for the continue
statement:
while/for condition:
# code block
if condition:
continue
# more code
As shown in the example above, the continue
statement is usually used inside a conditional statement (if statement) to check for a specific condition. When the condition is met, the continue
a statement is executed, and the code inside the current iteration of the loop is skipped, and the next iteration starts.
4. Python pass Statement
The pass
statement in Python is used as a placeholder where a statement is required syntactically, but no action is required. It is commonly used as a placeholder while writing code to indicate that some part of the code will be implemented later. The pass
statement is a null operation, meaning it does nothing.
For example, if you are defining a function, and you have not yet written the body of the function, you can use the pass
statement as a placeholder, so that the function definition is syntactically correct:
def my_function():
pass
In this example, the function my_function()
does not do anything, but the pass
statement allows the function to be defined syntactically.
Another example is using pass
in a loop when you want to do nothing for a certain condition:
for i in range(10):
if i % 2 == 0:
pass
else:
print(i)
In this example, the pass
a statement is used when i
is an even number, so nothing is done. The else
a statement is only executed when i
is an odd number, so i
is printed.
a. Using pass With Conditional Statement
The pass
statement in Python is a placeholder that does nothing. It is used to avoid syntax errors when a statement is required syntactically, but you don’t want any command or code to execute.
When used with conditional statements, pass
allows you to create a valid empty block of code. This can be useful when you are not yet sure what code to put inside the block.
Here’s an example of using pass
with a conditional statement:
x = 10
if x < 5:
pass
else:
print("x is greater than or equal to 5")
In this example, if the value of x
is less than 5, the pass
statement will be executed and the program will move on to the next line of code. If the value of x
is greater than or equal to 5, the else
block will be executed and the message “x is greater than or equal to 5” will be printed.
b. Use of pass Statement inside Function or Class
The pass
statement is often used as a placeholder for a block of code that is not yet implemented, but needs to be added later. It is commonly used in situations where the syntax requires a statement, but no action is required.
In functions or classes, the pass
statement can be used as a placeholder for the body of the function or class definition. This can be useful when you want to define the structure of the function or class, but have not yet written the code to implement it.
Here is an example of using the pass
statement inside a function:
def my_function():
pass
In this example, my_function()
is defined with the pass
statement as the function body. This function does nothing when called, but it can be useful as a placeholder for a function that will be defined later.
Similarly, the pass
statement can be used inside a class definition:
class MyClass:
pass
In this example, MyClass
is defined by the pass
statement as the class body. This class does nothing, but it can be useful as a placeholder for a class that will be defined later.
🤲Functions
In this section, we will cover the basics of Python functions. Knowing how to use functions is essential for writing efficient and reusable code…
A function is a block of code that performs a specific task. It is like a subprogram that can be called from the main program. Functions take input arguments, perform operations, and return output values. Python provides several built-in functions, and we can also define our own functions to perform custom operations.
Benefits of Using Functions
There are several benefits of using functions in programming, including:
- Code Reusability: Functions allow us to reuse code by defining a block of code that can be called multiple times from different parts of the program.
- Modularity: Functions break down complex tasks into smaller, more manageable units, making the code more organized and easier to maintain.
- Abstraction: Functions provide an abstraction layer that hides the complexity of the code and makes it easier to use.
- Debugging: Functions make it easier to isolate and fix errors in code, making debugging a more straightforward process.
Types of function
There are two types of functions in Python programming:
- Standard library functions – These are built-in functions in Python that are available to use.
- User-defined functions – We can create our functions based on our requirements.
Defining and Calling Functions
Defining and calling functions is a fundamental concept in Python programming. Functions enable us to organize code into reusable blocks, which makes our programs easier to read, debug, and maintain. In this section, we will explore the process of defining and calling functions in Python.
Defining Functions
Defining a function in Python means creating a function object that maps the function name to the function.
a. Syntax
The syntax for defining a function in Python is:
def function_name(parameters):
"""docstring"""
statement(s)
Where:
def
the keyword is used to define a function.function_name
is the name of the function. It should follow the same naming rules as for the identifiers.parameters
are the input arguments to the function. They are optional.docstring
is an optional documentation string that describes what the function does. It is enclosed within triple quotes.statement(s)
are the statements that are executed when the function is called. They should be indented with four spaces.
For example:
def greet(name):
"""This function greets the person passed in as parameter"""
print("Hello, " + name + ". How are you doing?")
Here, greet
is the name of the function, name
is the input parameter, and the print()
statement is executed when the function is called.
b. Parameters
Function parameters are the inputs that a function can accept. Parameters allow us to pass values or data to a function, which the function can then use to perform certain operations. In Python, function parameters are defined within the parentheses following the function name. There are two types of parameters:
- Positional parameters: These are mandatory parameters that are passed to a function in a specific order. The number of positional parameters should match the number of arguments passed to the function.
- Keyword parameters: These are optional parameters that can be passed to a function with a specific keyword. They have default values assigned to them, which are used when no value is passed for them during a function call.
For example:
def greet(name, message="Hello"):
print(message + ", " + name)
In this example, name
is a positional parameter and message
is a keyword parameter with a default value of “Hello”. We can call this function using either positional or keyword arguments:
greet("John") # prints "Hello, John"
greet("Jane", "Hi") # prints "Hi, Jane"
greet(message="Hi", name="Alice") # prints "Hi, Alice"
Note that when using keyword parameters, the order in which they are passed does not matter, as long as their keywords match the parameter names in the function definition.
c. Return Values
In Python, functions can return values using the return
statement. The return
statement can be followed by a value or an expression that is evaluated to return the value. The general syntax for returning values from a function is as follows:
def function_name(parameters):
# function body
return value
Here, the return
statement is used to return the value to the calling function. The value can be of any data type, such as an integer, float, string, or even a list, dictionary, or tuple.
When a function returns a value, it can be assigned to a variable, used in an expression, or printed to the console using the print()
function.
For example, the following function calculates the sum of two numbers and returns the result:
def sum_numbers(a, b):
result = a + b
return result
The function can be called and the returned value can be printed to the console using the following code:
result = sum_numbers(10, 20)
print(result)
This will output 30
to the console, which is the result of adding 10
and 20
.
Examples
Here’s an example of a function that takes two parameters and returns their sum:
def add_numbers(a, b):
sum = a + b
return sum
In this example, we define a function called add_numbers
that takes two parameters a
and b
. The function then calculates their sum and returns the result using the return
keyword. Once the function is defined, we can call it and pass in arguments to the parameters:
result = add_numbers(5, 7)
print(result) # Output: 12
In this example, we call the add_numbers
function and pass in the values 5
and 7
as arguments to its parameters a
and b
. The function then calculates the sum of these two values and returns 12
. Finally, we assign the return value of the function to a variable called result
and print it to the console.
Calling Functions
After defining a function, you can call it to perform a specific task or operation. When a function is called, the code inside the function’s block gets executed, and the function may return a value if specified.
a. Syntax
The syntax for calling a function is:
function_name(argument1, argument2, ...)
Here, function_name
is the name of the function that you want to call and argument1
, argument2
, and so on, are the arguments that you want to pass to the function. If the function doesn’t take any arguments, you can simply call it using the following syntax:
function_name()
This will call the function with no arguments.
b. Positional Arguments
Positional arguments are the most common type of arguments passed to a function in Python. In this type of argument passing, the arguments are matched based on their position in the function call. The first argument in the function call is matched with the first parameter in the function definition, the second argument with the second parameter, and so on.
For example, let’s say we have a function called add_numbers
that takes two arguments, num1
and num2
, and returns their sum:
def add_numbers(num1, num2):
return num1 + num2
To call this function, we can pass two values as positional arguments:
result = add_numbers(5, 10)
print(result) # Output: 15
In this example, the first argument 5
is matched with the first parameter num1
, and the second argument 10
is matched with the second parameter num2
. The function returns their sum 15
, which is then printed to the console.
c. Keyword Arguments
Keyword arguments are arguments passed to a function that are preceded by the name of the parameter to which they correspond. In this case, the order in which the arguments are passed doesn’t matter, as long as each argument is assigned to the correct parameter.
Here is an example of a function call with keyword arguments:
def greet(name, message):
print(f"{message}, {name}!")
greet(message="Hello", name="Rocky")
Output:
Hello, Rocky!
In the example above, we pass the arguments message
and name
to the function greet
using the syntax parameter_name=value
. This allows us to pass arguments out of order without any confusion and makes our code more readable.
d. Default Values
When defining a function, you can specify default values for some or all of the parameters. These default values will be used when the function is called without passing any values for those parameters.
Here’s an example:
def greet(name, greeting='Hello'):
print(greeting + ', ' + name)
greet('Alice') # prints "Hello, Alice"
greet('Bob', 'Hi') # prints "Hi, Bob"
In the example above, greeting
is an optional parameter with a default value of 'Hello'
. When we call greet('Alice')
, the function uses the default value for greeting
and prints “Hello, Alice”. When we call greet('Bob', 'Hi')
, the function uses the value 'Hi'
for greeting
and prints “Hi, Bob”.
Examples
# Defining a function to calculate the sum of two numbers
def add_numbers(num1, num2):
sum = num1 + num2
return sum
# Calling the function with positional arguments
result1 = add_numbers(5, 10)
print("Result 1:", result1)
# Calling the function with keyword arguments
result2 = add_numbers(num1=7, num2=3)
print("Result 2:", result2)
# Calling the function with one argument and using the default value for the other
result3 = add_numbers(num1=2)
print("Result 3:", result3)
Output:
Result 1: 15
Result 2: 10
Result 3: TypeError: add_numbers() missing 1 required positional argument: 'num2'
In this example, we defined a function add_numbers()
that takes two parameters and returns their sum. We then called the function three times with different combinations of arguments:
- The first call uses positional arguments to pass
5
and10
as the values fornum1
andnum2
, respectively. - The second call uses keyword arguments to pass
7
and3
tonum1
andnum2
, respectively. - The third call only passes a value for
num1
, which uses the default value of0
fornum2
. However, this call results in aTypeError
because the function requires two arguments and we only provided one.
Function Arguments
Functions are an essential aspect of Python programming. They allow us to create blocks of code that can be reused throughout our code, which makes our code more efficient, modular, and easier to maintain. In Python, we can define functions that accept arguments to take input values and use them to perform some tasks.
There are several types of function arguments in Python, and we will explore them in detail. We will learn how to define functions with arguments and how to call them with different types of arguments, including positional arguments, keyword arguments, and default arguments.
Positional Arguments
When it comes to passing arguments to a function, positional arguments are one of the most commonly used methods in Python. As the name suggests, these arguments are passed based on their position or order, from left to right, in the function call.
In other words, the first argument passed in the function call corresponds to the first parameter defined in the function definition, the second argument corresponds to the second parameter, and so on. Positional arguments are useful when you want to pass a fixed number of arguments to a function, and the order in which they are passed is important.
Let’s take an example of a function that calculates the area of a rectangle using its length and breadth as arguments. The length and breadth will be our positional arguments, and their order will be important.
def calculate_area(length, breadth):
area = length * breadth
return area
# Calling the function with positional arguments
result = calculate_area(5, 6)
print("The area of the rectangle is:", result)
In this example, we define a function called calculate_area
that takes two positional arguments: length
and breadth
. We then call the function and pass the values 5
and 6
as arguments, respectively. These values are assigned to length
and breadth
in the function definition, and the area of the rectangle is calculated using the formula area = length * breadth
. Finally, the calculated area is returned and printed to the console.
Keyword Arguments
When calling a function, the values for the parameters can be passed by specifying the parameter names, rather than relying on their positions. These are called keyword arguments. Using keyword arguments can make the function call more readable and easier to understand, especially when dealing with functions that have many parameters.
Keyword arguments are particularly useful when the function has default parameter values. By using keyword arguments, you can selectively override the default values for only the parameters that need to be changed.
For example, let’s consider a function that calculates the volume of a rectangular prism, which has three parameters: length, width, and height. We can use keyword arguments to specify the values for these parameters, like this:
def calculate_volume(length, width, height):
return length * width * height
# calling the function with keyword arguments
volume = calculate_volume(length=3, width=4, height=5)
Here, we’ve specified the values for the length, width, and height parameters using keyword arguments. This makes the function call more readable, and we can easily see what values we’re passing in.
Using keyword arguments can also make the function call more robust to changes in the function signature. If we add or remove a parameter from the function, the function call will still work as long as the parameter names remain the same. This is in contrast to positional arguments, where adding or removing a parameter can break the function call if the argument positions are not adjusted accordingly.
Default Arguments
Have you ever found yourself repeatedly passing the same argument to a function while calling it? In Python, you can avoid that repetition by setting default values for function arguments. In this way, if an argument is not specified while calling the function, it takes the default value that was defined in the function definition. This feature is known as default arguments. Default arguments are used to provide a default value to a function parameter in case a value is not provided when the function is called. This makes it easier to write functions that can handle different input values without requiring the user to provide a value for every parameter.
Syntax
To specify a default value for a parameter, you simply include an equal sign and the default value after the parameter name in the function definition. For example:
def greet(name, message="Hello"):
print(message, name)
In this example, the message
parameter has a default value of "Hello"
. If the user does not provide a value for message
when they call the greet
function, it will default to "Hello"
. If the user does provide a value for message
, that value will be used instead.
Example
Copy
def greet(name, message="Hello"):
print(message, name)
greet("John") # prints "Hello John"
greet("Jane", "Hi there") # prints "Hi there Jane"
In this example, we define a function greet
that takes two parameters: name
and message
. If the user does not provide a value for message
, it defaults to "Hello"
. We then call the greet
function twice, once with only a value for name
, and once with values for both name
and message
. The function uses the default value of "Hello"
for message
in the first call, and the user-provided value of "Hi there"
in the second call.
Variable-Length Arguments (Arbitrary Arguments)
Variable-length arguments, also known as arbitrary arguments, allow a function to accept any number of arguments. In Python, there are two types of variable-length arguments: *args and **kwargs.
args is used to pass a variable number of non-keyword arguments to a function. It is represented by an asterisk () before the parameter name in the function definition. The function treats the arguments as a tuple.
kwargs is used to pass a variable number of keyword arguments to a function. It is represented by two asterisks () before the parameter name in the function definition. The function treats the arguments as a dictionary.
Using variable-length arguments makes the function more flexible, as it allows the user to pass any number of arguments without having to change the function definition.
Here is an example of a function that accepts variable-length arguments:
def print_args(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
print_args(1, 2, 3, a=4, b=5)
Output:
Positional arguments: (1, 2, 3)
Keyword arguments: {'a': 4, 'b': 5}
In this example, the print_args() function accepts both positional arguments (1, 2, 3) and keyword arguments (a=4, b=5). The function then prints the positional arguments as a tuple and the keyword arguments as a dictionary.
Note that the order of the parameter names does not matter, but *args must come before **kwargs in the function definition.
Keyword Variable-Length Arguments.
Keyword variable-length arguments, also known as kwargs, allow you to pass a variable number of keyword arguments to a function. This means you can pass any number of arguments to a function, as long as they are all named.
The syntax for defining kwargs uses two asterisks (**) before the parameter name. Within the function, kwargs are treated as dictionaries, with the keyword argument names as keys and their corresponding values as values.
Kwargs are especially useful when you want to create a function with a lot of optional arguments, as it allows you to pass them in a flexible manner without having to define all possible argument combinations in the function definition.
Here’s an example of using kwargs in a function definition:
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
In this example, the print_kwargs
function takes any number of keyword arguments and prints them out in the format key: value
.
Here’s how you can call the print_kwargs
function with kwargs:
print_kwargs(name="Rocky", age=30, location="New York")
This will output:
name: Rocky
age: 30
location: New York
As you can see, the kwargs are passed as keyword arguments, with the argument name followed by the value. The function then prints out each key-value pair in the kwargs dictionary.
Anonymous Functions (Lambda Functions)
Lambda functions, also known as anonymous functions, are functions without a name. These functions are small and typically used when you need to pass a function as an argument to another function. Lambda functions are defined using the keyword “lambda” and can take any number of arguments, but can only have one expression.
Lambda functions are often used with built-in functions such as filter(), map(), and reduce(). They are also commonly used in functional programming paradigms.
The syntax of a lambda function is:
lambda arguments: expression
Here, “arguments” are the parameters that the lambda function will accept and “expression” is the operation that the function will perform.
Let’s take an example to understand it better:
# Define a lambda function to add two numbers
add_numbers = lambda x, y: x + y
# Call the lambda function
result = add_numbers(10, 20)
# Print the result
print(result)
In the example above, we defined a lambda function that takes two arguments and adds them together. We then called the lambda function with arguments 10 and 20 and stored the result in the variable “result”. Finally, we printed the result, which is 30.
Lambda functions are a powerful tool in Python programming, but it’s important to use them wisely and only when necessary.
Return Statement
The return statement is a fundamental concept in Python functions. It is used to return a value or an expression from a function to the calling program. When a return statement is encountered in a function, it immediately terminates the execution of the function and returns the specified value to the calling program.
The return statement in Python can be used with or without a value. If you don’t specify a value after the return keyword, it returns None by default.
In Python, a function can return multiple values separated by commas. When multiple values are returned, they are packed into a tuple.
Example:
def sum_and_difference(a, b):
sum = a + b
difference = a - b
return sum, difference
result = sum_and_difference(10, 5)
print(result) # Output: (15, 5)
In the example above, the sum_and_difference
function returns two values: the sum and the difference of the two input arguments. The function is called with the arguments 10
and 5
, and the returned values are assigned to the variable result
. The print statement outputs the tuple containing the two returned values.
It’s important to note that the return statement can only be used within a function. If you try to use it outside of a function, you will get a syntax error.
Global and Local Variables
Global and local variables are an essential aspect of programming in any language, and Python is no exception. In Python, a variable’s scope determines where the variable can be accessed within the code. There are two types of variables in Python – global variables and local variables.
Global variables are the variables that are declared outside a function or a block of code, and they can be accessed from anywhere within the code. Local variables, on the other hand, are declared inside a function or a block of code and can only be accessed within that block.
When a variable is declared inside a function, it is by default considered to be a local variable. If we want to use the same variable name globally, we can use the ‘global’ keyword to indicate that the variable is a global variable.
a. Global variable
In Python, a variable defined outside a function is a global variable. Global variables are accessible from any part of the code, including inside functions. However, if a function tries to modify a global variable, it must first declare the variable as global using the global
keyword. Otherwise, the function will create a new local variable with the same name as the global variable, which will have no effect on the original global variable.
Here’s an example:
x = 10 # global variable
def my_func():
global x
x += 5 # modifies the global variable
print(x) # prints 15
my_func()
print(x) # prints 15
In this example, we have a global variable x
with a value of 10. The function my_func()
modifies the value of x
by adding 5 to it and then prints the new value. When we call the function, it prints 15. After the function call, we print the value of x
again, which is still 15 because we modified the global variable inside the function.
Without the global
keyword, the function would create a new local variable x
that has no relation to the global variable x
:
x = 10 # global variable
def my_func():
x = 5 # creates a new local variable x
print(x) # prints 5
my_func()
print(x) # prints 10
In this example, the function my_func()
creates a new local variable x
with a value of 5. When we call the function, it prints the local variable, which is 5. After the function call, we print the value of the global variable x
, which is still 10 and was not affected by the function call.
b. Local variables
In Python, a variable defined inside a function has local scope, which means it can only be accessed inside that function. Local variables can be defined with the same name as a global variable, but they are entirely different variables.
Here’s an example:
x = 5 # global variable
def my_function():
x = 3 # local variable with the same name as global variable
print("Local variable x:", x)
my_function()
print("Global variable x:", x)
Output:
Local variable x: 3
Global variable x: 5
In the example above, x
is a global variable with a value of 5. Inside the my_function
function, a local variable named x
is defined with a value of 3. When the function is called, the local variable x
is printed, which outputs 3
. After the function call, the global variable x
is printed, which outputs 5
.
It’s important to note that a local variable cannot be accessed outside of the function in which it is defined. If you try to access a local variable outside of its function, a NameError
will occur.
Recursion
Recursion is a programming technique where a function calls itself repeatedly until a specific condition is met. In Python, as in many other programming languages, recursion is a powerful tool that can be used to solve complex problems.
The basic idea behind recursion is to break down a problem into smaller subproblems that are easier to solve, and then combine the results to solve the original problem. Recursive functions have a few key components:
- Base case: The simplest form of the problem that can be solved directly without recursion.
- Recursive case: The problem is broken down into smaller subproblems that are solved recursively until the base case is reached.
Recursion can be used to solve a wide variety of problems, such as traversing complex data structures like trees and graphs, searching for patterns in data, and generating fractal images. However, it’s important to use recursion judiciously, since it can be computationally expensive and lead to stack overflow errors if not used properly.
Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
This is a function that calculates the factorial of a number using recursion. The base case is when n
is equal to 1, and the function simply returns 1. Otherwise, it calculates n
times the factorial of n-1
, which is done by calling the function recursively.
For example, factorial(5)
would return 120
because 5 x 4 x 3 x 2 x 1 = 120.
Function Decorators
Function decorators are a way to add extra functionality to existing functions in Python. Decorators allow you to modify or extend the behavior of a function without changing its source code. They are a powerful tool for code reuse and can help you write more efficient and maintainable code.
In Python, a decorator is a special type of function that takes another function as its argument and returns a new function with some additional functionality. The syntax for using decorators is simply to place the decorator function name above the function definition you want to decorate.
Here’s an example of a simple decorator that adds a timer to a function:
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Elapsed time: {end_time - start_time:.2f} seconds")
return result
return wrapper
@timer
def my_function():
time.sleep(1)
return "Hello, World!"
my_function()
In this example, the timer
a function is a decorator that takes another function func
as an argument. It defines a new function wrapper
that wraps the original function func
with the timer functionality. The wrapper
function uses the time
module to measure the elapsed time of the original function, then prints the elapsed time to the console.
The @timer
decorator syntax is used to decorate the my_function
function with the timer
decorator. When my_function
is called, it is actually the decorated wrapper
a function that gets executed. The wrapper
function calls the original my_function
and returns its result, while also printing the elapsed time.
Function decorators can be used for a variety of purposes, such as caching, logging, authentication, and more. They are a powerful and flexible tool for extending the functionality of your Python code.
PYTHON DATA TYPES
😇Introduction
Just like in the real world, where everything has a specific type – be it a person, animal, or object, programming languages have data types that help to define the nature of the values used in the code.
Python, being a dynamically-typed language, allows us to define variables without specifying their data type. However, it is essential to understand the various data types in Python and how to work with them efficiently.
In this section, we’ll explore the different data types in Python, how to declare them, and how to perform operations on them. So, fasten your seatbelts and get ready to dive into the world of Python data types!
Types Of Data Types
In Python, there are several types of data types that we can use to store and manipulate different kinds of data. Here are some of the most common types of data types in Python:
- Numeric Data Types: These include integers, floating-point numbers, and complex numbers.
- String Data Type: Strings are used to represent a sequence of characters. They are immutable, which means that once they are created, their contents cannot be changed.
- Boolean Data Type: This type of data can only have two possible values – True or False.
- List Data Type: Lists are used to store a collection of items. They are mutable, which means that you can add, remove, or modify items in a list.
- Tuple Data Type: Tuples are similar to lists, but they are immutable, which means that you cannot modify them once they are created.
- Set Data Type: Sets are used to store a collection of unique items. They are mutable, which means that you can add or remove items from a set.
- Dictionary Data Type: Dictionaries are used to store key-value pairs. They are mutable, which means that you can add, remove, or modify items in a dictionary.
Understanding these data types is essential in programming with Python.
🔢Numeric Data Types
Numeric data types are used to represent numbers in Python. There are three main numeric data types in Python:
- Integer: Integers are whole numbers without any decimal points. They can be positive, negative, or zero. In Python, integers are represented by the int class.
- Float: Floats are numbers with decimal points or scientific notation. They can also be positive, negative, or zero. In Python, floats are represented by the float class.
- Complex: Complex numbers are numbers with a real and imaginary part. They are represented in the form of a + bj, where a and b are floats, and j is the square root of -1. In Python, complex numbers are represented by the complex class.
Numeric data types are used in various mathematical operations such as addition, subtraction, multiplication, division, and more. They are also used in scientific calculations and statistical analysis.
a. Integer
In Python, the integer data type represents positive or negative whole numbers without any decimal points. Integers are a common and basic type of data used in programming.
In Python, integers have unlimited precision, meaning that they can be as large or small as necessary without any overflow errors.
To assign an integer value to a variable in Python, simply use the equal sign (=) followed by the desired value.
Example:
# Assigning an integer value to a variable
x = 5
# Printing the value of the variable
print(x) # Output: 5
In Python, the type() function can be used to determine the data type of a variable. To check if a variable is of integer type, we can use the isinstance() function.
Example:
# Checking the data type of a variable
x = 5
print(type(x)) # Output: <class 'int'>
# Checking if a variable is of integer type
print(isinstance(x, int)) # Output: True
b. Float
A float is a numeric data type in Python that represents floating-point numbers. Floating-point numbers are numbers with a decimal point, and they can be positive or negative. Floats are commonly used in scientific and engineering applications where precise decimal calculations are required.
In Python, you can create a float by simply including a decimal point in a number. For example:Copy
x = 3.14
y = -2.5
You can also use the float() function to convert other data types to a float. For example:Copy
x = float(5)
y = float("3.14")
One important thing to note about float is that they are not always represented exactly due to the limitations of binary arithmetic. This can sometimes lead to unexpected results in calculations involving floats. To avoid such issues, you can use the decimal module in Python for more precise decimal calculations.
c. Complex
In Python, complex numbers are represented by a combination of a real and an imaginary part, both of which are represented by floating-point numbers. The imaginary part is denoted by a suffix ‘j’ or ‘J’.
Here’s an example of a complex number in Python:
z = 3 + 2j
print(z)
Output:
(3+2j)
In the example above, the variable z
is a complex number with a real part of 3
and an imaginary part of 2
. The output is displayed in parentheses, with the imaginary part followed by a ‘j’.
😸List
Python offers several built-in data structures to hold and manipulate data efficiently. One such data structure is a list, which is a collection of items stored in a specific order. A list is mutable, which means it can be changed after it is created.
In Python, lists are created by enclosing a comma-separated sequence of items in square brackets ([]), as shown below:
my_list = [1, 2, 3, 'apple', 'banana', 'cherry']
In this example, the list contains three integers and three strings. The order of the items in the list is preserved.
Lists are very versatile and can hold any type of data, including other lists. They also support various operations, such as indexing, slicing, adding, removing, and sorting elements.
In this section, we will discuss the properties and operations of Python lists in more detail.
Create a Python List
To create a Python list, you can use square brackets []
and separate the values with commas. Here is an example:
my_list = [1, 2, 3, "apple", "banana"]
This creates a list with integers 1
, 2
, and 3
, as well as the strings "apple"
and "banana"
. You can also create an empty list like this:
empty_list = []
Or create a list with a single value:
single_value_list = [42]
Access Python List Elements
To access the elements of a Python list, you can use the indexing operator []
. The index of the first element in a list is 0
, the second element has an index of 1
, and so on. You can also use negative indices to access elements from the end of the list, with -1
being the index of the last element, -2
being the index of the second last element, and so on.
Here’s an example:
my_list = ['apple', 'banana', 'cherry']
print(my_list[0]) # Output: 'apple'
print(my_list[2]) # Output: 'cherry'
print(my_list[-1]) # Output: 'cherry'
You can also use slicing to access a range of elements in a list. Slicing is done using the colon :
operator. The first number before the colon represents the starting index (inclusive), and the second number after the colon represents the ending index (exclusive).Copy
my_list = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(my_list[1:4]) # Output: ['banana', 'cherry', 'orange']
If you omit the first number, Python assumes that you want to start at the beginning of the list. Similarly, if you omit the second number, Python assumes that you want to go until the end of the list.
my_list = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(my_list[:3]) # Output: ['apple', 'banana', 'cherry']
print(my_list[2:]) # Output: ['cherry', 'orange', 'kiwi']
You can also use negative indices when slicing. In that case, -1
represents the last element, -2
represents the second last element, and so on.
my_list = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(my_list[-3:-1]) # Output: ['cherry', 'orange']
Negative Indexing in Python
Negative indexing in Python allows you to access elements of a list by counting from the end of the list. In other words, the index -1 refers to the last element, -2 refers to the second to last element, and so on.
For example, suppose we have a list my_list = [10, 20, 30, 40, 50]
. To access the last element of the list, we can use negative indexing like this:
last_element = my_list[-1]
This would assign the value 50
to the variable last_element
. Similarly, we can access the second to last element using -2
:
second_to_last = my_list[-2]
This would assign the value 40
to the variable second_to_last
.
Slicing of a Python List
Slicing is a technique used in Python to extract a portion of a list by specifying a range of indices. It returns a new list that contains the specified elements.
To slice a Python list, we use the slicing operator :
. The syntax for slicing a list is as follows:
list_name[start:end:step]
start
: The starting index of the slice. If not specified, it defaults to 0.end
: The ending index of the slice. If not specified, it defaults to the length of the list.step
: The step size of the slice. If not specified, it defaults to 1.
Here are some examples of slicing a Python list:
# Create a list
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice from index 1 to index 5 (exclusive)
print(my_list[1:5]) # Output: [1, 2, 3, 4]
# Slice from index 2 to the end of the list
print(my_list[2:]) # Output: [2, 3, 4, 5, 6, 7, 8, 9]
# Slice from the beginning of the list to index 4 (exclusive)
print(my_list[:4]) # Output: [0, 1, 2, 3]
# Slice from index 1 to index 7 (exclusive) with a step size of 2
print(my_list[1:7:2]) # Output: [1, 3, 5]
# Reverse the list
print(my_list[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Add Elements to a Python List
Python List provides different methods to add items to a list.
a. Using append()
The append()
method is used to add a single element to the end of an existing list.
Here’s an example:
my_list = [1, 2, 3, 4]
my_list.append(5)
print(my_list) # Output: [1, 2, 3, 4, 5]
In this example, we first create a list my_list
with elements 1, 2, 3, and 4. We then call the append()
method on this list and pass it the argument 5. The append()
method adds 5 to the end of the list, and the final output is [1, 2, 3, 4, 5].
b. Using extend()
To add multiple elements to a Python list, you can use the extend()
method. This method takes an iterable as an argument and adds each element of the iterable to the end of the list.
Here’s an example:
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
In this example, the extend()
method is used to add three elements to the end of the my_list
list. The argument passed to extend()
is a list [4, 5, 6]
, which is iterated over and each element is added to the end of the list.
You can also use other iterable objects such as tuples, sets, or even another list with the extend()
method.
Change List Items
To change items of a Python list, you can use the indexing and assignment operator =
to assign a new value to the desired element of the list.
Here’s an example:
# create a list
fruits = ["apple", "banana", "cherry"]
# change the second element (index 1)
fruits[1] = "kiwi"
# print the modified list
print(fruits)
Output:
['apple', 'kiwi', 'cherry']
In the above example, we first created a list of fruits. Then, we used the indexing and assignment operator =
to change the second element of the list from banana
to kiwi
. Finally, we printed the modified list using the print()
function.
Remove an Item From a List
1. Using del()
In Python we can use the del statement to remove one or more items from a list. For example,
my_list = ['apple', 'banana', 'cherry', 'orange']
# delete the second element (banana)
del my_list[1]
# print the updated list
print(my_list)
Output:
['apple', 'cherry', 'orange']
In the example above, we first create a list of fruits. Then, using the del
keyword, we delete the second element (index 1), which is ‘banana’. Finally, we print the updated list to verify that the element has been deleted.
2. Using remove()
The remove()
method is used to remove the first occurrence of a specified value from a list.
Syntax: list_name.remove(value)
Example:
fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana')
print(fruits)
Output:
['apple', 'cherry', 'banana']
Python List Methods
Python List Methods are built-in functions that allow us to perform operations on Python lists. Some commonly used Python List Methods are:
- append(): adds an element to the end of the list.
- extend(): adds elements from an iterable to the end of the list.
- insert(): adds an element at the specified index.
- remove(): removes the first occurrence of the specified element from the list.
- pop(): removes the element at the specified index, or the last element if no index is specified, and returns it.
- clear(): removes all the elements from the list.
- index(): returns the index of the first occurrence of the specified element.
- count(): returns the number of times the specified element occurs in the list.
- sort(): sorts the list in ascending order.
- reverse(): reverses the order of the elements in the list.
These methods help us manipulate the list in various ways and make it more convenient to use.
Operation on List
To perform operations on a Python list, you can use a combination of built-in functions and methods. Some common operations on a Python list include:
- Concatenation: You can concatenate two or more lists using the
+
operator or theextend()
method. - Repetition: You can repeat a list a specified number of times using the
*
operator. - Membership testing: You can test whether an element is present in a list using the
in
keyword. - Length: You can get the length of a list using the
len()
function. - Sorting: You can sort a list using the
sort()
method. - Reversing: You can reverse a list using the
reverse()
method. - Copying: You can create a copy of a list using the
copy()
method or thelist()
constructor.
Here are some examples:
- Concatenation:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print(list3) # Output: [1, 2, 3, 4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
- Repetition:
list1 = [1, 2, 3]
list2 = list1 * 3
print(list2) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
- Membership testing:
list1 = [1, 2, 3]
if 2 in list1:
print("2 is present in the list")
else:
print("2 is not present in the list")
# Output: 2 is present in the list
- Length:
list1 = [1, 2, 3]
length = len(list1)
print(length) # Output: 3
- Reversing:
list1 = [1, 2, 3]
list1.reverse()
print(list1) # Output: [3, 2, 1]
- Sorting:
list1 = [3, 1, 2]
list1.sort()
print(list1) # Output: [1, 2, 3]
- Copying:
list1 = [1, 2, 3]
list2 = list1.copy()
list3 = list(list1)
print(list2) # Output: [1, 2, 3]
print(list3) # Output: [1, 2, 3]
Function on List
To perform a function on a Python list, you can use various built-in functions provided by Python.
Here are some commonly used functions on a Python list:
len()
: This function returns the number of elements in the list.max()
: This function returns the largest element in the list.min()
: This function returns the smallest element in the list.sum()
: This function returns the sum of all elements in the list.sorted()
: This function returns a sorted list.reversed()
: This function returns a reversed list.any()
: This function returnsTrue
if at least one element in the list isTrue
, otherwise it returnsFalse
.all()
: This function returnsTrue
if all elements in the list areTrue
, otherwise it returnsFalse
.enumerate()
: This function returns an iterator of tuples containing the index and the value of each element in the list.zip()
: This function returns an iterator of tuples where each tuple contains the elements from the input lists at that index.filter()
: This function returns a new list containing only the elements for which the given function returnsTrue
.map()
: This function applies the given function to each element in the list and returns a new list containing the results.reduce()
: This function applies the given function to the first two elements in the list, then applies the function to the result and the next element in the list, and so on, until all elements have been processed. The final result is returned. Note thatreduce()
is not a built-in function in Python 3, but is available in thefunctools
module.
To perform a function on a Python list, you can use various built-in functions provided by Python. Here are some examples:
len()
: This function returns the length of the list, i.e., the number of elements in the list.
Example:
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
Output:
5
sum()
: This function returns the sum of all elements in the list.
Example:
my_list = [1, 2, 3, 4, 5]
print(sum(my_list))
Output:
15
max()
: This function returns the maximum value from the list.
Example:
my_list = [1, 2, 3, 4, 5]
print(max(my_list))
Output:
5
min()
: This function returns the minimum value from the list.
Example:
my_list = [1, 2, 3, 4, 5]
print(min(my_list))
Output:
1
sorted()
: This function returns a new sorted list.
Example:
my_list = [5, 3, 1, 4, 2]
sorted_list = sorted(my_list)
print(sorted_list)
Output:
[1, 2, 3, 4, 5]
reversed()
: This function returns a new reversed list.
Example:
my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)
Output:
[5, 4, 3, 2, 1]
😸Tuple
Have you ever packed for a trip and made a list of everything you need to bring? Tuples are like your packing list for your Python program! They allow you to create a collection of items that can’t be changed (immutable), just like how once you’ve packed your suitcase, you can’t add or remove items without unpacking everything.
Creating a Tuple
To create a tuple in Python, you can enclose a sequence of elements in parentheses, separated by commas. Here is an example:
my_tuple = (1, 2, 3, 'hello', 'world')
In this example, my_tuple
is a tuple containing 5 elements: the integers 1, 2, and 3, and the strings ‘hello’ and ‘world’. You can also create an empty tuple like this:Copy
empty_tuple = ()
Tuples can contain elements of different data types, and can also contain other tuples as elements, making them a versatile data structure in Python.
Accessing Tuple Elements
To access the elements of a tuple, you can use the indexing operator []. The index starts at 0 for the first element, 1 for the second element, and so on. You can also use negative indexing, which starts at -1 for the last element and goes backward.
Here’s an example:
# creating a tuple
my_tuple = ('apple', 'banana', 'cherry')
# accessing tuple elements
print(my_tuple[0]) # output: apple
print(my_tuple[1]) # output: banana
print(my_tuple[2]) # output: cherry
print(my_tuple[-1]) # output: cherry
print(my_tuple[-2]) # output: banana
print(my_tuple[-3]) # output: apple
In this example, we created a tuple my_tuple
with three elements (‘apple’, ‘banana’, ‘cherry’). We accessed the elements of the tuple using their index, both positive and negative. The output shows the corresponding element at each index.
Tuple Methods
Unlike Lists, Tuples are immutable objects in Python, meaning that they cannot be modified after they are created. Therefore, they have a limited number of methods available compared to lists. Here are some commonly used Tuple methods:
- count(): This method returns the number of times a specified element appears in the tuple.
- index(): This method returns the index of the first occurrence of a specified element in the tuple.
Let’s see some examples:
# Creating a tuple
my_tuple = (1, 2, 3, 4, 2, 5, 6, 2)
# Using count() method
print(my_tuple.count(2)) # Output: 3
# Using index() method
print(my_tuple.index(4)) # Output: 3
In the above example, we created a tuple with some elements, and then we used the count()
method to find out the number of times the element 2
appears in the tuple. We also used the index()
method to find out the index of the first occurrence of the element 4
in the tuple.
Advantages of Using Tuples
Here are some advantages of using tuples in Python:
- Immutable: Tuples are immutable, which means that once they are created, you cannot modify their contents. This makes them safer to use in certain cases where you don’t want the data to be accidentally modified.
- Faster Access: Since tuples are stored in a contiguous block of memory, accessing an element in a tuple is faster compared to accessing an element in a list.
- Useful for Unpacking: Tuples are often used for returning multiple values from a function. They are also useful when you want to unpack a sequence into multiple variables.
- Efficient Memory Usage: Since tuples are immutable and cannot be modified, Python can optimize memory usage more efficiently for tuples compared to lists.
- Valid Dictionary Keys: Tuples are immutable and hashable, which makes them valid dictionary keys in Python. This can be useful in certain cases where you want to use a tuple as a key in a dictionary.
Differences between Lists and Tuples
Lists | Tuples |
---|---|
Lists are mutable i.e., elements of a list can be modified. | Tuples are immutable i.e., elements of a tuple cannot be modified. |
Lists use square brackets [] to enclose the elements. | Tuples use parentheses () to enclose the elements. |
Lists have several built-in methods like append() , extend() , insert() , remove() , pop() , etc. for modification. | Tuples have only two built-in methods: count() and index() . |
Lists are usually used to store homogeneous items of varying lengths. | Tuples are usually used to store heterogeneous items of fixed lengths. |
Lists are slower than tuples. | Tuples are faster than lists. |
Lists consume more memory as compared to tuples. | Tuples consume less memory as compared to lists. |
When to Use Tuples
Tuples are commonly used in the following situations:
- When you want to ensure that the data is not modified accidentally or intentionally, as tuples are immutable.
- When you have a collection of related data that doesn’t need to be modified, such as coordinates, dimensions, or other fixed data sets.
- When you want to use a collection of data as a key in a dictionary because tuples are hashable (unlike lists).
- When you want to return multiple values from a function. You can return a tuple containing the required values, and the function caller can unpack them as needed.
Tuple Packing and Unpacking
Tuple packing and unpacking are useful features in Python that allow you to assign multiple values to a single variable, and also to extract values from a tuple into separate variables.
Tuple Packing:
When you create a tuple with multiple values, you are actually performing tuple packing. For example:
my_tuple = 1, 2, 3
Here, we have created a tuple named my_tuple
with three values 1, 2, and 3. Python automatically packs these values into a tuple.
You can also use parentheses to create a tuple, like this:
my_tuple = (1, 2, 3)
Tuple Unpacking:
Tuple unpacking allows you to extract the values of a tuple into separate variables. For example:
my_tuple = 1, 2, 3
x, y, z = my_tuple
print(x) # Output: 1
print(y) # Output: 2
print(z) # Output: 3
Here, we have created a tuple named my_tuple
with three values 1, 2, and 3. We have then used tuple unpacking to assign each value to a separate variable x, y, and z.
Tuple unpacking is particularly useful when you have functions that return multiple values as a tuple. You can use tuple unpacking to extract these values into separate variables, like this:
def my_function():
return 1, 2, 3
x, y, z = my_function()
print(x) # Output: 1
print(y) # Output: 2
print(z) # Output: 3
Tuple Applications
Some common applications of tuples in Python are:
- Multiple variable assignment: Tuples can be used to assign multiple values to multiple variables in a single line of code. This is known as tuple unpacking. For example:
x, y, z = (1, 2, 3)
- Function returns: Functions can return multiple values as a tuple. The calling function can then unpack the tuple to access the returned values. For example:
Copy
def calculate(x, y):
sum = x + y
diff = x - y
return sum, diff
result = calculate(5, 3)
print(result) # (8, 2)
sum, diff = calculate(5, 3)
print(sum) # 8
print(diff) # 2
- Immutable data storage: Since tuples are immutable, they can be used to store data that should not be changed accidentally or intentionally. For example, a set of constant values that are used throughout the program.
- Dictionary keys: Tuples can be used as keys in Python dictionaries since they are immutable. For example:
my_dict = {('John', 'Doe'): 25, ('Jane', 'Doe'): 30}
- Sequences of values: Tuples can be used to represent sequences of values, such as the x and y coordinates of a point in a 2D plane, or the RGB values of a color.
😨Strings
In Python, a string is a sequence of characters, which can be either letters, numbers, or symbols, enclosed within single quotes (‘ ‘), double quotes (” “), or triple quotes (“”” “”” or ”’ ”’). Strings are one of the most commonly used data types in Python, and they are immutable, which means that once a string is created, it cannot be modified.
Python provides a range of built-in functions and methods to manipulate strings, including slicing, concatenation, repetition, and searching. Understanding how to work with strings is essential in Python programming, as strings are often used to store and manipulate textual data such as user inputs, file names, and messages.
Creating a String
In Python, you can create a string by enclosing a sequence of characters in either single quotes (‘…’) or double quotes (“…”). Here’s an example:
# creating a string using single quotes
my_string = 'Hello, World!'
print(my_string)
# creating a string using double quotes
my_string2 = "Hello, Python!"
print(my_string2)
Output:
Hello, World!
Hello, Python!
You can also create a string using triple quotes (”’…”’ or “””…”””). Triple-quoted strings can span multiple lines and are often used for docstrings or for multi-line strings. Here’s an example:
# creating a string using triple quotes
my_string3 = '''This is a
multi-line string
using triple quotes.'''
print(my_string3)
Output:
This is a
multi-line string
using triple quotes.
Accessing Characters in a String
We can access the characters in a string in three ways.
- Indexing
Indexing is used to access a specific character in a string by referring to its position using an index number enclosed in square brackets []
. The index number starts from 0 for the first character in the string and increases by 1 for each subsequent character.
Here is an example of indexing a string:
my_string = "Hello, World!"
print(my_string[0]) # Output: H
print(my_string[4]) # Output: o
print(my_string[-1]) # Output: !
In the first example, we access the first character of the string "Hello, World!"
using its index number 0
, which returns "H"
. In the second example, we access the fifth character using the index number 4
, which returns "o"
. In the third example, we access the last character of the string using the negative index number -1
, which returns "!"
.
- Negative Indexing
Negative indexing allows you to access the characters of a string from the end. In negative indexing, the index of the last character is -1, and the index of the second-last character is -2, and so on.
For example, let’s consider the following string:
my_string = "Hello World"
To access the last character of the string using negative indexing, we can use:
print(my_string[-1]) # Output: d
Similarly, to access the second-last character, we can use:
print(my_string[-2]) # Output: l
- slicing
Slicing is another way to access a range of characters in a string. It involves specifying the start index, end index, and the step size.
Here’s an example:
my_string = "Hello, world!"
substring = my_string[2:9:2]
print(substring)
Output:
lo,w
In the above example, we started slicing from index 2 (l
) and stopped at index 9 (w
) with a step size of 2. This means we got every second character between index 2 and 9.
Note that the start index is inclusive, while the end index is exclusive. This means that the character at the end index is not included in the slice.
Deleting Stings
In Python, we cannot delete or remove a part of a string. However, we can delete the entire string using the del
keyword or by reassigning the string variable to an empty string.
Here is an example of deleting a string using the del
keyword:
my_string = "Hello World!"
del my_string
After executing this code, the my_string
variable will no longer exist in memory.
Here is an example of reassigning a string variable to an empty string:
my_string = "Hello World!"
my_string = ""
After executing this code, the my_string
variable will still exist in memory, but its value will be an empty string.
String Methods
There are many built-in methods available in Python for manipulating strings. Here are some of the most commonly used ones:
len()
: Returns the length of the string.upper()
: Converts all characters in the string to uppercase.lower()
: Converts all characters in the string to lowercase.capitalize()
: Converts the first character of the string to uppercase and the rest to lowercase.title()
: Converts the first character of each word in the string to uppercase and the rest to lowercase.strip()
: Removes any whitespace characters from the beginning and end of the string.replace()
: Replaces all occurrences of a substring in the string with another substring.split()
: Splits the string into a list of substrings based on a delimiter.join()
: Joins a list of strings into a single string using a delimiter.find()
: Searches the string for a substring and returns the index of the first occurrence.count()
: Counts the number of occurrences of a substring in the string.startswith()
: Returns True if the string starts with a given substring.endswith()
: Returns True if the string ends with a given substring.isnumeric()
: Returns True if all characters in the string are numeric.isalpha()
: Returns True if all characters in the string are alphabetic.isdigit()
: Returns True if all characters in the string are digits.isalnum()
: Returns True if all characters in the string are alphanumeric.isspace()
: Returns True if all characters in the string are whitespace characters.
These are just a few examples of the many string methods available in Python.
here are some examples of string methods:
upper()
: This method returns the string in uppercase letters.
string = "hello world"
print(string.upper()) # output: HELLO WORLD
lower()
: This method returns the string in lowercase letters.
Copy
string = "HELLO WORLD"
print(string.lower()) # output: hello world
capitalize()
: This method capitalizes the first letter of the string.
string = "hello world"
print(string.capitalize()) # output: Hello world
split()
: This method splits the string into a list of substrings based on a specified separator.
Copy
string = "apple,banana,orange"
print(string.split(",")) # output: ['apple', 'banana', 'orange']
replace()
: This method replaces a specified substring with another substring in the string.
string = "hello world"
print(string.replace("world", "python")) # output: hello python
strip()
: This method removes any leading and trailing whitespace from the string.
string = " hello world "
print(string.strip()) # output: hello world
String Formatting
String formatting is the process of creating a string that represents a value or a set of values in a specific way. In Python, there are several ways to format a string, including the %-formatting method, the str.format() method, and f-strings.
Here is an example using f-strings:
name = "Alice"
age = 30
print(f"My name is {name} and I'm {age} years old.")
This will output:
My name is Alice and I'm 30 years old.
In this example, the f-string is enclosed in curly braces {}
and contains the variable names that we want to include in the string. The variables are automatically converted to strings and inserted into the string in the correct order.
Another way to format a string is by using the format()
method:
name = "Bob"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))
This will output:
My name is Bob and I'm 25 years old.
In this example, the format()
method is called on the string and the values to be inserted are passed as arguments in the correct order. The curly braces {}
serve as placeholders for the values to be inserted.
The %-formatting method is another way to format strings in Python, but it is less commonly used than the format()
method and f-strings.
Escape Characters
Escape characters are special characters that are used to represent certain characters that cannot be typed or are difficult to type. In Python, escape characters are represented by a backslash () followed by a character or a sequence of characters. Here are some commonly used escape characters in Python:
- \n : newline
- \t : tab
- ‘ : single quote
- ” : double quote
- \b : backspace
- \r : carriage return
For example, if you want to print a string that contains a single quote, you can use the escape character like this:
print('I don\'t like Python.')
The output will be:
I don't like Python.
Triple Quotes
Triple quotes in Python are used to represent multiline strings. This means that strings can span across multiple lines and preserve the formatting of the text. Triple quotes can be used with both single and double quotes.
Triple quotes are commonly used for documentation strings (docstrings) in Python, which are used to document Python modules, functions, classes, and methods. They are enclosed in triple quotes, and can span multiple lines to provide detailed information about the code.
Here’s an example of using triple quotes to create a multiline string:
my_string = '''This is a multiline
string in Python.
It can span across multiple lines
and preserve the formatting.'''
print(my_string)
Output:
This is a multiline
string in Python.
It can span across multiple lines
and preserve the formatting.
In the above example, the triple quotes allow us to create a multiline string that spans across four lines. The newlines and the formatting of the string are preserved when we print it to the console.
Python String Operations
Python provides various string operations that can be used to manipulate and process strings. Some of the commonly used string operations in Python are:
- Concatenation: It is used to join two or more strings together. The concatenation operator in Python is the plus sign (+).
- Repetition: It is used to repeat a string a certain number of times. The repetition operator in Python is the asterisk sign (*).
- Slicing: It is used to extract a part of a string. Slicing is done by specifying the start index and end index of the substring separated by a colon.
- Length: It is used to find the length of a string. The length of a string is the number of characters in the string.
- Case conversion: It is used to convert the case of the characters in a string. Python provides methods like upper(), lower(), title() to convert the case of the characters in a string.
- Strip: It is used to remove leading and trailing whitespaces from a string.
- Replace: It is used to replace a substring in a string with another substring.
- Find: It is used to find the first occurrence of a substring in a string.
- Count: It is used to count the number of occurrences of a substring in a string.
These operations make it easier to manipulate and process strings in Python.
☺️Sets
A set is an unordered collection of unique elements in Python. The elements can be of any data type, but they must be immutable (i.e., they cannot be changed). Sets are mutable, which means that you can add, remove, and update their elements after they have been created.
In Python, sets are defined using curly braces {}
or the built-in set()
function.
Creating a Set
To create a set, you can define a comma-separated list of elements inside curly braces {}
or use the set()
function with a list of elements as an argument.
Here’s an example of how to create a set:
# Creating a set
fruits = {"apple", "banana", "cherry"}
print(fruits)
# Output: {'banana', 'apple', 'cherry'}
# Creating a set using set() function
colors = set(["red", "green", "blue"])
print(colors)
# Output: {'blue', 'green', 'red'}
As you can see, the elements in a set are not ordered in any particular way.
Create an Empty Set in Python
To create an empty set in Python, you can use either of the following ways:
- Using curly braces {}:
Copy
my_set = {}
print(type(my_set)) # <class 'dict'>
Here, the empty curly braces {}
actually create an empty dictionary instead of an empty set.
- Using the
set()
function:
Copy
my_set = set()
print(type(my_set)) # <class 'set'>
Here, we use the set()
function to create an empty set.
Note: To create a set with at least one element, we should enclose the elements in curly braces {}
or use the set()
function.
Duplicate Items in a Set
In a set, duplicate items are not allowed. If we try to add a duplicate item to a set, it will not be added and the set will remain unchanged.
For example:
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
my_set.add(5)
print(my_set) # Output: {1, 2, 3, 4, 5}
my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
In the above example, we try to add the value 5
to the set my_set
twice, but it only gets added once. When we try to add the value 6
, it gets added to the set since it is not a duplicate item.
Accessing Set Elements
Since sets are unordered, you cannot access their elements by index. Instead, you can loop through the set using a for
loop or check if an element is in the set using the in
keyword.
Here’s an example:
# Looping through a set
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
# Output:
# banana
# apple
# cherry
# Checking if an element is in a set
colors = set(["red", "green", "blue"])
print("red" in colors)
# Output: True
Modifying Sets
You can add, remove, or update elements in a set after it has been created.
Adding Elements to a Set
To add an element to a set, you can use the add()
method or the update()
method to add multiple elements.
Here’s an example:
# Adding an element to a set
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)
# Output: {'banana', 'apple', 'cherry', 'orange'}
# Adding multiple elements to a set
colors = set(["red", "green", "blue"])
colors.update(["yellow", "purple"])
print(colors)
# Output: {'red', 'yellow', 'blue', 'purple', 'green'}
Removing Elements from a Set
To remove an element from a set, you can use the remove()
method or the discard()
method. The only difference between the two methods is that if you try to remove an element that is not in the set, the remove()
method will raise a KeyError
exception, while the discard()
method will not.
Here’s an example:
# Removing an element from a set
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
# Output: {'apple', 'cherry'}
# Removing an element that does not exist using remove() method
fruits.remove("orange")
# Output: KeyError: 'orange'
# Removing an element that does not exist using discard() method
fruits.discard("orange")
print(fruits)
# Output: {'apple', 'cherry'}
Updating Elements in a Set
To update an element in a set, you can use the update()
method or the add()
method.
The update()
method is used to add multiple items to a set at once. It takes an iterable as an argument and adds each element of the iterable to the set. If any of the elements already exist in the set, they are ignored.
Here’s an example of using the update()
method to add multiple elements to a set:
fruits = {'apple', 'banana', 'cherry'}
fruits.update(['orange', 'grape'])
print(fruits)
Output:
{'banana', 'cherry', 'orange', 'grape', 'apple'}
The add()
method, on the other hand, is used to add a single element to a set. If the element already exists in the set, it is ignored.
Here’s an example of using the add()
method to add a single element to a set:
fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange')
print(fruits)
Output:
{'banana', 'cherry', 'orange', 'apple'}
You can also update a set with another set using the update()
method:
fruits1 = {'apple', 'banana', 'cherry'}
fruits2 = {'orange', 'grape', 'apple'}
fruits1.update(fruits2)
print(fruits1)
Output:
{'banana', 'cherry', 'orange', 'grape', 'apple'}
Built-in Functions with Set
Built-in functions like all()
, any()
, enumerate()
, len()
, max()
, min()
, sorted()
, sum()
etc. are commonly used with sets to perform different tasks.
Function | Description |
---|---|
len() | Returns the length (number of items) in a set |
max() | Returns the maximum value of a set |
min() | Returns the minimum value of a set |
any() | Returns True if any item in the set is true. If the set is empty, returns False. |
all() | Returns True if all items in the set are true. If the set is empty, returns True. |
set() | Constructs a new set from an iterable (list, tuple, string, etc.) |
sorted() | Returns a new sorted list from the items in a set |
sum() | Returns the sum of all elements in a set |
pop() | Removes and returns an arbitrary item from the set |
clear() | Removes all elements from the set |
copy() | Returns a shallow copy of the set |
isdisjoint() | Returns True if two sets have no intersection |
issubset() | Returns True if all items in the set are present in another set |
issuperset() | Returns True if a set contains all the items in another set |
union() | Returns a new set with all items from both sets |
intersection() | Returns a new set with items common to both sets |
difference() | Returns a new set with items in one set but not the other |
symmetric_difference() | Returns a new set with items in either set, but not both sets |
Iterate Over a Set in Python
You can iterate over a set in Python using a for
loop. Here’s an example:
fruits = {'apple', 'banana', 'cherry'}
for fruit in fruits:
print(fruit)
Output:
banana
apple
cherry
Note that the order of the elements in the set may vary when you iterate over it.
Find Number of Set Elements
To find the number of elements in a set in Python, you can use the built-in len()
function.
Here’s an example:
my_set = {1, 2, 3, 4, 5}
print(len(my_set)) # Output: 5
In the above example, we have a set my_set
with 5 elements. We use the len()
function to find the number of elements in the set and print the output, which is 5.
Set Operations
Python Set provides different built-in methods to perform mathematical set operations like union, intersection, subtraction, and symmetric difference.
Union of Two Sets
The union of two sets in Python can be obtained using the union()
method or the pipe operator |
. Here’s an example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# using union() method
set3 = set1.union(set2)
print(set3) # Output: {1, 2, 3, 4, 5}
# using pipe operator
set4 = set1 | set2
print(set4) # Output: {1, 2, 3, 4, 5}
In the above example, we have two sets set1
and set2
. We can obtain the union of these two sets by calling the union()
method on set1
and passing set2
as an argument. We can also use the pipe operator |
to perform the union operation on these two sets. The result of both approaches is the same set {1, 2, 3, 4, 5}
.
Set Intersection
Set Intersection means the common elements in both sets.
In Python, the intersection of two sets can be found using the intersection()
method or the &
operator.
Here’s an example:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# using intersection() method
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {4, 5}
# using & operator
intersection_set = set1 & set2
print(intersection_set) # Output: {4, 5}
In the above example, we have two sets, set1
and set2
, and we are finding their intersection using the intersection()
method and the &
operator. The resulting set contains the common elements in both sets, which are 4 and 5.
Check if two sets are equal
The sets are equal
Output:
set1 = {1, 2, 3}
set2 = {3, 2, 1}
if set1 == set2:
print("The sets are equal")
else:
print("The sets are not equal")
To check if two sets are equal, you can use the ==
operator. Here’s an example:
Other Python Set Methods
Here are some other commonly used methods in Python sets:
add(element)
: Adds an element to the set.remove(element)
: Removes an element from the set. Raises a KeyError if the element is not found.discard(element)
: Removes an element from the set. Does not raise an error if the element is not found.pop()
: Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty.clear()
: Removes all elements from the set.copy()
: Returns a copy of the set.intersection_update(other_set)
: Updates the set with the intersection of itself and another set.difference_update(other_set)
: Updates the set with the difference of itself and another set.symmetric_difference_update(other_set)
: Updates the set with the symmetric difference of itself and another set.update(other_set)
: Updates the set by adding elements from another set.
These methods modify the set in place and do not return a new set.
✌️Dictionary
A Python dictionary is an unordered collection of key-value pairs that is mutable, meaning you can change its contents, unlike tuples and strings. It is also known as associative arrays, hash tables, or simply hashes. Each key-value pair in a dictionary is separated by a colon (:), and the pairs are separated from each other by commas. A dictionary is defined within curly braces ({}) and can be assigned to a variable just like any other data type in Python.
Dictionaries are extremely useful when it comes to dealing with large data sets or datasets where the position of data is not important. Instead, what is important is the association between two pieces of information.
In Python, dictionaries are implemented as hash tables, which means that the time complexity for accessing, inserting, or deleting a key-value pair is O(1), making them very efficient for many use cases.
Creating a Dictionary
In Python, we can create a dictionary by enclosing a comma-separated list of key-value pairs inside curly braces {}
. Each key-value pair is separated by a colon :
. Here is an example:
# create a dictionary
person = {'name': 'John', 'age': 30, 'city': 'New York'}
# print the dictionary
print(person)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
In the example above, we created a dictionary called person
that contains three key-value pairs: 'name': 'John'
, 'age': 30
, and 'city': 'New York'
. We then printed the dictionary using the print()
function.
Accessing Elements from a Dictionary
We can access the elements of a dictionary by referring to its key name, inside square brackets or by using the get()
method.
Example using square brackets:
my_dict = {"name": "John", "age": 28, "location": "New York"}
print(my_dict["name"]) # Output: John
print(my_dict["age"]) # Output: 28
Example using the get()
method:
my_dict = {"name": "John", "age": 28, "location": "New York"}
print(my_dict.get("name")) # Output: John
print(my_dict.get("age")) # Output: 28
If we try to access a key that does not exist in the dictionary using square brackets, we will get a KeyError
. However, if we use the get()
method and the key does not exist in the dictionary, it will return None
(or a default value we can specify).Copy
my_dict = {"name": "John", "age": 28, "location": "New York"}
print(my_dict["occupation"]) # Output: KeyError: 'occupation'
print(my_dict.get("occupation")) # Output: None
print(my_dict.get("occupation", "-")) # Output: -
Updating and Adding Elements to a Dictionary
To update an element in a dictionary, we can simply access the key and reassign a new value to it. If the key does not exist, it will be added as a new key-value pair.
Here’s an example:
# create a dictionary
my_dict = {'apple': 2, 'banana': 4, 'orange': 1}
# update the value of 'apple'
my_dict['apple'] = 3
# add a new key-value pair
my_dict['pear'] = 5
print(my_dict) # {'apple': 3, 'banana': 4, 'orange': 1, 'pear': 5}
In this example, we first created a dictionary my_dict
with three key-value pairs. Then we updated the value of the key 'apple'
to 3
. Finally, we added a new key-value pair 'pear': 5'
to the dictionary.
Removing Elements from a Dictionary
We can remove elements from a dictionary in several ways, using the del
keyword, pop()
method, and clear()
method.
- Using the
del
keyword:
We can use the del
keyword to remove a specific key-value pair from the dictionary. Here’s an example:
my_dict = {'name': 'John', 'age': 25, 'gender': 'male'}
del my_dict['gender']
print(my_dict) # Output: {'name': 'John', 'age': 25}
- Using the
pop()
method:
We can use the pop()
method to remove a specific key-value pair from the dictionary and return the value of the removed key. Here’s an example:
my_dict = {'name': 'John', 'age': 25, 'gender': 'male'}
removed_value = my_dict.pop('gender')
print(my_dict) # Output: {'name': 'John', 'age': 25}
print(removed_value) # Output: 'male'
- Using the
clear()
method:
We can use the clear()
method to remove all the key-value pairs from the dictionary. Here’s an example:
my_dict = {'name': 'John', 'age': 25, 'gender': 'male'}
my_dict.clear()
print(my_dict) # Output: {}
Change Value of Dictionary
To change the value of a dictionary, you can simply assign a new value to the corresponding key. Here’s an example:
# create a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
# change the value of 'age' key
my_dict['age'] = 30
# print the updated dictionary
print(my_dict)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
In the above example, we first created a dictionary my_dict
with three key-value pairs. Then we changed the value of the 'age'
key to 30
by assigning a new value to it. Finally, we printed the updated dictionary.
Dictionary Methods
Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.
Method | Description |
---|---|
clear() | Removes all items from the dictionary |
copy() | Returns a shallow copy of the dictionary |
fromkeys(seq[, v]) | Returns a new dictionary with keys from seq and value v |
get(key[,d]) | Returns the value of the key key . If the key doesn’t exist, returns d (defaults to None ) |
items() | Returns a view object of the dictionary’s (key, value) pairs |
keys() | Returns a view object of the dictionary’s keys |
pop(key[,d]) | Removes the key and returns the associated value. If the key doesn’t exist and d is not provided, raises a KeyError . If d is provided, returns d |
popitem() | Removes and returns an arbitrary (key, value) pair. Raises a KeyError if the dictionary is empty |
setdefault(key[,d]) | Returns the value of the key. If the key doesn’t exist, inserts the key with a value of d (defaults to None ) |
update([other]) | Updates the dictionary with the key/value pairs from other . If a key already exists in the dictionary, its value is updated |
values() | Returns a view object of the dictionary’s values |
Dictionary Membership Test
In Python, we can use the in
keyword to check if a key is present in a dictionary. Here is an example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'a' in my_dict:
print('Key "a" is present in the dictionary')
else:
print('Key "a" is not present in the dictionary')
Output:Copy
Key "a" is present in the dictionary
We can also use the not in
keyword to check if a key is not present in a dictionary. Here is an example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'd' not in my_dict:
print('Key "d" is not present in the dictionary')
else:
print('Key "d" is present in the dictionary')
Output:
Key "d" is not present in the dictionary
Iterating Through a Dictionary
You can iterate through a dictionary using a for loop to access each key-value pair of the dictionary. Here is an example:
my_dict = {"apple": 2, "banana": 4, "orange": 1}
# iterating through the dictionary
for key, value in my_dict.items():
print(key, value)
Output:
apple 2
banana 4
orange 1
In this example, the items()
method is used to access the key-value pairs of the dictionary, and then a for loop is used to iterate through the pairs. The key
and value
variables are used to store the key and value of each pair in each iteration of the loop.
Looping Techniques with Dictionaries
In Python, there are several looping techniques that can be used to iterate through a dictionary. Here are some of them:
- Looping through keys:
We can use a for
loop to iterate over the keys of a dictionary. Here’s an example:
my_dict = {'apple': 3, 'banana': 2, 'orange': 1}
for key in my_dict:
print(key)
Output:
apple
banana
orange
- Looping through values:
We can also use a for
loop to iterate over the values of a dictionary. Here’s an example:Copy
my_dict = {'apple': 3, 'banana': 2, 'orange': 1}
for value in my_dict.values():
print(value)
Output:
3
2
1
- Looping through key-value pairs:
We can use a for
loop to iterate over the key-value pairs of a dictionary using the items()
method. Here’s an example:Copy
my_dict = {'apple': 3, 'banana': 2, 'orange': 1}
for key, value in my_dict.items():
print(key, value)
Output:
apple 3
banana 2
orange 1
- Using List Comprehensions:
We can also use list comprehensions to iterate over the keys, values, or items of a dictionary. Here are some examples:
my_dict = {'apple': 3, 'banana': 2, 'orange': 1}
# List comprehension to get all the keys
keys = [key for key in my_dict]
print(keys)
# List comprehension to get all the values
values = [value for value in my_dict.values()]
print(values)
# List comprehension to get all the key-value pairs
items = [(key, value) for key, value in my_dict.items()]
print(items)
Output:
['apple', 'banana', 'orange']
[3, 2, 1]
[('apple', 3), ('banana', 2), ('orange', 1)]
Built-in Functions with Dictionaries
Function | Description |
---|---|
len() | Returns the number of items (key-value pairs) in a dictionary |
str() | Produces a printable string representation of a dictionary |
type() | Returns the type of the passed variable. If a passed variable is a dictionary, then it would return a dictionary type |
dict() | Constructor method to create a dictionary |
clear() | Returns the type of the passed variable. If a passed variable is a dictionary, then it would return a dictionary-type |
copy() | Removes all elements of a dictionary dict |
fromkeys() | Returns a new dictionary with keys from seq and values set to value(default is None) |
get(key, default) | Returns the value for the given key if it exists, else returns the default value |
items() | Returns a list of the key-value pairs in the dictionary |
keys() | Returns a list of the keys in the dictionary |
values() | Returns a list of the values in the dictionary |
pop(key) | Removes and returns the value for the given key if it exists, else returns the default value |
popitem() | Removes and returns an arbitrary key-value pair from the dictionary |
update() | Adds dictionary dict2 to dictionary dict |
❤️ If you liked the article, like and subscribe to my channel, “Securnerd”.
👍 If you have any questions or if I would like to discuss the described hacking tools in more detail, then write in the comments. Your opinion is very important to me! at last of post