0% found this document useful (0 votes)
16 views107 pages

Python Programming Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views107 pages

Python Programming Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 107

Python Programming

Programming in Python 3 – A complete introduction to the Python Language, 2nd edition by


Mark Summerfield, Publisher – Pearson
What is Python?
• Python is a high-level, general-purpose, and very popular
programming language. Python programming language (latest Python
3) is being used in web development, Machine Learning applications,
along with all cutting-edge technology in Software Industry.

• Python language is being used by almost all tech-giant companies like


– Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.
What is Python?
The biggest strength of Python is huge collection of standard library which
can be used for the following:
• Machine Learning
• GUI Applications (like Kivy, Tkinter, PyQt etc. )
• Web frameworks like Django (used by YouTube, Instagram, Dropbox)
• Image processing (like OpenCV, Pillow)
• Web scraping (like Scrapy, BeautifulSoup, Selenium)
• Test frameworks
• Multimedia
• Scientific computing
• Text processing and many more..
Why Learn Python?

• Python is currently the most widely used multi-purpose, high-level


programming language, which allows programming in Object-
Oriented and Procedural paradigms.
• Python programs generally are smaller than other programming
languages like Java.
• Programmers have to type relatively less and the indentation
requirement of the language, makes them readable all the time.
About Python
• Python is a widely used general-purpose, high-level programming
language.
• Every Release of Python is open-source. Python releases have also
been General Public License (GPL) -compatible.
• Any version of Python can be downloaded from the Python Software
Foundation website at python.org.
• Most languages, notably Linux provide a package manager through
which you can directly install Python on your Operating System
• Windows: There are many interpreters available freely to run Python
scripts like IDLE (Integrated Development Environment) that comes
bundled with the Python software downloaded from http://python.org/.

• Linux: Python comes preinstalled with popular Linux distros such as


Ubuntu and Fedora. To check which version of Python you’re running, type
“python” in the terminal emulator. The interpreter should start and print
the version number.

• macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to
manually install Python 3 from http://python.org/.
First Program
• Before we start Python programming, we need to have an interpreter
to interpret and run our programs.
• Just type in the following code after you start the interpreter.
# Script Begins

print(“Welcome to Python Programming")

# Scripts Ends

Few Observations:
1. # Script Begins, In Python, comments begin with a #. This statement is ignored by the interpreter and serves as
documentation for our code.
2. print(“Welcome to Python Programming”), To print something on the console, print() function is used. This function
also adds a newline after our message is printed(unlike in C).
Reason for increasing popularity

• Emphasis on code readability, shorter codes, ease of writing


• Programmers can express logical concepts in fewer lines of code in
comparison to languages such as C,C++ or Java.
• Python supports multiple programming paradigms, like object-
oriented, imperative and functional programming or procedural.
• There exists inbuilt functions for almost all of the frequently used
concepts.
• Philosophy is “Simplicity is the best”.
LANGUAGE FEATURES

• Interpreted
There are no separate compilation and execution steps like C and C++.
Directly run the program from the source code.
Internally, Python converts the source code into an intermediate form called bytecodes which is
then translated into native language of specific computer to run it.
No need to worry about linking and loading with libraries, etc.
• Platform Independent
Python programs can be developed and executed on multiple operating system platforms.
Python can be used on Linux, Windows, Macintosh, Solaris and many more.
• Free and Open Source; Redistributable
• High-level Language
In Python, no need to take care about low-level details such as managing the memory used by
the program.
• Simple
Closer to English language;Easy to Learn
More emphasis on the solution to the problem rather than the syntax
• Embeddable
Python can be used within C/C++ program to give scripting capabilities for the program’s
users.
• Robust:
Exceptional handling features
Memory management techniques in built
• Rich Library Support
The Python Standard Library is very vast.
Known as the “batteries included” philosophy of Python ;It can help do various things
involving regular expressions, documentation generation, unit testing, threading,
databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.
Besides the standard library, there are various other high-quality libraries such as the Python
Imaging Library which is an amazingly simple image manipulation library.
(/ C++)
• Python doesn’t convert its code into machine code, something that hardware can
understand.
• It converts it into something called byte code.
• So within Python, compilation happens, but it’s just not in a machine language.
• It is into byte code (.pyc or .pyo) and this byte code can’t be understood by the CPU.
• So we need an interpreter called the Python virtual machine to execute the byte codes.
Compiler Vs Interpreter

• In the system both the compiler and interpreter are the same they
convert high-level code to machine code.
• The interpreter converts source code into the machine when the
program runs in a system while a compiler converts the source code
into machine code before the program runs in our system.

Note: The complete script of Python is written in the C


Programming Language. When we write a Python program, the
program is executed by the Python interpreter. This interpreter is
written in the C language.
Python Keywords
• Keywords in Python are reserved words that can not be used as a
variable name, function name, or any other identifier.

Note: The keyword module comes with various methods to manipulate keywords. The read-only
attribute (variable), kwlist, returns a list of all keywords reserved for the interpreter.
Comments in Python
• Single-line comment in Python

• Python also allows comments at the end of lines, ignoring the


previous text.

• Multiline comment in Python


Python Variables, Constants and Literals
Python Variables
• Constant and variable names should have a combination of letters in
lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_). For example: snake_case, MACRO_CASE, camelCase,
CapWords
• Python is case-sensitive. So num and Num are different variables.
site1 = site2 = 'program1'
var num = 5
print(site1) # prints program1 var Num = 55
print(site2) # prints program1 print(num) # 5
print(Num) # 55

site_name = 'program1'
print(site_name)

# assigning a new value to site_name


site_name = 'apple.com'

print(site_name)
Python Constants
• A constant is a special type of variable whose value cannot be
changed.
• In Python, constants are usually declared and assigned in a module (a
new file containing variables, functions, etc which is imported to the
main file).
• Let's see how we declare constants in separate file and use it in the
main file,
Create a constant.py: Create a main.py:
Python Data Types
Since everything is an object in Python programming, data types are actually
classes and variables are instances(object) of these classes.
Python Numeric Data type
• In Python, numeric data type is used to hold numeric values.

• Integers, floating-point numbers and complex numbers fall under Python


numbers category. They are defined as int, float and complex classes in
Python.

• int - holds signed integers of non-limited length.


• float - holds floating decimal points and it's accurate up to 15 decimal
places.
• complex - holds complex numbers.
• We can use the type() function to know which class a variable or a value
belongs to.
Type Conversion in Python
• Operations like addition, subtraction convert integers to float
implicitly (automatically), if one of the operands is float. For example,
print(1 + 2.0) # prints 3.0

• Explicit Type Conversion


We can also use built-in functions like int(), float() and complex() to
convert between types explicitly. These functions can even convert
from strings.
Python List Data Type
• List is an ordered collection of similar or different types of items
(integer, float, string, etc.) separated by commas and enclosed within
brackets [ ].
• A list can store duplicate elements
Access List Elements
• In Python, a list is associated with a number. The number is known as
a list index.
• The index of the first element is 0, second element is 1 and so on.
• Python allows negative indexing for its sequences. The index of -
1 refers to the last item, -2 to the second last item and so on.

Note: If the specified index does not exist in a list, Python


throws the IndexError exception.
Slicing of a List

• In Python, it is possible to access a portion of a list using the slicing


operator : For example,

Add Elements to a List


Lists are mutable (changeable). Meaning we can add and remove elements from a list.
We use the extend() method to add all the items of an iterable (list, tuple, string, dictionary, etc.) to the end of the list.

We use the insert() method to add an element at the specified index.

Change List Items : Python lists are mutable. Meaning lists are changeable. And we can change items of a list by
assigning new values using the = operator
In Python we can use the del statement to remove one or more
Remove an Item From a List:
items from a list. For example,

In Python we can use the del statement to remove one or more items from a list. For example,
List Methods : Python has many useful list methods that makes it really easy to work with lists.
Iterating through a List : We can use a for loop to iterate over the elements
of a list. For example,

Check if an Element Exists in a List, We use the in keyword to check if an item exists in the list or not. For
example,

List Length: We use the len() function to find the size of a list. For example,
List Comprehension: It is a concise and elegant way to create lists. For example,

is equivalent to
Python Tuple Data Type
• A tuple in Python is similar to a list. The difference between the two is
that we cannot change the elements of a tuple once it is assigned
whereas we can change the elements of a list.
• A tuple is created by placing all the items (elements) inside
parentheses (), separated by commas. The parentheses are optional,
however, it is a good practice to use them.

• A tuple can have any number of items and they may be of different
types (integer, float, list, string, etc.).
we can also create tuples without using parentheses:

Create a Python Tuple With one Element : In Python, creating a tuple with one element is a bit tricky.
Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is a tuple,
Access Python Tuple Elements
Indexing :We can use the index operator [] to access an item in a tuple, where the index starts from 0.

So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range
( 6,7,... in this example) will raise an IndexError.

Negative Indexing : Python allows negative indexing for its sequences.


The index of -1 refers to the last item, -2 to the second last item and so on. For example,
Slicing : We can access a range of items in a tuple by using the slicing operator colon :

Python Tuple Methods : Only the following two methods are available.
Iterating through a Tuple in Python : We can use the for loop to iterate over the elements of a tuple. For
example,

Check if an Item Exists in the Python Tuple :


We use the in keyword to check if an item exists in the tuple or not. For example,
Python range()
The range() function returns a sequence of numbers between the give range. It gives a sequence of numbers starting
from 0 up to the number (but not including the number).

Note: range() returns an immutable sequence of numbers that


can be easily converted to lists, tuples, sets etc.

Syntax of range() : The range() function can take a maximum of three arguments:

The start and step parameters in range() are optional.


range() with Start and Stop Arguments, If we pass two arguments to range(), it means we are passing start and stop
arguments.

range() with Start, Stop and Step Arguments

Note: The default value of start is 0, and the default value of step
is 1. range(0, 5, 1) is equivalent to range(5).
Python String Data Type
• String is a sequence of characters represented by either single or
double quotes. For example,
Access String Characters in Python :
Indexing: One way is to treat strings as a list and use index values. For example,

Negative Indexing: Similar to a list, Python allows negative indexing for its strings. For example,

Slicing: Access a range of characters in a string by using the slicing operator colon :. For example,
Python Strings are immutable : In Python, strings are immutable.
That means the characters of a string cannot be changed. For example,

However, we can assign the variable name to a new string. For example,
Python String Operations

There are many operations that can be performed with strings which makes it one of the most used data types in
Python.

Compare Two Strings: We use the == operator to compare two strings.


If two strings are equal, the operator returns True. Otherwise, it returns False. For example,
Join Two or More Strings: In Python, we can join (concatenate) two or more strings using the + operator.

Iterate Through a Python String : We can iterate through a string using a for loop. For example,

Python String Length : In Python, we use the len() method to find the length of a string. For example,
String Membership Test :We can test if a substring exists within a string or not, using the keyword in.

Methods of Python String


Python String Formatting (f-Strings) :
Python f-Strings make it really easy to print values and variables. For example,
Python Set Data Type
• A set is a collection of unique data. That is, elements of a set cannot
be duplicate. For example, Suppose we want to store information
about student IDs. Since student IDs cannot be duplicate, we can use
a set.
Create a Set in Python :

Note: When you run this code, you might get output in a
different order. This is because the set has no particular order.
Duplicate Items in a Set: Let's see what will happen if we try to include duplicate items in a set.

Add Items to a Set in Python :In Python, we use the add() method to add an item to a set. For example,

Update Python Set :


The update() method is used to update the set with items other collection types (lists, tuples, sets, etc). For
example,
Remove an Element from a Set : We use the discard() method to remove the specified element from a set. For example,

Built-in Functions with Set


Iterate Over a Set in Python

Find Number of Set Elements :


We can use the len() method to find the number of elements present in a Set. For example,
Python Set Operations
Union of Two Sets : The union of two sets A and B include all the elements of set A and B.
We use the | operator or the union() method to perform the set union operation.

Set Intersection :The intersection of two sets A and B include the common elements between set A and B.
In Python, we use the & operator or the intersection() method to perform the set intersection operation.
Difference between Two Sets : The difference between two sets A and B include elements of set A that are not present on
set B. We use the - operator or the difference() method to perform the difference between two sets.

Set Symmetric Difference : The symmetric difference between two sets A and B includes all elements of A
and B without the common elements. In Python, we use the ^ operator or the
symmetric_difference() method to perform symmetric difference between two sets.
Check if two sets are equal : We can use the == operator to check whether two sets are equal or not. For example,
Python Dictionary Data Type

• Python dictionary is an ordered collection of items. It stores elements


in key/value pairs.
• Here, keys are unique identifiers that are associated with each value.
Create a Dictionary :
We create dictionaries by placing key:value pairs inside curly brackets {}, separated by commas.

Note: Dictionary keys must be immutable, such as tuples, strings, integers,


etc. We cannot use mutable (changeable) objects such as lists as keys.
Python Dictionary Length : We can get the size of a dictionary by using the len() function.

Access Dictionary Items :We can access the value of a dictionary item by placing the key inside square brackets.
Change Dictionary Items : Python dictionaries are mutable (changeable). We can change the value of a
dictionary element by referring to its key.

Add Items to a Dictionary : We can add an item to the dictionary by assigning a value to a new key (that does not
exist in the dictionary).
Remove Dictionary Items: We use the del statement to remove an element from the dictionary. For example,

If we need to remove all items from the dictionary at once, we can use the clear() method.
Python Dictionary Methods
Dictionary Membership Test : We can check whether a key exists in a dictionary using the in operator.

Note: The in operator checks whether a key exists; it doesn't check whether a value exists or not.
Iterating Through a Dictionary : A dictionary is an ordered collection of items (starting from Python 3.7). Meaning a
dictionary maintains the order of its items. We can iterate through dictionary keys one by one using a for loop.
Python Basic Input and Output
Python Output : In Python, we can simply use the print() function to print output.

Syntax of print() : The actual syntax of the print function accepts 5 parameters

In the above example, the print() statement only includes the object to be printed. Here,
the value for end is not used. Hence, it takes the default value '\n'.
Python print() with end Parameter:

Notice that we have included the end= ' ' after the end of the first print() statement.
Hence, we get the output in a single line separated by space.
Python print() with sep parameter :

Output formatting : Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method.

Here, the curly braces {} are used as placeholders.


Python Input :
While programming, we might want to take the input from the user. In Python, we can use the input() function.

Syntax of input()

To convert user input into a number we can use int() or float() functions as:
Python Operators
Python Arithmetic Operators
Python Assignment Operators
Python Comparison Operators
Python Logical Operators
Python Bitwise operators

In the table above: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Python Special operators : Python language offers some special types of operators like the identity operator and the
membership operator.

Identity operators :In Python, is and is not are used to check if two values are located on the same part of the memory.
Two variables that are equal does not imply that they are identical.
Membership operators
In Python, in and not in are the membership operators. 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.
Python if...else Statement

In Python, there are three forms of the if...else statement.

1. if statement
2. if...else statement
3. if...elif...else statement

Python if Statement
Python if...else Statement

Python if...elif...else Statement


Python Nested if statements

Notes:

We can add else and elif statements to the inner if statement as required.
We can also insert inner if statement inside the outer else or elif statements(if they exist)
We can nest multiple layers of if statements.
Python for Loop
There are 2 types of loops in Python: for loop & while loop

Python for Loop


In Python, a for loop is used to iterate over sequences such as lists, tuples, string, etc.

for Loop Syntax : The syntax of a for loop is:

Here, val accesses each item of sequence on each iteration. The loop continues until we reach the last item in the
sequence.

Varients of for loop:

1. for Loop Through a String


2. for Loop with Python range()

3. for Loop Without Accessing Items

The _ symbol is used to denote that the elements of a sequence will not be used
within the loop body.
4. Python for loop with else

Note: The else part is executed when the loop is exhausted


(after the loop iterates through every item of a sequence).
Factorial of a Number using Loop
Python while Loop
Python while loop is used to run a block code until a certain condition is met.

The syntax of while loop is:

Here,
• A while loop evaluates the condition, If the condition evaluates to True, the code inside the while loop is
executed.
• condition is evaluated again.
• This process continues until the condition is False.
• When condition evaluates to False, the loop stops.
Python While loop with else
In Python, a while loop may have an optional else block.

Here, the else part is executed after the condition of the loop evaluates to False.

Inside loop
Python break and continue
Python break Statement
The break statement is used to terminate the loop immediately when it is encountered.

Python continue Statement


The continue statement is used to skip the current iteration of the loop and the control flow of the
program goes to the next iteration.
Python Functions
A function is a block of code that performs a specific task.

Suppose, you need to create a program to create a circle and color it. You can create two functions to solve this problem:

• create a circle function


• create a color function
Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.

Types of function :
There are two types of function in Python programming:

• Standard library functions - These are built-in functions in Python that are available to use.
• User-defined functions - We can create our own functions based on our requirements.

Python Function Declaration


def - keyword used to declare a function
function_name - any name given to the function
arguments - any value passed to function
return (optional) - returns value from a function
Python Library Functions
In Python, standard library functions are the built-in functions that can be used directly in our program.

These library functions are defined inside the module. And, to use them we must include the module inside our program.

For example, sqrt() is defined inside the math module.


Python Function Arguments
1. Function Argument with Default Values
In Python, we can provide default values to function arguments.

We use the = operator to provide default values.


2. Python Keyword Argument
In keyword arguments, arguments are assigned based on the name of arguments.

3. Python Function With Arbitrary Arguments


Sometimes, we do not know in advance the number of arguments that will be passed into a function. To handle this kind of
situation, we can use arbitrary arguments in Python.
Arbitrary arguments allow us to pass a varying number of values during a function call.
We use an asterisk (*) before the parameter name to denote this kind of argument.
Python Recursion
Recursion is the process of defining something in terms of itself.
Python Lambda/Anonymous Function
In Python, a lambda function is a special type of function without the function name.

• We use the lambda keyword instead of def to create a lambda function.


• argument(s) - any value passed to the lambda function
• expression - expression is executed and returned

Python lambda Function without


an Argument
Python lambda Function with an Argument
Python Modules
As our program grows bigger, it may contain many lines of code. Instead of putting everything in a single file, we can use
modules to separate codes in separate files as per their functionality. This makes our code organized and easier to
maintain.

Module is a file that contains code to perform a specific task. A module may contain variables, functions, classes etc.
Let's see an example,

Let us create a module. Type the following and save it as example.py.

Here, we have defined a function add() inside a module named example. The function takes in two numbers and returns
their sum.
Import 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.

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.

Note:

Python has tons of standard modules.


You can check out the full list of Python standard modules and their use cases.
Standard modules can be imported the same way as we import our user-defined module example.
Import Python Standard Library Modules
The Python standard library contains well over 200 modules.
We can import a module according to our needs.

Suppose we want to get the value of pi, first we import the math module and use math.pi.

Python import with Renaming


In Python, we can also import a module by renaming it.
Python from...import statement
We can import specific names(definitions) from a module without importing the module
as a whole.

Import all names


In Python, we can import all names(definitions) from a module using the following construct:

Note: Importing everything with the asterisk (*) symbol is not a good programming practice.
The dir() built-in function
In Python, we can use the dir() function to list all the function names in a module.

For example, earlier we have defined a function add() in the module example.

We can use dir in example module in the following way:

Here, we can see a sorted list of names (along with add). All other names that
begin with an underscore are default Python attributes associated with the
module (not user-defined).
Python Package
A package is a container that contains various functions to perform specific tasks. For example, the math package includes
the sqrt() function to perform the square root of a number.

While working on big projects, we have to deal with a large amount of code, and writing everything together in the same
file will make our code look messy. Instead, we can separate our code into multiple files by keeping the related code
together in packages.

Now, we can use the package whenever we need it in our projects. This way we can also reuse our code.
Package Model Structure in Python Programming
Suppose we are developing a game.
Importing module from a package
In Python, we can import modules from packages using the dot (.) operator.

How to access function definition from the Package


For example, assume select_difficulty() is a function present in the start module, there are two ways:
1. We want to import the start module in the above example, it can be done as

Now, if this module contains a function named select_difficulty(), we must use the full name to reference it.

2. Import Without Package Prefix : We can import the module without the package prefix as follows:

We can now call the function simply as follows:

3. Import Required Functionality Only: Additional way of importing just the required function (or class or
variable) from a module within a package would be as follows:

Now we can directly call this function.


Python File I/OPython File Operation
A file is a container in computer storage devices used for storing data.

When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so that
the resources that are tied with the file are freed.

Hence, in Python, a file operation takes place in the following order:

1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening Files in Python
In Python, we use the open() method to open files.

To demonstrate how we open files in Python, let's suppose we have a file named test.txt with the following content.

Now, let's try to open data from this file using the open() function.

Here, we have created a file object named file1. This object can be used to work with files and directories.

By default, the files are open in read mode (cannot be modified). The code above is equivalent to
Here's few simple examples of how to open a file in different modes,

Reading Files in Python


After we open a file, we use the read() method to read its contents. For example,

Closing Files in Python


When we are done with performing operations on the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file. It is done using the close() method in
Python. For example,
Use of with...open Syntax
In Python, we can use the with...open syntax to automatically close the file. For example,

Note: Since we don't have to worry about closing the file, make a habit of using the with...open syntax.

Writing to Files in Python


There are two things we need to remember while writing to a file.

1. If we try to open a file that doesn't exist, a new file is created.


2. If a file already exists, its content is erased, and new content is added to the file.
In order to write into a file in Python, we need to open it in write mode by passing "w" inside open() as a second argument.

Suppose, we don't have a file named test2.txt. Let's see what happens if we write contents to the test2.txt file.
# Python program to demonstrate
# writing to file

# Opening a file
file1 = open('myfile.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"

# Writing a string to file


file1.write(s)

# Writing multiple strings


# at a time
file1.writelines(L)

# Closing file
file1.close()

# Checking if the data is


# written to file or not
file1 = open('myfile.txt', 'r')
print(file1.read())
file1.close()
Appending to a file
When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will
be inserted at the end, after the existing data. Let’s see the below example to clarify the difference between write
mode and append mode.

You might also like