This presentation educates you about Python and the reason for learning python, Key advantages of learning Python, Characteristics of Python, Hello World using Python syntax and Applications of Python.
For more topics stay tuned with Learnbay.
Python is a high-level language programming, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable.
This presentation educates you about Python and the reason for learning python, Key advantages of learning Python, Characteristics of Python, Hello World using Python syntax and Applications of Python.
For more topics stay tuned with Learnbay.
Python is a high-level language programming, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable.
WHY
WHERE
HOW
WHEN
WHO
FOR WHAT
Defining Data Science
• What Does a Data Science Professional Do?
• Data Science in Business
• Use Cases for Data Science
Introduction to Python
What is Python?
Python is a high-level, interpreted programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Python emphasizes code readability with its clean and straightforward syntax, making it an excellent choice for beginners and experienced developers alike.
Features of Python:
Simple and Easy to Learn: Python's syntax is designed to be intuitive and readable, making it easy for beginners to grasp.
Interpreted: Python code is executed line by line by the Python interpreter, which means you can run Python code without the need for compilation.
High-Level: Python abstracts low-level details, allowing developers to focus on solving problems rather than dealing with system-level intricacies.
Dynamic Typing: Python uses dynamic typing, meaning you don't need to declare variable types explicitly. Variables can dynamically change types during execution.
Multi-paradigm: Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
Extensive Standard Library: Python comes with a vast standard library that provides support for various tasks like file I/O, networking, and more, making it highly versatile.
Portability: Python is available on various platforms, including Windows, macOS, and Linux, making it highly portable.
Community and Ecosystem: Python has a large and active community, contributing to a rich ecosystem of libraries and frameworks for various domains, such as web development, data science, machine learning, and more.
Use Cases of Python:
Web Development: With frameworks like Django and Flask, Python is widely used for building web applications.
Data Science: Python's rich ecosystem of libraries such as NumPy, Pandas, and Matplotlib makes it a popular choice for data analysis and visualization.
Machine Learning and AI: Libraries like TensorFlow, PyTorch, and scikit-learn enable developers to build machine learning models and AI applications efficiently.
Scripting: Python's simplicity and versatility make it ideal for writing scripts for automation, system administration, and more.
Game Development: Python is used in game development, both for writing game logic and scripting within game engines like Unity.
Installing Python:
To get started with Python, you need to install it on your system. You can download Python from the official website python.org and follow the installation instructions for your operating system.
Hello, World! Example:
Let's start with the traditional "Hello, World!" program in Python:
python
Copy code
print("Hello, World!")
This simple program prints "Hello, World!" to the console. It's a common starting point for learning any programming language.
Migration of Applications to Python is the most prudent DecisionMindfire LLC
Python is one of the top 10 most popular programming languages of 2021, according to the latest PYPL Index. It’s a no-brainer that if you want your software to perform better in the long run- Python is the best choice. If you use a different language for your applications, you can consider moving your applications to Python.
Apxic Technologies is a well-known name in the area of Computer education in Ambala. It is the best place to learn Python in Ambala. Book your free demo class now: 7497897720
If you're referring to acquisitions made by companies prior to the implementation of the Goods and Services Tax (GST), here are some acquisitions that occurred before GST was introduced:
Facebook (Meta Platforms, Inc.):
Instagram (Acquired in 2012)
WhatsApp (Acquired in 2014)
Oculus VR (Acquired in 2014)
Alphabet Inc. (Google):
YouTube (Acquired in 2006)
DoubleClick (Acquired in 2008)
Nest Labs (Acquired in 2014)
Amazon:
Zappos (Acquired in 2009)
Twitch (Acquired in 2014)
Microsoft Corporation:
LinkedIn (Acquired in 2016)
Skype (Acquired in 2011)
Apple Inc.:
Beats Electronics (Acquired in 2014)
Shazam (Acquisition announced in 2017, completed in 2018)
Oracle Corporation:
Sun Microsystems (Acquired in 2010)
Siebel Systems (Acquired in 2006)
IBM (International Business Machines Corporation):
Cognos (Acquired in 2007)
SPSS (Acquired in 2009)
Salesforce:
Tableau Software (Acquired in 2019)
MuleSoft (Acquired in 2018)
Cisco Systems:
WebEx (Acquired in 2007)
Meraki (Acquired in 2012)
Intel Corporation:
McAfee (Acquired in 2011)
Altera Corporation (Acquired in 2015)
These are just a few examples of acquisitions made by companies prior to the implementation of GST. These acquisitions have played significant roles in shaping the strategies and offerings of these tech giants.
If you're referring to acquisitions made by companies prior to the implementation of the Goods and Services Tax (GST), here are some acquisitions that occurred before GST was introduced:
Facebook (Meta Platforms, Inc.):
Instagram (Acquired in 2012)
WhatsApp (Acquired in 2014)
Oculus VR (Acquired in 2014)
Alphabet Inc. (Google):
YouTube (Acquired in 2006)
DoubleClick (Acquired in 2008)
Nest Labs (Acquired in 2014)
Amazon:
Zappos (Acquired in 2009)
Twitch (Acquired in 2014)
Microsoft Corporation:
LinkedIn (Acquired in 2016)
Skype (Acquired in 2011)
Apple Inc.:
Beats Electronics (Acquired in 2014)
Shazam (Acquisition announced in 2017, completed in 2018)
Oracle Corporation:
Sun Microsystems (Acquired in 2010)
Siebel Systems (Acquired in 2006)
IBM (International Business Machines Corporation):
Cognos (Acquired in 2007)
SPSS (Acquired in 2009)
Salesforce:
Tableau Software (Acquired in 2019)
MuleSoft (Acquired in 2018)
Cisco Systems:
WebEx (Acquired in 2007)
Meraki (Acquired in 2012)
Intel Corporation:
McAfee (Acquired in 2011)
Altera Corporation (Acquired in 2015)
These are just a few examples of acquisitions made by companies prior to the implementation of GST. These acquisitions have played significant roles in shaping the strategies and offerings of these tech giants.
If you're referring to acquisitions made by companies prior to the implementation of the Goods and Services Tax (GST), here are some acquisitions that occurred before GST was introduced:
Facebook (Meta Platforms, Inc.):
Instagram (Acquired in 2012)
WhatsApp (Acquired in 2014)
Oculus VR (Acquired in 2014)
Alphabet Inc. (Google):
YouTube (Acquired in 2006)
DoubleClick (Acquired in 2008)
Nest Labs (Acquired in 2014
WHY
WHERE
HOW
WHEN
WHO
FOR WHAT
Defining Data Science
• What Does a Data Science Professional Do?
• Data Science in Business
• Use Cases for Data Science
Introduction to Python
What is Python?
Python is a high-level, interpreted programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Python emphasizes code readability with its clean and straightforward syntax, making it an excellent choice for beginners and experienced developers alike.
Features of Python:
Simple and Easy to Learn: Python's syntax is designed to be intuitive and readable, making it easy for beginners to grasp.
Interpreted: Python code is executed line by line by the Python interpreter, which means you can run Python code without the need for compilation.
High-Level: Python abstracts low-level details, allowing developers to focus on solving problems rather than dealing with system-level intricacies.
Dynamic Typing: Python uses dynamic typing, meaning you don't need to declare variable types explicitly. Variables can dynamically change types during execution.
Multi-paradigm: Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
Extensive Standard Library: Python comes with a vast standard library that provides support for various tasks like file I/O, networking, and more, making it highly versatile.
Portability: Python is available on various platforms, including Windows, macOS, and Linux, making it highly portable.
Community and Ecosystem: Python has a large and active community, contributing to a rich ecosystem of libraries and frameworks for various domains, such as web development, data science, machine learning, and more.
Use Cases of Python:
Web Development: With frameworks like Django and Flask, Python is widely used for building web applications.
Data Science: Python's rich ecosystem of libraries such as NumPy, Pandas, and Matplotlib makes it a popular choice for data analysis and visualization.
Machine Learning and AI: Libraries like TensorFlow, PyTorch, and scikit-learn enable developers to build machine learning models and AI applications efficiently.
Scripting: Python's simplicity and versatility make it ideal for writing scripts for automation, system administration, and more.
Game Development: Python is used in game development, both for writing game logic and scripting within game engines like Unity.
Installing Python:
To get started with Python, you need to install it on your system. You can download Python from the official website python.org and follow the installation instructions for your operating system.
Hello, World! Example:
Let's start with the traditional "Hello, World!" program in Python:
python
Copy code
print("Hello, World!")
This simple program prints "Hello, World!" to the console. It's a common starting point for learning any programming language.
Migration of Applications to Python is the most prudent DecisionMindfire LLC
Python is one of the top 10 most popular programming languages of 2021, according to the latest PYPL Index. It’s a no-brainer that if you want your software to perform better in the long run- Python is the best choice. If you use a different language for your applications, you can consider moving your applications to Python.
Apxic Technologies is a well-known name in the area of Computer education in Ambala. It is the best place to learn Python in Ambala. Book your free demo class now: 7497897720
If you're referring to acquisitions made by companies prior to the implementation of the Goods and Services Tax (GST), here are some acquisitions that occurred before GST was introduced:
Facebook (Meta Platforms, Inc.):
Instagram (Acquired in 2012)
WhatsApp (Acquired in 2014)
Oculus VR (Acquired in 2014)
Alphabet Inc. (Google):
YouTube (Acquired in 2006)
DoubleClick (Acquired in 2008)
Nest Labs (Acquired in 2014)
Amazon:
Zappos (Acquired in 2009)
Twitch (Acquired in 2014)
Microsoft Corporation:
LinkedIn (Acquired in 2016)
Skype (Acquired in 2011)
Apple Inc.:
Beats Electronics (Acquired in 2014)
Shazam (Acquisition announced in 2017, completed in 2018)
Oracle Corporation:
Sun Microsystems (Acquired in 2010)
Siebel Systems (Acquired in 2006)
IBM (International Business Machines Corporation):
Cognos (Acquired in 2007)
SPSS (Acquired in 2009)
Salesforce:
Tableau Software (Acquired in 2019)
MuleSoft (Acquired in 2018)
Cisco Systems:
WebEx (Acquired in 2007)
Meraki (Acquired in 2012)
Intel Corporation:
McAfee (Acquired in 2011)
Altera Corporation (Acquired in 2015)
These are just a few examples of acquisitions made by companies prior to the implementation of GST. These acquisitions have played significant roles in shaping the strategies and offerings of these tech giants.
If you're referring to acquisitions made by companies prior to the implementation of the Goods and Services Tax (GST), here are some acquisitions that occurred before GST was introduced:
Facebook (Meta Platforms, Inc.):
Instagram (Acquired in 2012)
WhatsApp (Acquired in 2014)
Oculus VR (Acquired in 2014)
Alphabet Inc. (Google):
YouTube (Acquired in 2006)
DoubleClick (Acquired in 2008)
Nest Labs (Acquired in 2014)
Amazon:
Zappos (Acquired in 2009)
Twitch (Acquired in 2014)
Microsoft Corporation:
LinkedIn (Acquired in 2016)
Skype (Acquired in 2011)
Apple Inc.:
Beats Electronics (Acquired in 2014)
Shazam (Acquisition announced in 2017, completed in 2018)
Oracle Corporation:
Sun Microsystems (Acquired in 2010)
Siebel Systems (Acquired in 2006)
IBM (International Business Machines Corporation):
Cognos (Acquired in 2007)
SPSS (Acquired in 2009)
Salesforce:
Tableau Software (Acquired in 2019)
MuleSoft (Acquired in 2018)
Cisco Systems:
WebEx (Acquired in 2007)
Meraki (Acquired in 2012)
Intel Corporation:
McAfee (Acquired in 2011)
Altera Corporation (Acquired in 2015)
These are just a few examples of acquisitions made by companies prior to the implementation of GST. These acquisitions have played significant roles in shaping the strategies and offerings of these tech giants.
If you're referring to acquisitions made by companies prior to the implementation of the Goods and Services Tax (GST), here are some acquisitions that occurred before GST was introduced:
Facebook (Meta Platforms, Inc.):
Instagram (Acquired in 2012)
WhatsApp (Acquired in 2014)
Oculus VR (Acquired in 2014)
Alphabet Inc. (Google):
YouTube (Acquired in 2006)
DoubleClick (Acquired in 2008)
Nest Labs (Acquired in 2014
Similar to Python Programming and ApplicationsUnit-1.docx (20)
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Python Programming and ApplicationsUnit-1.docx
1. Python Introduction
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990.
Why to Learn Python?
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is
designed to be highly readable. It uses English keywords frequently where as other languages
use punctuation, and it has fewer syntactical constructions than other languages.
Advantages of Python:
Python is Interpreted − Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.
Characteristics of Python
Following are important characteristics of Python Programming −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large
applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Difference between C and Python
Metrics Python C
Introduction
Python is an interpreted, high-
level, general-purpose
programming language.
C is a general-purpose,
procedural computer
programming language.
Speed
Interpreted programs execute
slower as compared to compiled
Compiled programs execute
faster as compared to
2. programs. interpreted programs.
Usage
It is easier to write a code in
Python as the number of lines is
less comparatively.
Program syntax is harder than
Python.
Declaration of variables
There is no need to declare the
type of variable. Variables are
untyped in Python. A given
variable can be stuck on values of
different types at different times
during the program execution
In C, the type of
a variable must be declared
when it is created, and only
values of that type must be
assigned to it.
Error Debugging
Error debugging is simple. This
means it takes only one in
instruction at a time and compiles
and executes simultaneously.
Errors are shown instantly and the
execution is stopped, at that
instruction.
In C, error debugging is
difficult as it is a compiler
dependent language. This
means that it takes the entire
source code, compiles it and
then shows all the errors.
Function renaming
mechanism
Supports function renaming
mechanism i.e, the same function
can be used by two different
names.
C does not support function
renaming mechanism. This
means the same function
cannot be used by two
different names.
Complexity
Syntax of Python programs is
easy to learn, write and read.
The syntax of a C program is
harder than Python.
Memory-management
Python uses an automatic
garbage collector for memory
management.
In C, the Programmer has to
do memory management on
their own.
3. Applications
Python is a General-Purpose
programming language. C is generally used for
hardware related applications.
Built-in functions
Python has a large library of
built-in functions.
C has a limited number of
built-in functions.
Implementing Data
Structures
Gives ease of implementing data
structures with built-in insert,
append functions.
Implementing data
structures requires its
functions to be explicitly
implemented
Pointers
No pointers functionality
available in Python.
Pointers are available in C.
Hello World using C and Python.
#include<stdio.h>
Int main()
{
Printf(“Hello World!n”);
PRINTF(“WE ARE FROM CVR”);
Return 0;
}
Python Code
Just to give you a little excitement about Python, I'm going to give you a small conventional
Python Hello World program.
print("Hello, Python!")
Indentation
Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported,
but the standard indentation requires standard Python code to use four spaces. For example:
x = 1
if x == 1:
# indented four spaces
print("x is 1.")
4. Python Syntax compared to other programming languages
Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.
Applications of Python
As mentioned before, Python is one of the most widely used language over the web. I'm going
to list few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and ported
to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell
scripting.
5. FeaturesofPythonProgrammingLanguage
1. Easy to code
Python is very easy to code. Compared to other popular languages like Java and C++, it is easier
to code in Python. Anyone can learn python syntax in just a few hours. Though sure, mastering
Python requires learning about all its advanced concepts and packages and modules. That takes
time. Thus, it is programmer-friendly.
2. Easy to read
Being a high-level language, Python code is quite like English. Looking at it, you can tell what
the code is supposed to do. Also, since it is dynamically-typed, it mandates indentation. This aids
readability.
3. Expressive
First, let’s learn about expressiveness. Suppose we have two languages A and B, and all
programs that can be made in A can be made in B using local transformations. However, there
are some programs that can be made in B, but not in A, using local transformations. Then, B is
said to be more expressive than A. Python provides us with a myriad of constructs that help us
focus on the solution rather than on the syntax. This is one of the outstanding python features
that tells you why you should learn Python.
4. Free and Open-Source
Firstly, Python is freely available. You can download it from the following link
https://www.python.org/downloads/
For insight on how to download and install Python, refer to our tutorial on Python Installation.
Secondly, it is open-source. This means that its source code is available to the public. You can
download it, change it, use it, and distribute it. This is called FLOSS(Free/Libre and Open
Source Software). As the Python community, we’re all headed toward one goal- an ever-
bettering Python.
5. High-Level
6. As we discussed in point 2b, it is a high-level language. This means that as programmers, we
don’t need to remember the system architecture. Nor do we need to manage the memory. This
makes it more programmer-friendly and is 1 of the key python features. Any doubt yet in the
features of Python. Please ask.
6. Portable
Let’s assume you’ve written a Python code for your Windows machine. Now, if you want to run
it on a Mac, you don’t need to make changes to it for the same. In other words, you can take one
code and run it on any machine, there is no need to write different code for different machines.
This makes Python a portable language. However, you must avoid any system-dependent
features in this case.
7. Interpreted
If you’re any familiar with languages like C++ or Java, you must first compile it, and then run it.
But in Python, there is no need to compile it. Internally, its source code is converted into an
immediate form called bytecode. So, all you need to do is to run your Python code without
worrying about linking to libraries, and a few other things.
By interpreted, we mean the source code is executed line by line, and not all at once. Because of
this, it is easier to debug your code. Also, interpreting makes it just slightly slower than Java, but
that does not matter compared to the benefits it has to offer.
Any doubt or query yet about the features of python programming language? If yes, Drop a
comment and we will get back to you.
8. Object-Oriented
A programming language that can model the real world is said to be object-oriented. It focuses
on objects, and combines data and functions. Contrarily, a procedure-oriented language revolves
around functions, which are code that can be reused. Python supports both procedure-oriented
and object-oriented programming which is one of the key python features. It also supports
multiple inheritance, unlike Java. A class is a blueprint for such an object. It is an abstract data
type, and holds no values.
9. Extensible
If needed, you can write some of your Python code in other languages like C++. This makes
Python an extensible language, meaning that it can be extended to other languages.
10. Embeddable
7. We just saw that we can put code in other languages in our Python source code. However, it is
also possible to put our Python code in a source code in a different language like C++. This
allows us to integrate scripting capabilities into our program of the other language.
11. Large Standard Library
Python downloads with a large library that you can use so you don’t have to write your own code
for every single thing. There are libraries for regular expressions, documentation-generation,
unit-testing, web browsers, threading, databases, CGI, email, image manipulation, and a lot of
other functionality.
12. GUI Programming
GUI or Graphical User Interface is one of the key aspects of any programming language because
it has the ability to add flair to code and make the results more visual. Python has support for a
wide array of GUIs which can easily be imported to the interpreter, thus making this one of the
most favorite languages for developers.
13. Dynamically Typed
Python is dynamically-typed. This means that the type for a value is decided at runtime, not in
advance. This is why we don’t need to specify the type of data while declaring it.
There are two major Python versions, Python 2 and Python 3. Python 2 and 3 are quite different.
We use Python 3, because it is more semantically correct and supports newer features.
For example, one difference between Python 2 and 3 is the print statement. In Python 2, the
"print" statement is not a function, and therefore it is invoked without parentheses. However, in
Python 3, it is a function, and must be invoked with parentheses.
Print a ---- python 2
Print(a) ---- python 3
Python History and Versions
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
8. o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3
Why the Name Python?
There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, short, and little-bit mysterious. So he
decided to select naming Python after the "Monty Python's Flying Circus" for their newly
created programming language.
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, etc.
Python Version List
Python programming language is being updated regularly with new features and supports. There
are lots of update in Python versions, started from 1994 to current release.
A list of Python versions with its released date is given below.
Python Version Released Date
9. Python 1.0 January 1994
Python 1.5 December 31, 1997
Python 1.6 September 5, 2000
Python 2.0 October 16, 2000
Python 2.1 April 17, 2001
Python 2.2 December 21, 2001
Python 2.3 July 29, 2003
Python 2.4 November 30, 2004
Python 2.5 September 19, 2006
Python 2.6 October 1, 2008
Python 2.7 July 3, 2010
Python 3.0 December 3, 2008
Python 3.1 June 27, 2009
Python 3.2 February 20, 2011
Python 3.3 September 29, 2012
10. Python 3.4 March 16, 2014
Python 3.5 September 13, 2015
Python 3.6 December 23, 2016
Python 3.7 June 27, 2018
Python 3.8 October 14, 2019
Tips to Keep in Mind While Learning Python
The most common question asked by the beginners - "What is the best way to learn
Python"? It is the initial and relevant question because first step in learning any programming
language is to know how to learn.
The proper way of learning will help us to learn fast and become a good Python developer.
In this section, we will discuss various tips that we should keep in mind while learning Python.
1. Make it Clear Why We Want to Learn
The goal should be clear before learning the Python. Python is an easy, a vast language as well.
It includes numbers of libraries, modules, in-built functions and data structures. If the goal is
unclear then it will be a boring and monotonous journey of learning Python. Without any clear
goal, you perhaps won't make it done.
So, first figure out the motivation behind learning, which can anything be such as knowing
something new, develop projects using Python, switch to Python, etc. Below are the general
areas where Python is widely used. Pick any of them.
o Data Analysis and Processing
o Artificial Intelligence
o Games
o Hardware/Sensor/Robots
o Desktop Applications
11. Choose any one or two areas according to your interest and start the journey towards learning
Python.
2. Learn the Basic Syntax
It is the most essential and basic step to learn the syntax of the Python programming language.
We have to learn the basic syntax before dive deeper into learning it. As we have discussed in
our earlier tutorial, Python is easy to learn and has a simple syntax. It doesn't use semicolon and
brackets. Its syntax is like the English language.
So it will take minimum amount of time to learning its syntax. Once we get its syntax properly,
further learning will be easier and quicker getting to work on projects.
Note - Learn Python 3, not Python 2.7, because the industry no longer uses it. Our Python
tutorial is based on its latest version Python 3.
3. Write Code by Own
Writing the code is the most effective and robust way to learn Python. First, try to write code on
paper and run in mind (Dry Run) then move to the system. Writing code on paper will help us
get familiar quickly with the syntax and the concept store in the deep memory. While writing the
code, try to use proper functions and suitable variables names.
There are many editors available for Python programming which highlights the syntax related
issue automatically. So we don't need to pay lot of attention of these mistakes.
4. Keep Practicing
The next important step is to do the practice. It needs to implementing the Python concepts
through the code. We should be consistence to our daily coding practice.
Consistency is the key of success in any aspect of life not only in programming. Writing code
daily will help to develop muscle memory.
We can do the problem exercise of related concepts or solve at least 2 or 3 problems of Python. It
may seem hard but muscle memory plays large part in programing. It will take us ahead from
those who believe only the reading concept of Python is sufficient.
5. Make Notes as Needed
Creating notes by own is an excellent method to learn the concepts and syntax of Python. It will
establish stability and focus that helps you become a Python developer. Make brief and concise
notes with relevant information and include appropriate examples of the subject concerned.
Maintain own notes are also helped to learn fast. A study published in Psychological Science that
-
12. The students who were taking longhand notes in the studies were forced to be more selective —
because you can't write as fast as you can type.
6. Discuss Concepts with Other
Coding seems to be solitary activity, but we can enhance our skills by interacting with the others.
We should discuss our doubts to the expert or friends who are learning Python. This habit will
help to get additional information, tips and tricks, and solution of coding problems. One of the
best advantages of Python, it has a great community. Therefore, we can also learn from
passionate Python enthusiasts.
7. Do small Projects
After understanding Python's basic concept, a beginner should try to work on small projects. It
will help to understand Python more deeply and become more component in it. Theoretical
knowledge is not enough to get command over the Python language. These projects can be
anything as long as they teach you something. You can start with the small projects such as
calculator app, a tic-toc-toe game, an alarm clock app, a to-do list, student or customer
management system, etc.
Once you get handy with a small project, you can easily shift toward your interesting domain
(Machine Learning, Web Development, etc.).
8. Teach Others
There is a famous saying that "If you want to learn something then you should teach other".
It is also true in case of learning Python. Share your information to other students via creating
blog posts, recording videos or taking classes in local training center. It will help us to enhance
the understanding of Python and explore the unseen loopholes in your knowledge. If you don't
want to do all these, join the online forum and post your answers on Python related questions.
9. Explore Libraries and Frameworks
Python consists of vast libraries and various frameworks. After getting familiar with Python's
basic concepts, the next step is to explore the Python libraries. Libraries are essential to work
with the domain specific projects. In the following section, we describe the brief introduction of
the main libraries.
o TensorFlow - It is an artificial intelligence library which allows us to create large scale
AI based projects.
o Django - It is an open source framework that allows us to develop web applications. It is
easy, flexible, and simple to manage.
13. o Flask - It is also an open source web framework. It is used to develop lightweight web
applications.
o Pandas - It is a Python library which is used to perform scientific computations.
o Keras - It is an open source library, which is used to work around the neural network.
There are many libraries in Python. Above, we have mentioned a few of them.
10. Contribute to Open Source
As we know, Python is an open source language that means it is freely available for everyone.
We can also contribute to Python online community to enhance our knowledge. Contributing to
open source projects is the best way to explore own knowledge. We also receive the feedback,
comments or suggestions for work that we submitted. The feedback will enable the best practices
for Python programming and help us to become a good Python developer.
Usage of Python
Python is a general purpose, open source, high-level programming language and also provides
number of libraries and frameworks. Python has gained popularity because of its simplicity, easy
syntax and user-friendly environment. The usage of Python as follows.
o Desktop Applications
o Web Applications
o Data Science
o Artificial Intelligence
o Machine Learning
o Scientific Computing
o Robotics
o Internet of Things (IoT)
o Gaming
o Mobile Apps
o Data Analysis and Preprocessing
Python Identifiers, Variables and Keywords
Python Identifiers
14. Python Identifier is the name we give to identify a variable, function, class, module or other
object. That means whenever we want to give an entity a name, that’s called identifier.
Sometimes variable and identifier are often misunderstood as same but they are not.
Python Variables:
A variable in Python represents an entity whose value can change as and when required.
Conceptually, it is a memory location which holds the actual value. And we can retrieve the
value from our code by querying the entity.But for doing it we need to give a nickname to that
memory location so that we can refer to it. That’s identifier, the nickname.
Rules for writing Identifiers and Variables
There are some rules for writing Identifiers. But first you must know Python is case sensitive.
That means Name and name are two different identifiers in Python. Here are some rules for
writing Identifiers in python.
1. Identifiers can be combination of uppercase and lowercase letters, digits or an underscore(_).
So myVariable, variable_1, variable_for_print all are valid python identifiers.
For example – Names like shapeClass, shape_1, and upload_shape_to_db are all
valid identifiers.
var@1 -- invalid
Limit all lines to a maximum of 79 characters.
Though these are hard rules for writing identifiers, also there are some naming conventions
which are not mandatory but rather good practices to follow.
1. Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
2. Starting an identifier with a single leading underscore indicates the identifier is private.
3. If the identifier starts and ends with two underscores, then it means the identifier is language-
defined special name.
4. While c = 10 is valid, writing count = 10 would make more sense and it would be easier to
figure out what it does even when you look at your code after a long time.
5. Multiple words can be separated using an underscore, for example this_is_a_variable.
15. Testing If An Identifier Is Valid.
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier. They are
used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can vary slightly in the course of time.
All the keywords except True, False and None are in lowercase and they must be written as it is.
The list of all the keywords is given below.
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Keywords in Python
16. Basic Data Types:
Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object in
Python programming, data types are actually classes and variables are instance (object) of these
classes.
Following are the standard or built-in data type of python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Numeric
In Python, numeric data type represents the data which has numeric value. Numeric value can be
integer, floating number or even complex numbers. These values are defined
as int, float and complex class in Python.
Type Format Description
17. Type Format Description
int a = 10 Signed Integer
long a = 345L
(L) Long integers, they can also be represented in octal and
hexadecimal
float
a =
45.67
(.) Floating point real values
complex a = 3.14J (J) Contains integer in the range 0 to 255.
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
18. print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Complex Numbers – Complex number is represented by complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Explicit Type Conversion
Example
Convert from one type to another:
19. x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x) ---- 1.0
#convert from float to int:
b = int(y) --- 2
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Implicit Type Conversion
a = 10
b = 3.4
c = a+b
print(type(c))
output: Class Float
20. Boolean Data Type
The boolean data type is either True or False. In Python, boolean variables are defined by
the True and False keywords.
>>> a = True
>>> type(a)
<class 'bool'>
>>> b = False
>>> type(b)
<class 'bool'>
The output <class 'bool'> indicates the variable is a boolean data type.
Note the keywords True and False must have an Upper Case first letter. Using a
lowercase true returns an error.
21. >>> c = true
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'true' is not defined
>>> d = false
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'false' is not defined
Integers and Floats as Booleans
Integers and floating point numbers can be converted to the boolean data type using
Python's bool() function. An int, float or complex number set to zero returns False. An integer,
float or complex number set to any other number, positive or negative, returns True.
>>>zero_int = 0
>>> bool(zero_int)
False
>>>pos_int = 1
>>> bool(pos_int)
True
>>>neg_flt = -5.1
>>> bool(neg_flt)
True
What are operators in python?
Operators are special symbols in Python that carry out arithmetic or logical computation. The
value that the operator operates on is called the operand.
For example:
>>>2+3
5
Arithmetic operators
22. Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
Operator Meaning Example
+ Add two operands or unary plus x + y+ 2
- Subtract right operand from the left or unary minus x - y- 2
* Multiply two operands x * y
/ Divide left operand by the right one (always results into float) x / y
%
Modulus - remainder of the division of left operand by the
right
x % y (remainder
of x/y)
//
Floor division - division that results into whole number
adjusted to the left in the number line
x // y
** Exponent - left operand raised to the power of right
x**y (x to the
power y)
Example 1: Arithmetic operators in Python
x = 15
y = 4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
23. print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
Run Code
Output
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Comparison operators
Comparison operators are used to compare values. It returns either True or False according to
the condition.
Operator Meaning Example
> Greater than - True if left operand is greater than the right x > y
< Less than - True if left operand is less than the right x < y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
24. >=
Greater than or equal to - True if left operand is greater than or equal to
the right
x >= y
<=
Less than or equal to - True if left operand is less than or equal to the
right
x <= y
Example 2: Comparison operators in Python
x = 10
y = 12
!
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
Run Code
Output
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
25. Logical operators
Logical operators are the and, or, not operators.
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x
Example 3: Logical Operators in Python
x = True
y = False
print('x and y is',xand y)
print('x or y is',xor y)
print('not x is',not x)
Run Code
Output
x and y is False
x or y is True
not x is False
Here is the truth table for these operators.
Bitwise operators
26. Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit,
hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)
Assignment operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the
left.
There are various compound operators in Python like a += 5 that adds to the variable and later
assigns the same. It is equivalent to a = a + 5.
27. Special operators
Python language offers some special types of operators like the identity operator or the
membership operator. They are described below with examples.
Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does not
imply that they are identical.
Membership operators
in and not in are the membership operators in Python. They are used to test whether a value or
variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x
Example #5: Membership operators in Python
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H'in x)
# Output: True
print('hello'notin x)
# Output: True
print(1in y)
28. # Output: False
print('a'in y)
Run Code
Output
True
True
True
False
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
Reading data dynamically from user:
Syntax: X = input(“msg”)
Ex: x = input(“Enter the value of x”)
How print() works in Python?
1)
print("Python is fun.")
a = 5
# Two objects are passed
print("a =", a)
b = a
# Three objects are passed
print('a =', a, '= b')
Output:
When you run the program, the output will be:
Python is fun.
29. a = 5
a = 5 = b
The sep parameter when used with end parameter it produces awesome results. Some examples
by combining the sep and end parameter.
We passed the sep and end parameters in the above program.
Different types of print options: Formatting output using % and {}
name = ‘jhon’
age = 25
sal = 25325.5
#Approach 1
Print(name,age,sal)
Output:jhon 25 25325.5
#Approach 2
Print(‘Name is:’,name)
Print(‘Age is:’,age)
Print(‘Salary is:’,sal)
Output:Name is john
Age is 25
30. Salary is 25325.5
Output:Name:john Age:25 Salary:25325.5
Strings
String Literals
Strings are sequences of character data. The string type in Python is called str.
String literals may be delimited using either single or double quotes. All the characters between
the opening delimiter and matching closing delimiter are part of the string:
print("Hello")
print('Hello')
print("I am a string.")
I am a string.
type("I am a string.")
<class 'str'>
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:
a= "Hello"
print(a)
A string in Python can contain as many characters as you wish. The only limit is your machine’s
memory resources.
A string can also be empty:
A = ''''
What if you want to include a quote character as part of the string itself? Your first impulse
might be to try something like this:
>>>print('This string contains a single quote (')character.')
SyntaxError: invalid syntax
31. If you want to include either type of quote character within the string, the simplest way is to
delimit the string with the other type. If a string is to contain a single quote, delimit it with
double quotes and vice versa:
>>>print("This string contains a single quote (') character.")
This string contains a single quote (') character.
>>>print('This string contains a double quote (") character.')
This string contains a double quote (") character.
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consecteturadipiscingelit,
sed do eiusmodtemporincididunt
utlabore et dolore magna aliqua."""
print(a)
Or three single quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consecteturadipiscingelit,
sed do eiusmodtemporincididunt
utlabore et dolore magna aliqua.'''
print(a)
Escape Sequences in Strings
If a string is delimited by single quotes, you can’t directly specify a single quote character as part
of the string because, for that string, the single quote has special meaning—it terminates the
string:
>>>print('This string contains a single quote (') character.')
32. SyntaxError: invalid syntax
Specifying a backslash in front of the quote character in a string “escapes” it and causes Python
to suppress its usual special meaning. It is then interpreted simply as a literal single quote
character:
>>>print('This string contains a single quote (') character.')
This string contains a single quote (') character.
The same works in a string delimited by double quotes as well:
>>>print("This string contains a double quote (") character.")
This string contains a double quote (") character.
The following is a table of escape sequences which cause Python to suppress the usual special
interpretation of a character in a string:
Escape
Sequence
Usual Interpretation of
Character(s) After Backslash “Escaped” Interpretation
' Terminates string with single quote opening delimiter Literal single quote (') character
" Terminates string with double quote opening delimiter Literal double quote (") character
newline Terminates input line Newline is ignored
Introduces escape sequence Literal backslash () character
Ordinarily, a newline character terminates line input. So pressing Enter in the middle of a string
will cause Python to think it is incomplete:
>>>print('a
SyntaxError: EOL while scanning string literal
To break up a string over more than one line, include a backslash before each newline, and the
newlines will be ignored:
>>>print('a
... b
... c')
abc
To include a literal backslash in a string, escape it with a backslash:
>>> print('foobar')
foobar
33. Applying Special Meaning to Characters
Next, suppose you need to create a string that contains a tab character in it. Some text editors
may allow you to insert a tab character directly into your code. But many programmers consider
that poor practice, for several reasons:
The computer can distinguish between a tab character and a sequence of space characters,
but you can’t. To a human reading the code, tab and space characters are visually
indistinguishable.
Some text editors are configured to automatically eliminate tab characters by expanding
them to the appropriate number of spaces.
Some Python REPL environments will not insert tabs into code.
In Python (and almost all other common computer languages), a tab character can be specified
by the escape sequence t:
>>>print('footbar')
foo bar
The escape sequence t causes the t character to lose its usual meaning, that of a literal t. Instead,
the combination is interpreted as a tab character.
Here is a list of escape sequences that cause Python to apply special meaning instead of
interpreting literally: Examples:
>>>print("atb")
a b
>>>print("anb")
a
b
Triple-Quoted Strings
There is yet another way of delimiting strings in Python. Triple-quoted strings are delimited by
matching groups of three single quotes or three double quotes. Escape sequences still work in
triple-quoted strings, but single quotes, double quotes, and newlines can be included without
escaping them. This provides a convenient way to create a string with both single and double
quotes in it:
>>>print('''This string has a single (') and a double (") quote.''')
This string has a single (') and a double (") quote.
Because newlines can be included without escaping them, this also allows for multiline strings:
>>>print("""This is a
34. string that spans
across several lines""")
This is a
string that spans
across several lines
You will see in the upcoming tutorial on Python Program Structure how triple-quoted strings can
be used to add an explanatory comment to Python code.
Python: String Methods (Built-in)
String methods are working on the string its called from, if you have a string called, string =
"Hello World", then the string method is called such this: string.string_method()
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a
length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1]) -- e
Accessing characters in Python- String Indexing
In Python, individual characters of a String can be accessed by using the method of
Indexing.
Indexing allows negative address references to access characters from the back of the
String, e.g. -1 refers to the last character, -2 refers to the second last character and so on.
While accessing an index out of the range will cause an IndexError.
Only Integers are allowed to be passed as an index, float or other types will cause
a TypeError.
35. C V R C O E
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
A[5] = E
A[8] – index error
A[a] – Type error
Python program on indexing:
str1 = "software engineer"
print('First character of string is',str1[0])
print('Last character of string is',str1[-1])
print('fifth character of string is',str1[4])
print('Last fifth character of string is',str1[-5])
print(len(str1))
print('Character of string at 18th position is',str1[18])
Output:
====== RESTART: E:/Bhavani/Bhavani/Subjects/Python/Programs/strings.py ======
First character of string is s
Last character of string is r
fifth character of string is w
Last fifth character of string is i
17
Traceback (most recent call last):
36. File "E:/Bhavani/Bhavani/Subjects/Python/Programs/strings.py", line 13, in <module>
print('Character of string at 18th position is',str1[18])
IndexError: string index out of range
Attempting to index more than the length of the string will give “string index out of
range” error.
Str1 = “hello”
Print(len(str1) --- 5
Print(str1.count(‘l’)) -- 2
String Slicing
Python also allows a form of indexing syntax that extracts substrings from a string, known as
string slicing. S = “COLLEGE”
S1 = S[2:5] ---- LLE
If s is a string, an expression of the form s[m:n] returns the portion of s starting with
position m, and up to but not including position n:
Example:
print('substring of the given string is',str1[3:7])
output: substring of the given string is twar
The expression s[m:n] will return a substring that is n - m characters in length, in this
case, 7 - 3 = 4.
If we omit the first index, the slice starts at the beginning of the string.
Thus, s[:n] and s[0:n] are equivalent:
Example:
print('substring of the given string is',str1[:5])
output: substring of the given string is softw
OR
print('substring of the given string is',str1[0:5])
output: substring of the given string is softw
37. Similarly, if you omit the second index as in s[n:], the slice extends from the first index
through the end of the string. This is a nice, concise alternative to the more
cumbersome s[n:len(s)]:
S[n:-1]
S[:] --- ?
Example:
print('substring of the given string is',str1[0:])
OR
print('substring of the given string is',str1[0:len(str1)])
Output: substring of the given string is software engineer
Omitting both indices returns the original string, in its entirety. Literally. It’s not a copy,
it’s a reference to the original string:
Example:
print('substring of the given string is',str1[:])
Output: substring of the given string is software engineer
If the first index in a slice is greater than or equal to the second index, Python returns an
empty string.
Example:
print('substring of the given string is',str1[2:2])
print('substring of the given string is',str1[4:2])
Output: substring of the given string is
substring of the given string is
Negative indices can be used with slicing as well. -1 refers to the last character, -2 the
second-to-last, and so on, just as with simple indexing.
Example:
print('substring of the given string is',str1[-7:-3])
38. It will returns -3-(-7) = -3+7 = 4 characters from last 7th
character in the string.
Output: substring of the given string is ngin
S[m:n]
Specifying a Stride in a String Slice:
There is one more variant of the slicing syntax to discuss. Adding an additional : and a third
index designates a stride (also called a step), which indicates how many characters to jump after
retrieving each character in the slice.
Example:
print('String stride example',str1[1:8:2])
Output: String stride example otae
You can specify a negative stride value as well, in which case Python steps backward
through the string. In that case, the starting/first index should be greater than the
ending/second index:
Example:
print('String stride example',str1[-8:-1:2])
Output: String stride example egne
Interpolating Variables into a String
This is formally named the Formatted String Literal, but is more usually referred to by its
nickname f-string.
n = 20
>>> m = 25
>>> prod = n * m
>>>print('The product of', n, 'and', m, 'is', prod)
The product of 20 and 25 is 500
But this is cumbersome. To accomplish the same thing using an f-string:
Specify either a lowercase f or uppercase F directly before the opening quote of the string
literal. This tells Python it is an f-string instead of a standard string.
39. Specify any variables to be interpolated in curly braces ({}).
Recast using an f-string, the above example looks much cleaner:
>>> n = 20
>>> m = 25
>>> prod = n * m
>>>print(f'The product of {n} and {m} is {prod}')
>>>print(‘The product of {} and {} is {}’.format(n,m,prod))
The product of 20 and 25 is 500
The product of 20 and 25 is 500
Example:
String1 = "{} {} {}".format('cvr', 'Engineering', 'College')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('cvr', 'Engineering', 'College')
print("nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g = 'cvr', f = ' Engineering ', l = ' College ')
print("nPrint String in order of Keywords: ")
print(String1)
Output:
Print String in default order:
cvr Engineering Collge
Print String in Positional order:
Engineering cvr Collge
Print String in order of Keywords:
College Engineering cvr
40. Formatting output using % and {}
name = ‘jhon’
age = 25
sal = 25325.5
#Approach 1
Print(name,age,sal)
Output:jhon 25 25325.5
Manipulating Strings: (Using string Operators)
One way to manipulate strings is by using string operators. These operators are represented by
symbols that you likely associate with mathematics, such as +, -, *, /, and =. When used with
strings, they perform actions that are similar to, but not the same as, their mathematical
counterparts.
Concatenate
This term means to join strings together. The process is known as concatenating strings and it is
done using the plus (+) operator. Note that you must be explicit about where you want blank
spaces to occur by placing them between single quotation marks also.
In this example, the string “message1” is given the content “hello world”.
message1='hello'+' '+'world'
print(message1)
->helloworld
Multiply
If you want multiple copies of a string, use the multiplication (*) operator. In this example,
string message2a is given the content “hello” times three; string message 2b is given content
“world”; then we print both strings.
message2a='hello '*3
message2b='world'
print(message2a+message2b)
->hellohellohelloworld
Append
What if you want to add material to the end of a string successively? There is a special operator
for that (+=).
41. message3='howdy'
message3+=' '
message3+='world'
print(message3)
->howdyworld
How to change or delete a string?
Strings are immutable. This means that elements of a string cannot be changed once it has been
assigned. We can simply reassign different strings to the same name.
1. >>>my_string='computer science'
2. >>>my_string[5]='a'
3. ...
4. TypeError:'str'object does not support item assignment
5. >>>my_string='Python'
6. >>>my_string
7. 'Python'
We cannot delete or remove characters from a string. But deleting the string entirely is possible
using the keyword del.
1. >>>delmy_string[1]
2. ...
3. TypeError:'str'object doesn't support item deletion
4. >>> del my_string
5. >>>my_string
6. ...
7. NameError: name 'my_string' is not defined
String Membership Test
Membership (In)
This operator returns ‘True’ value if the character is present in the given String.
# example
var1 ='Python'
print('n'in var1)
# True
Membership (Not In)
It returns ‘True’ value if the character is not present in the given String.
42. # example
var1 ='Python'
print('N'notin var1)
# True
Built-In String Functions In Python
Conversion Functions
1. capitalize() – Returns the string with the first character capitalized and rest of the characters in
lower case.
var='PYTHON'
print(var.capitalize())
# Python
2. lower() – Converts all the characters of the String to lowercase
var='TechBeamers'
print(var.lower())
# techbeamers
3. upper() – Converts all the characters of the String to uppercase
var='TechBeamers'
print(var.upper())
# TECHBEAMERS
4. swapcase() – Swaps the case of every character in the String means that lowercase characters
got converted to uppercase and vice-versa.
var='TechBeamers'
print(var.swapcase())
# tECHbEAMERS
5. title() – Returns the ‘titlecased’ version of String, which means that all words start with
uppercase and the rest of the characters in words are in lowercase.
var='welcome to Python programming'
print(var.title())
# Welcome To Python Programming
6. count( str[, beg [, end]]) – Returns the number of times substring ‘str’ occurs in the range
[beg, end] if beg and end index are given else the search continues in full String Search is case-
sensitive.
43. var='TechBeamers'
str='e'
print(var.count(str))
# 3
var1='Eagle Eyes'
print(var1.count('e'))
# 2
var2='Eagle Eyes'
print(var2.count('E',0,5))
# 1
Comparison Functions – Part1
1. islower() – Returns ‘True’ if all the characters in the String are in lowercase. If any of the char
is in uppercase, it will return False.
var='Python'
print(var.islower())
# False
var='python'
print(var.islower())
# True
2. isupper() – Returns ‘True’ if all the characters in the String are in uppercase. If any of the
char is in lowercase, it will return False.
var='Python'
print(var.isupper())
# False
var='PYTHON'
print(var.isupper())
# True
3. isdecimal() – Returns ‘True’ if all the characters in String are decimal. If any character in the
String is of other data-type, it will return False.
Decimal characters are those from the Unicode category Nd.
num=u'2016'
print(num.isdecimal())
# True
44. 4. isdigit() – Returns ‘True’ for any char for which isdecimal() would return ‘True and some
characters in the ‘No’ category. If there are any characters other than these, it will return False’.
Precisely, digits are the characters for which Unicode property includes: Numeric_Type=Digit or
Numeric_Type=Decimal.
For example, superscripts are digits, but fractions not.
print('2'.isdigit())
# True
print('²'.isdigit())
# True
Comparison Functions – Part2
1. isnumeric() – Returns ‘True’ if all the characters of the Unicode String lie in any one of the
categories Nd, No, and NI.
If there are any characters other than these, it will return False.
Precisely, Numeric characters are those for which Unicode property includes:
Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
num=u'2016'
print(num.isnumeric())
# True
num=u'year2016'
print(num.isnumeric())
# False
2. isalpha() – Returns ‘True’ if String contains at least one character (non-empty String), and all
the characters are alphabetic, ‘False’ otherwise.
print('python'.isalpha())
# True
print('python3'.isalpha())
# False
3. isalnum() – Returns ‘True’ if String contains at least one character (non-empty String), and all
the characters are either alphabetic or decimal digits, ‘False’ otherwise.
print('python'.isalnum())
# True
45. print('python3'.isalnum())
# True
Padding Functions
1. rjust(width[,fillchar]) – Returns string filled with input char while pushing the original
content on the right side.
By default, the padding uses a space. Otherwise, ‘fillchar’ specifies the filler character.
var='Python'
print(var.rjust(10))
# Python
print(var.rjust(10,'-'))
# ----Python
2. ljust(width[,fillchar]) – Returns a padded version of String with the original String left-
justified to a total of width columns
By default, the padding uses a space. Otherwise, ‘fillchar’ specifies the filler character.
var='Python'
print(var.ljust(10))
# Python
print(var.ljust(10,'-'))
# Python----
3. center(width[,fillchar]) – Returns string filled with the input char while pushing the original
content into the center.
By default, the padding uses a space. Otherwise, ‘fillchar’ specifies the filler character.
var='Python'
print(var.center(20))
# Python
print(var.center(20,'*'))
# *******Python*******
4. zfill(width) – Returns string filled with the original content padded on the left with zeros so
that the total length of String becomes equal to the input size.
If there is a leading sign (+/-) present in the String, then with this function, padding starts after
the symbol, not before it.
46. var='Python'
print(var.zfill(10))
# 0000Python
var='+Python'
print(var.zfill(10))
# +000Python
Search Functions
1. find(str [,i [,j]]) – Searches for ‘str’ in complete String (if i and j not defined) or in a sub-
string of String (if i and j are defined).This function returns the index if ‘str’ is found else returns
‘-1’.
Here, i=search starts from this index, j=search ends at this index.
var="Tech Beamers"
str="Beam"
print(var.find(str))
# 5
var="Tech Beamers"
str="Beam"
print(var.find(str,4))
# 5
var="Tech Beamers"
str="Beam"
print(var.find(str,7))
# -1
2. index(str) – This is same as ‘find’ method. The only difference is that it raises the
‘ValueError’ exception if ‘str’ doesn’t exist.
var='Tech Beamers'
str='Beam'
print(var.index(str))
# 5
var='Tech Beamers'
str='Beam'
print(var.index(str,4))
# 5
var='Tech Beamers'
47. str='Beam'
print(var.index(str,7))
# ValueError: substring not found
3. rfind(str[,i [,j]]) – This is same as find() just that this function returns the last index where
‘str’ is found. If ‘str’ is not found, it returns ‘-1’.
var='This is a good example'
str='is'
print(var.rfind(str,0,10))
# 5
Print(var.find(str,0,10)) ---- #2
print(var.rfind(str,10))
# -1
4. count(str[,i [,j]]) – Returns the number of occurrences of substring ‘str’ in the String.
Searches for ‘str’ in the complete String (if i and j not defined) or in a sub-string of String (if i
and j are defined).
Where: i=search starts from this index, j=search ends at this index.
var='This is a good example'
str='is'
print(var.count(str))
# 2
print(var.count(str,4,10))
# 1
String Substitution Functions
1. replace(old,new[,count]) – Replaces all the occurrences of substring ‘old’ with ‘new’ in the
String.
If the count is available, then only ‘count’ number of occurrences of ‘old’ will be replaced with
the ‘new’ var.
Where old =substring to replace, new =substring
var='This is a good example'
str='was'
print(var.replace('is',str))
# Thwas was a good exampleprint (var.replace('is',str,1))
# Thwas is a good example
48. 2. split([sep[,maxsplit]]) – Returns a list of substring obtained after splitting the String with
‘sep’ as a delimiter.
Where, sep= delimiter, the default is space, maxsplit= number of splits to be done
var="This is a good example"
print(var.split())
# ['This', 'is', 'a', 'good', 'example']
print (var.split(' ', 3))
# ['This', 'is', 'a', 'good example']
3. splitlines(num) – Splits the String at line breaks and returns the list after removing the line
breaks.
Where num = if this is a positive value. It indicates that line breaks will appear in the returned
list.
var='Print new linenNextlinennMove again to new line'
print(var.splitlines())
# ['Print new line', 'Nextline', '', 'Move again to new line']print (var.splitlines(1))
# ['Print new linen', 'Nextlinen', 'n', 'Move again to new line']
4. join(seq) – Returns a String obtained after concatenating the sequence ‘seq’ with a delimiter
string.
Where: the seq= sequence of elements to join
seq=('ab','bc','cd')
str='='
print(str.join(seq))
print(‘@’.join(seq))
print(‘ ‘.join(seq))
ab bc cd
ab@bc@cd
# ab=bc=cd
Misc String Functions
1. lstrip([chars]) – Returns a string after removing the characters from the beginning of the
String.
Where: Chars=this is the character to be trimmed from the String.
The default is whitespace character.
49. var=' This is a good example '
print(var.lstrip())
# This is a good example
var='*****This is a good example*****'
print(var.lstrip('*'))
# This is a good example**********
2. rstrip() – Returns a string after removing the characters from the End of the String.
Where: Chars=this is the character to be trimmed from the String. The default is whitespace
character.
var=' This is a good example '
print(var.rstrip())
# This is a good example
var='*****This is a good example*****'
print(var.rstrip('*'))
# *****This is a good example
3. rindex(str[,i [,j]]) – Searches for ‘str’ in the complete String (if i and j not defined) or in a
sub-string of String (if i and j are defined). This function returns the last index where ‘str’ is
available.
If ‘str’ is not there, then it raises a ValueError exception.
Where: i=search starts from this index, j=search ends at this index.
var='This is a good example'
str='is'
print(var.rindex(str,0,10))
# 5
print(var.rindex(str,10))
# ValueError: substring not found
4. len(string) – Returns the length of given String
var='This is a good example'
print(len(var))
# 22
Built-In Functions
Math
Function Description
50. Function Description
abs() Returns absolute value of a number
divmod() Returns quotient and remainder of integer division
max() Returns the largest of the given arguments or items in an iterable
min() Returns the smallest of the given arguments or items in an iterable
pow() Raises a number to a power
round() Rounds a floating-point value
sum() Sums the items of an iterable
Functions
In Python, a function is a group of related statements that performs a specific task. A function is
a block of organized, reusable code that is used to perform a single, related action. Functions
provide better modularity for our application and a high degree of code reusing.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
# C function syntax:
int func_name(int,int)
{
Body of the func;
Return a;
}
51. Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
returnAbove shown is a function definition that consists of the following components.
1. Keyword def that marks the start of the function header.
2. A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
How to call a function in python?
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.!
Note: Try running the above code in the Python program with the function definition to see the
output.
Docstrings
52. The first string after the function header is called the docstring and is short for documentation
string. It is briefly used to explain what a function does.
Although optional, documentation is a good programming practice. Unless you can remember
what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally
use triple quotes so that docstring can extend up to multiple lines. This string is available to us as
the __doc__ attribute of the function.
The return statement:
The return statement is used to exit a function and go back to the place from where it was called.
Syntax of return
This statement can contain an expression that gets evaluated and the value is returned. If there is
no expression in the statement or the return statement itself is not present inside a function, then
the function will return the None object.
Here, None is the returned value since greet() directly prints the name and no return statement is
used.
def add1(x,y):
z = x + y
return z
a = int(input(“Enter the first numbern”))
b = int(input(“Enter the second numbern”))
53. c = add1(a,b)
print(“The addition of 2 numbers is “, c)
How Function works in Python?
Working of functions in Python
Scope and Lifetime of variables:
Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function are not visible from outside the function. Hence, they have a
local scope.
The lifetime of a variable is the period throughout which the variable exits in the memory. The
lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
54. Types of Functions:
There are three types of functions in Python:
Built-in functions, such as help() to ask for help, min() to get the minimum
value, print() to print an object to the terminal.
User-Defined Functions (UDFs), which are functions that users create to help them out;
And
Anonymous functions, which are also called lambda functions because they are not
declared with the standard def keyword.
Functions vs Methods
A method refers to a function which is part of a class. You access it with an instance or object of
the class. A function doesn’t have this restriction: it just refers to a standalone function. This
means that all methods are functions, but not all functions are methods.
Creating a Function:
Syntax:
def function_name(parameters):
"""docstring"""
statement(s)
int func_name(parameters)
{
}
Example:
def my_function():
print("Hello from a function")
55. Above shown is a function definition which consists of following components.
1. Keyword def marks the start of function header.
2. A function name should be unique to identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must have
same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Calling a Function:
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments. Arguments are specified after the
function name, inside the parentheses. You can add as many arguments as you want, just
separate them with a comma.
The following example has a function with one argument (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:
defgreet(): ---- 0 Arguments-----
print(“Good morning”)
greet()
def full_name(x); ---- 1 Argument ----
print(“The full name is”,x)
full_name(“cvr”)
56. Example with 2 arguments:
def sum1(a,b):
c = a+b
print("The sum is ",c)
n1 = 10
n2 = 20
sum1(n1,n2)
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed
into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that are sent to the function when it is called.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.
Function Arguments in Python
There are four types of arguments that Python UDFs can take:
Default arguments
Required arguments
Keyword arguments
Variable number of arguments
Default Arguments
Default arguments are those that take a default value if no argument value is passed during the
function call. You can assign this default value by with the assignment operator =, just like in the
following example:
57. # Define `plus()` function
def plus(a,b= 2):
return a + b
# Call `plus()` with only `a` parameter
C = plus(1)--- 3
# Call `plus()` with `a` and `b` parameters
C = plus(1, 3) --- 4
Required Arguments
As the name kind of gives away, the required arguments of a UDF are those that have to be in
there. These arguments need to be passed during the function call and in precisely the right order,
just like in the following example:
# Define `plus()` with required arguments
def plus(a,b):
return a + b
c = plus(1) --- error
c = plus(1,2) --- returns 3 as output
c = plus(1,2,3) ---- error
Keyword Arguments
If you want to make sure that you call all the parameters in the right order, you can use the
keyword arguments in your function call. You use these to identify the arguments by their
parameter name. Let’s take the example from above to make this a bit more clear:
# Define `plus()` function
def plus(a,b):
return a + b
# Call `plus()` function with parameters
C = plus(2,3)
# Call `plus()` function with keyword arguments
Print(plus(a=1, b=2))
Print(plus(b=2, a=1))
58. both can be used
Variable Number of Arguments
In cases where you don’t know the exact number of arguments that you want to pass to a
function, you can use the following syntax with *args:
# Define `plus()` function to accept a variable number of arguments
def plus(*args):
return sum(args)
# Calculate the sum
C = plus(1,4,5) --- 10
C = plus(1,4) --- 5
C = plus(4,6,8,9,1) --- 28
The asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. Note here that you might as well have passed *varint, *var_int_args or any
other name to the plus() function.
You see that the above function makes use of the built-in Python sum() function to sum all the
arguments that get passed to plus(). If you would like to avoid this and build the function entirely
yourself, you can use this alternative:
# Define `plus()` function to accept a variable number of arguments
def plus(*args):
total = 0
for i in args:
total += i
return total
# Calculate the sum
C = plus(20,30,40,50)
C = plus(40,50)
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your function, add
two asterix: ** before the parameter name in the function definition.
59. This way the function will receive a dictionary of arguments, and can access the items
accordingly:
If the number of keyword arguments is unknown, add a double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Global vs Local Variables
In general, variables that are defined inside a function body have a local scope, and those defined
outside have a global scope. That means that local variables are defined within a function block
and can only be accessed inside that function, while global variables can be obtained by all
functions that might be in your script:
# Global variable `init`
init = 1
# Define `plus()` function to accept a variable number of arguments
def plus(*args):
# Local variable `sum()`
total = 0
for i in args:
total += i
return total
# Access the global variable
print("this is the initialized value " + str(init))
# (Try to) access the local variable
print("this is the sum " + str(total))
Anonymous Functions in Python
Anonymous functions are also called lambda functions in Python because instead of declaring
them with the standard def keyword, you use the lambda keyword.
60. A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax:
The formal syntax to write a lambda function is as given below:
lambda p1, p2: expression
Here, p1 and p2 are the parameters which are passed to the lambda function. You can add as
many or few parameters as you need.
However, notice that we do not use brackets around the parameters as we do with regular
functions. The last part (expression) is any valid python expression that operates on the
parameters you provide to the function.
Why to use lambda functions:
Lambda functions are used when you need a function for a short period of time. This is
commonly used when you want to pass a function as an argument to higher-order functions, that
is, functions that take other functions as their arguments.
Example 1:
x = lambda a : a + 10
print(x(5))
Output:
15
Lambda functions can take any number of arguments:
Example 2:
x = lambda a, b : a * b
print(x(5, 6))
Output:
30
A lambda function that sums argument a, b, and c and print the result:
61. As we can see in the above example both the cube() function and lambda_cube() function
behave the same and as intended. Let’s analyze the above example a bit more:
Without using Lambda: Here, both of them return the cube of a given number.
But, while using def, we needed to define a function with a name cube and needed
to pass a value to it. After execution, we also needed to return the result from where
the function was called using the return keyword.
Using Lambda: Lambda definition does not include a “return” statement, it always
contains an expression that is returned. We can also put a lambda definition
anywhere a function is expected, and we don’t have to assign it to a variable at all.
This is the simplicity of lambda functions.
We use anonymous functions when you require a nameless function for a short period of time,
and that is created at runtime. Specific contexts in which this would be relevant is when you’re
working with filter(), map() and reduce():
Lambda with reduce():
The reduce() function in Python takes in a function and a list as an argument. The function is
called with a lambda function and an iterable and a new reduced result( a single value) is
returned. This performs a repetitive operation over the pairs of the iterable. The reduce()
function belongs to the functools module.
Example: When we want to find the sum or product of all the elements of the list.
Syntax:
reduce(function, iterables) # iterables are nothing but which can be loop over
Examples of iterables: list, range(), tuple, string, etc.,
It can take, only one iterable.
from functools import reduce
my_list = [1,2,3,4,5,6,7,8,9,10]
# Use lambda function with `filter()`
filtered_list = list(filter(lambda x: (x*2 > 10), my_list))
# Use lambda function with `map()`
mapped_list = list(map(lambda x: x*2, my_list))
62. # Use lambda function with `reduce()`
reduced_list = reduce(lambda x, y: x+y, my_list)
print(filtered_list)
print(mapped_list)
print(reduced_list)
Output:
[6, 7, 8, 9, 10]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
55
Passing a List as an Argument
You can send any data types as argument to a function (string, number, list, dictionary etc.), and
it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
def namesfunc(list1):
for i in list1:
print(i)
nameslist = ['bhavani','akki','anu','sai']
namesfunc(nameslist)
Output:
bhavani
akki
anu
sai
The pass Statement
function definitions cannot be empty, but for some reason, if we have a function definition with
no content, put in the pass statement to avoid getting an error.
def myfunction():
pass
Modules in Python
63. Modules refer to a file containing Python statements and definitions.
A file containing Python code, for example: example.py, is called a module, and its module
name would be example.
We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
Let us create a module. Type the following and save it as example.py.
# Python Module example
defadd(a, b):
"""This program adds two
numbers and return the result"""
result = a + b
return result
Here, we have defined a function add() inside a module named example. The function takes in
two numbers and returns their sum.
Importing modules in Python
We can import the definitions inside a module to another module or the interactive interpreter in
Python.
We use the import keyword to do this. To import our previously defined module example, we
type the following in the Python prompt.
>>>import example
64. This does not import the names of the functions defined in example directly in the current
symbol table. It only imports the module name example there.
Using the module name we can access the function using the dot . operator. For example:
>>>example.add(4,5.5)
9.5
Python has tons of standard modules. You can check out the full list of Python standard
modules and their use cases. These files are in the Lib directory inside the location where you
installed Python.
Standard modules can be imported the same way as we import our user-defined modules.
There are various ways to import modules. They are listed below..
Python import statement
We can import a module using the import statement and access the definitions inside it using the
dot operator as described above. Here is an example.
# import statement example
# to import standard module math
import math
print("The value of pi is", math.pi)
When you run the program, the output will be:
The value of pi is 3.141592653589793
Import with renaming
We can import a module by renaming it as follows:
# import module by renaming it
65. import math as m
print("The value of pi is", m.pi)
We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid, and m.pi is
the correct implementation.
Python from...import statement
We can import specific names from a module without importing the module as a whole. Here is
an example.
# import only pi from math module
from math import pi
print("The value of pi is", pi)
Here, we imported only the pi attribute from the math module.
In such cases, we don't use the dot operator. We can also import multiple attributes as follows:
>>>from math import pi, e
>>>pi
3.141592653589793
>>>e
2.718281828459045
What is math module in Python?
The math module is a standard module in Python and is always available. To use mathematical
functions under this module, you have to import the module using import math.
It gives access to the underlying C library functions. For example,
# Square root calculation
66. import math
math.sqrt(4)
This module does not support complex datatypes. The cmath module is the complex counterpart.
Python - OS Module
It is possible to automatically perform many operating system tasks. The OS module in
Python provides functions for creating and removing a directory (folder), fetching its
contents, changing and identifying the current directory, etc.
You first need to import the os module to interact with the underlying operating system. So,
import it using the
import os
statement before using its functions.
Getting Current Working Directory
The getcwd() function confirms returns the current working directory.
Example: Get Current Working Directory
>>>importos
>>>os.getcwd()
'C:Python37'
Creating a Directory
We can create a new directory using the os.mkdir() function, as shown below.
Example: Create a Physical Directory
>>>importos
>>>os.mkdir("C:MyPythonProject")
>>>os.mkdir(“My sample file”)
67. A new directory corresponding to the path in the string argument of the function will be
created. If you open the C: drive, then you will see the MyPythonProject folder has been
created.
By default, if you don't specify the whole path in the mkdir() function, it will create the
specified directory in the current working directory or drive. The following will
create MyPythonProject in the C:Python37 directory.
Example: Create a Physical Directory
>>>importos
>>>os.getcwd()
'C:Python37'
>>>os.mkdir("MyPythonProject")
Changing the Current Working Directory
We must first change the current working directory to a newly created one before doing any
operations in it. This is done using the chdir() function. The following change current working
directory to C:MyPythonProject.
Example: Change Working Directory
>>>importos
>>>os.chdir("C:MyPythonProject")# changing current working directory
>>>os.getcwd()
'C:MyPythonProject'
You can change the current working directory to a drive. The following makes the C: drive as
the current working directory.
Example: Change Directory to Drive
>>>os.chdir("C:")
>>>os.getcwd()
'C:'
In order to set the current directory to the parent directory use ".." as the argument in
the chdir() function.
Example: Change CWD to Parent
>>>os.chdir("C:MyPythonProject")
68. >>>os.getcwd()
'C:MyPythonProject'
>>>os.chdir("..")
>>>os.getcwd()
'C:'
Removing a Directory
The rmdir() function in the OS module removes the specified directory either with an absolute
or relative path. Note that, for a directory to be removed, it should be empty.
Example: Remove Directory
>>>importos
>>>os.rmdir("C:MyPythonProject")
However, you cannot remove the current working directory. To remove it, you must change
the current working directory, as shown below.
Example: Remove Directory
>>>importos
>>>os.getcwd()
'C:MyPythonProject'
>>>os.rmdir("C:MyPythonProject")
PermissionError:[WinError32] The process cannot access the file because it is being used by
another process:'d:MyPythonProject'
>>>os.chdir("..")
>>>os.rmdir("MyPythonProject")
Above, the MyPythonProject will not be removed because it is the current directory. We
changed the current working directory to the parent directory using os.chdir("..") and then
remove it using the rmdir() function.
List Files and Sub-directories
The listdir() function returns the list of all files and directories in the specified directory.
Example: List Directories
>>>importos
>>>os.listdir("c:python37")
['DLLs','Doc','fantasy-1.py','fantasy.db','fantasy.py','frame.py',
'gridexample.py','include','Lib','libs','LICENSE.txt','listbox.py','NEWS.txt',
'place.py','players.db','python.exe','python3.dll','python36.dll','pythonw.exe',
'sclst.py','Scripts','tcl','test.py','Tools','tooltip.py','vcruntime140.dll',
'virat.jpg','virat.py']
69. If we don't specify any directory, then list of files and directories in the current working
directory will be returned.
Example: List Directories of CWD
>>>importos
>>>os.listdir()
['.config','.dotnet','python']
Python - sys Module
The sys module provides functions and variables used to manipulate different parts of the
Python runtime environment. You will learn some of the important features of this module
here.
sys.argv
sys.argv returns a list of command line arguments passed to a Python script. The item at index
0 in this list is always the name of the script. The rest of the arguments are stored at the
subsequent indices.
Here is a Python script (test.py) consuming two arguments from the command line.
Example: test.py
import sys
print("You entered: ",sys.argv[1],sys.argv[2],sys.argv[3])
Above, sys.argv[1] contains the first argument 'Python', sys.argv[2] contains the second
argument 'Python', and sys.argv[3] contains the third argument 'Java'. sys.argv[0] contains the
script file name test.py.
sys.exit
This causes the script to exit back to either the Python console or the command prompt. This
is generally used to safely exit from the program in case of generation of an exception.
sys.maxsize
Returns the largest integer a variable can take.
Example: sys.maxsize
70. >>>import sys
>>>sys.maxsize
9223372036854775807
sys.path
This is an environment variable that is a search path for all Python modules.
Example: sys.path
>>>import sys
>>>sys.path
['','C:python36Libidlelib','C:python36python36.zip',
'C:python36DLLs','C:python36lib','C:python36',
'C:UsersacerAppDataRoamingPythonPython36site-packages',
'C:python36libsite-packages']
sys.version
This attribute displays a string containing the version number of the current Python
interpreter.
Example: sys.version
>>>import sys
>>>sys.version
'3.7.0 (v3.7.0:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)]'
Python - Statistics Module
The statistics module provides functions to mathematical statistics of numeric data. The
following popular statistical functions are defined in this module.
Mean
The mean() method calculates the arithmetic mean of the numbers in a list.
Example:
>>>import statistics
>>>statistics.mean([2,5,6,9])
5.5
Median
The median() method returns the middle value of numeric data in a list.
71. Example:
>>>import statistics
>>>statistics.median([1,2,3,8,9])
3
>>>statistics.median([1,2,3,7,8,9])
5.0
Mode
The mode() method returns the most common data point in the list.
Example:
>>>import statistics
>>>statistics.mode([2,5,3,2,8,3,9,4,2,5,6])
2
Standard Deviation
The stdev() method calculates the standard deviation on a given sample in the form of a list.
Example:
>>>import statistics
>>>statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5])
1.3693063937629153
Python - Random Module
The random module is a built-in module to generate the pseudo-random variables. It can be
used perform some action randomly such as to get a random number, selecting a random
elements from a list, shuffle elements randomly, etc.
Generate Random Floats
The random.random() method returns a random float number between 0.0 to 1.0. The function
doesn't need any arguments.
Example: random()
72. >>>import random
>>>random.random()
0.645173684807533
Generate Random Integers
The random.randint() method returns a random integer between the specified integers.
Example: randint()
>>>import random
>>>random.randint(1,100)
95
>>>random.randint(1,100)
49
Generate Random Numbers within Range
The random.randrange() method returns a randomly selected element from the range created
by the start, stop and step arguments. The value of start is 0 by default. Similarly, the value of
step is 1 by default.
Example:
>>>random.randrange(1,10)
2
>>>random.randrange(1,10,2)
5
>>>random.randrange(0,101,10)
80
Select Random Elements
The random.choice() method returns a randomly selected element from a non-empty
sequence. An empty sequence as argument raises an IndexError.
Example:
>>>import random
>>>random.choice('computer')
't'
>>>random.choice([12,23,45,67,65,43])
45
73. >>>random.choice((12,23,45,67,65,43))
67
Shuffle Elements Randomly
The random.shuffle() method randomly reorders the elements in a list.
Example:
>>> numbers=[12,23,45,67,65,43]
>>>random.shuffle(numbers)
>>> numbers
[23,12,43,65,67,45]
>>>random.shuffle(numbers)
>>> numbers
[23,43,65,45,12,67]
Comments:
# ---- single line comment
‘’’multiline comments’’’
“””multiline comments”””