Python Notes
Python Notes
Introduction
Python is one of the most popular programming languages today, known for its simplicity and ease
of use. It was created by Guido van Rossum and released in 1991.
Features of Python:
1. Python is object-oriented programming that supports polymorphism, abstraction, inheritance,
encapsulation, etc.
2. Indentation: Indentation is one of the greatest feature in python.
3. Free and open source
4. Large development community
5. Wide application: web development, Machine Learning, Data science, software development,
etc.
· Special Symbols: Python supports all kinds of special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _ + –
={}[]\.
· White Spaces: White spaces like tab space, blank space, newline, and carriage return.
Other: All ASCII and UNICODE characters are supported by Python which constitutes the Python character
set.
Tokens:
A token is the smallest individual unit in a Python program. All statements and instructions in
a program are built with tokens. The various tokens in Python are:
Keywords:
Keywords are words with special meaning or significance in a programming language. They
can’t be used as variable names, function names, or any other random purpose. They are used for
their special features. In Python, we have 3 keywords: try, False, True, class, break, continue, and, as,
assert, while, for, in, raise, except, or, not, if, elif, print, import, etc.
Identifiers:
Identifiers are the names given to any variable, function, class, list, methods, etc. for their
identification. Python is a case-sensitive language with some rules and regulations to name an
identifier.
Literals or Values:
Literals are the fixed values or data items used in a source code. Python supports different
types of literals such as:
String Literals: The text written in single, double, or triple quotes represents the string
literals in Python. For example: “Computer Science”, ‘sam’, etc. We can also use triple quotes to
write multi-line strings.
# String Literals
a = 'Hello'
b = "World"
c = '''This is a
String Literal'''
# Driver code
print(a)
print(b)
print(c)
Character Literals: Character literal is also a string literal type in which the character is
enclosed in single or double-quotes.
# Character Literals
a = 'G'
b = "W"
# Driver code
print(a)
print(b)
Numeric Literals: These are the literals written in form of numbers. Python supports the
following numerical literals:
● Integer Literal: It includes both positive and negative numbers along with 0. It doesn’t
include fractional parts. It can also include binary, decimal, octal, hexadecimal literal.
● Float Literal: It includes both positive and negative real numbers. It also includes
fractional parts.
● Complex Literal: It includes a+bi numeral, here a represents the real part and b
represents the complex part.
# Numeric Literals
a = 5
b = 10.3
c = -17
# Driver code
print(a)
print(b)
print(c)
Boolean Literals: Boolean literals have only two values in Python. These are True and False.
# Boolean Literals
a=3
b = (a == 3)
c = True + 10
# Driver code
print(a, b, c)
Special Literals: Python has a special literal ‘None’. It is used to denote nothing, no values,
or the absence of value.
# Special Literals
var = None
print(var)
Literals Collections: Literals collections in python includes list, tuple, dictionary, and sets.
● List: It is a list of elements represented in square brackets with commas in between.
These variables can be of any data type and can be changed as well.
● Tuple: It is also a list of comma-separated elements or values in round brackets. The
values can be of any data type but can’t be changed.
● Dictionary: It is the unordered set of key-value pairs.
● Set: It is the unordered collection of elements in curly braces ‘{}’.
# Literals collections my_dict = {1:'one', 2:'two',
# List 3:'three'}
my_list = [23, "geek", 1.2, 'data']
# Set
# Tuple my_set = {1, 2, 3, 4}
my_tuple = (1, 2, 3, 'hello')
# Driver code
# Dictionary print(my_list)
print(my_tuple)
print(my_dict) print(my_set)
Operators:
These are the tokens responsible to perform an operation in an expression. The variables on
which operation is applied are called operands. Operators can be unary or binary. Unary operators
are the ones acting on a single operand like complement operator, etc. While binary operators need
two operands to operate.
Punctuators:
These are the symbols that used in Python to organize the structures, statements, and expressions.
Some of the Punctuators are: [ ] { } ( ) @ -= += *= //= **== = , etc.
Python Indentation
Python indentation refers to adding white space before a statement to a particular block of code. In other
words, all the statements with the same space to the left, belong to the same code block.
● Numeric
● Sequence Type
● Boolean
● Set
● Dictionary
● Binary Types( memoryview , bytearray , bytes )
Numeric Data Types in Python:
The numeric data type in Python represents the data that has a numeric value. A numeric
value can be an integer, a floating number, or even a complex number. These values are defined as
Python int , Python float , and Python complex classes in Python .
1. Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
2. Float – This value is represented by the float class. It is a real number with a 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.
3. Complex Numbers – A complex number is represented by a complex class. It is specified as
(real part) + (imaginary part)j . For example – 2+3j
a = 5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square
brackets [ ].
thislist = ["apple", "banana", "cherry"]
print(thislist)
Keywords in Python
Python Keywords are some predefined and reserved words in Python that have special meanings.
Keywords are used to define the syntax of the coding. The keyword cannot be used as an identifier, function,
or variable name. All the keywords in Python are written in lowercase except True and False. There are 35
keywords in Python 3.11.
In Python, there is an inbuilt keyword module that provides an iskeyword() function that can be used
to check whether a given string is a valid keyword or not. Furthermore, we can check the name of the
keywords in Python by using the kwlist attribute of the keyword module.
Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a
combination of character digits and an underscore. They are case-sensitive i.e., ‘num’ and ‘Num’ and
‘NUM’ are three different identifiers in python. It is a good programming practice to give meaningful names
to identifiers to make the code understandable.
We can also use the Python string isidentifier() method to check whether a string is a valid identifier
or not.
Rules for Naming Python Identifiers
● It cannot be a reserved python keyword.
● It should not contain white space.
● It can be a combination of A-Z, a-z, 0-9, or underscore.
● It should start with an alphabet character or an underscore ( _ ).
● It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Python Operators
Operators in general are used to perform operations on values and variables. These are standard
symbols used for logical and arithmetic operations. In this article, we will look into different types of Python
operators.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
1. Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.
Example: The code performs division operations and prints the results. It demonstrates that
both integer and floating-point divisions return accurate results. For example, ’10/2′ results in
‘5.0’, and ‘-10/2’ results in ‘-5.0’.
Example: The code demonstrates integer (floor) division operations using the // in Python
operators. It provides results as follows: ’10//3′ equals ‘3’, ‘-5//2’ equals ‘-3’, ‘5.0//2′ equals
‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer division returns the largest integer less than or equal
to the division result.
2. Comparison Operators
In Python Comparison of Relational operators compares the values. It either returns True or
False according to the condition.
● Logical not
● logical and
● logical or
4. Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to
operate on binary numbers.
Precedence of Bitwise Operators in Python
The precedence of Bitwise Operators in Python is as follows:
● Bitwise NOT
● Bitwise Shift
● Bitwise AND
● Bitwise XOR
● Bitwise OR
5. Assignment Operators
Python Assignment operators are used to assign values to the variables.
6. Identity Operators
In Python, is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal do not imply that they
are identical.
7. Membership Operators
In Python, in and not in are the membership operators that are used to test whether a value or
variable is in a sequence.
Presence and Associativity of Operators:
Comments in Python:
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the
program.
Types of Comments in Python
There are three types of comments in Python:
● Single line Comments
● Multiline Comments
● String Literals
● Docstring Comments
1. Single-Line Comments
● Python single-line comment starts with the hashtag symbol (#) with no white spaces
and lasts till the end of the line.
● If the comment exceeds one line then put a hashtag on the next line and continue the
Python Comment.
● Python’s single-line comments are proved useful for supplying short explanations for
variables, function declarations, and expressions. See the following code snippet
demonstrating single line comment:
2. Multiline Comments
Unlike languages such as C++ and Java, Python doesn't have a dedicated method to write
multi-line comments.
However, we can achieve the same effect by using the hash (#) symbol at the beginning of
each line.
3. String Literals
Python ignores the string literals that are not assigned to a variable so we can use these string
literals as Python Comments.
4. Docstring Comments
● Python docstring is the string literals with triple quotes that are appeared right after
the function.
● It is used to associate documentation that has been written with Python modules,
functions, classes, and methods.
● It is added right below the functions, modules, or classes to describe what they do. In
Python, the docstring is then made available via the __doc__ attribute.
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Slicing Strings
You can return a range of characters by using the slice syntax.
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from
start to end.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Negative Indexing
Use negative indexes to start the slice from the end of the string:
String Concatenation:
To concatenate, or combine, two strings you can use the + operator.
Modify Strings Using STRING METHODS:
Python has a set of built-in methods that you can use on strings.
Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii characters
with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified
object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute
(property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each
item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by
default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ property of an object
zip() Returns an iterator, from two or more iterators
String Format
we can combine strings and numbers by using f-strings or the format() method!
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
Object Oriented Programming(OOPs):
In Python object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in
programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc.
in the programming. The main concept of object-oriented Programming (OOPs) or oops concepts in Python
is to bind the data and the functions that work together as a single unit so that no other part of the code can
access this data.
Why OOP’s
In the real world, we deal with and process objects, such as student, employee, invoice, car,
etc. Objects are not only data and not only functions, but combination of both. Each real-world
object has attributes and behavior associated with it.
● Objects in Python
In object oriented programming Python, The object is an entity that has a state and behavior
associated with it. It may be any real-world object like a mouse, keyboard, chair, table, pen,
etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects.
More specifically, any single integer or any single string is an object.
An object consists of:
● State: It is represented by the attributes of an object. It also reflects the properties of
an object.
● Behavior: It is represented by the methods of an object. It also reflects the response of
an object to other objects.
● Identity: It gives a unique name to an object and enables one object to interact with
other objects.
The Python self
● Class methods must have an extra first parameter in the method definition. We do not
give a value for this parameter when we call the method, Python provides it
● If we have a method that takes no arguments, then we still have to have one argument.
● This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self
is about.
The Python __init__ Method
The __init__ method is similar to constructors in C++ and Java. It is run as soon
as an object of a class is instantiated. The method is useful to do any
initialization you want to do with your object. Now let us define a class and
create some objects using the self and __init__ method.
● Polymorphism in Python
In object oriented Programming Python, Polymorphism simply means having many forms.
● Encapsulation in Python
In Python object oriented programming, Encapsulation is one of the fundamental concepts in
object-oriented programming (OOP). It describes the idea of wrapping data and the methods
that work on data within one unit. This puts restrictions on accessing variables and methods
directly and can prevent the accidental modification of data. To prevent accidental change, an
object’s variable can only be changed by an object’s method. Those types of variables are
known as private variables. It is used to restrict access to methods and variables. In
encapsulation, code and data are wrapped together w
● Inheritance in Python
In Python object oriented Programming, Inheritance is the capability of one class to derive or
inherit the properties from another class. The class that derives properties is called the
derived class or child class and the class from which the properties are being derived is called
the base class or parent class. The benefits of inheritance are:
Conditional Statements:
Conditional Statements are statements in Python that provide a choice for the control flow based on a
condition. It means that the control flow of the Python program will be decided based on the
outcome of the condition. Now let us see how Conditional Statements are implemented in Python.
For Loop:
For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python,
there is “for in” loop which is similar to foreach loop in other languages. Let us learn how to use for loops in
Python for sequential traversals with examples.
While Loop:
In Python, a while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
Using else Statement with for Loop in Python
We can also combine else statement with for loop like in while loop. But as there is no
condition in for loop based on which the execution will terminate so the else block will be
executed immediately after for block finishes execution.
In this code, the ‘for' loop iterates over a list and prints each element, just like in the previous
example. However, after the loop is finished, the “else” block is executed. So, in this case, it
will print “Inside Else Block” once the loop completes.
Nested Loops:
Python programming language allows to use one loop inside another loop which is called nested loop.
Following section shows few examples to illustrate the concept.
Loop Control Statements:
Loop control statements change execution from their normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed. Python supports the following control
statements.
Continue Statement
The continue statement in Python returns the control to the beginning of the loop.
BreakContinue Statement
The break statement terminates the loop immediately when it's encountered.
Pass Statement:
In Python programming, the pass statement is a null statement which can be used as a placeholder for future
code.
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future.
In such cases, we can use the pass statement.