Python Programming Notes
Python Programming Notes
• 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
# 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
• 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 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
site_name = 'program1'
print(site_name)
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.
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.
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,
Syntax of range() : The range() function can take a maximum of three 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.
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.
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,
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
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.
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
1. if statement
2. if...else statement
3. if...elif...else statement
Python if Statement
Python if...else Statement
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
Here, val accesses each item of sequence on each iteration. The loop continues until we reach the last item in the
sequence.
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
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.
Suppose, you need to create a program to create a circle and color it. You can create two functions to solve this problem:
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.
These library functions are defined inside the module. And, to use them we must include the module inside our program.
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,
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:
Suppose we want to get the value of pi, first we import the math module and use math.pi.
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.
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.
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:
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:
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.
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,
Note: Since we don't have to worry about closing the file, make a habit of using the with...open syntax.
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"
# Closing file
file1.close()