0% found this document useful (0 votes)
14 views21 pages

UNIT-I Python

Python is a high-level, interpreted programming language known for its ease of use and versatility, originating from the work of Guido van Rossum in 1989. It features a simple syntax, dynamic typing, and a rich standard library, making it suitable for various applications including GUI development and database connectivity. Python's popularity is supported by an active developer community and its open-source nature, allowing it to run on multiple platforms.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views21 pages

UNIT-I Python

Python is a high-level, interpreted programming language known for its ease of use and versatility, originating from the work of Guido van Rossum in 1989. It features a simple syntax, dynamic typing, and a rich standard library, making it suitable for various applications including GUI development and database connectivity. Python's popularity is supported by an active developer community and its open-source nature, allowing it to run on multiple platforms.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT - I

PYTHON
1. DEFINE PYTHON. (PART-B)
🙦 Python is an elegant and robust programming language that delivers both the power
and general applicability of traditional compiled languages with the ease of use of
simpler scripting and interpreted languages.
[Python is a very user-
friendly programming language. It's popular because it's both powerful (like languages
traditionally used for complex programming) and easy to use (like simpler languages).]
ORIGINS
2. WHERE DID THE PYTHON ORIGINATED FROM? (PART-B)
🙦 Work on Python began in late 1989 by Guido van Rossum, then at CWI (Centrum Wiskunde
Informatica, the National Research Institute for Mathematics and Computer Science) in
the Netherlands. It was eventually released for public distribution in early 1991.
🙦 At the time, van Rossum was a researcher with considerable language design experience with the
interpreted language ABC.
🙦 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.
🙦 Python has come a long way to become the most popular coding language in the world.
Python has just turned 30 and just recently at pycon22(python conference) a new feature was
released by Anaconda foundation it’s known as pyscript with this now python can be written
and run in the browser like JavaScript.
FEATURES
Python Features:

Python is a feature rich high-level, interpreted, interactive and


object-oriented scripting language. Here some of the important features of
Python:

Following section will explain these features in more detail:

Python is Easy to Learn

 This is one of the most important reasons for the


popularity of Python. Python has a limited set of
keywords.
1
 Its features such as simple syntax, usage of
indentation (spaces or tabs) to avoid clutter of curly
brackets and dynamic typing that doesn't necessitate
prior declaration of variable help a beginner to learn
Python quickly and easily.

Python is Interpreter Based

 Python is an interpreter-based language. The


interpreter takes one instruction from the source code
at a time, translates it into machine code and executes
it. (Python’s interpreter reads and executes code one
line at a time, instead of compiling the entire program
at once.)
 Instructions before the first occurrence of error are
executed. With this feature, it is easier to debug the
program and thus proves useful for the beginner level
programmer to gain confidence gradually. (Error
Handling: If an error occurs, Python stops at that
line, so you can fix issues one step at a time.)
 Python therefore is a beginner-friendly language.

Python is Interactive

 Standard Python distribution comes with an interactive


shell that works on the principle of REPL (Read –
Evaluate – Print – Loop).
 The shell presents a Python prompt >>>. You can type
any valid Python expression and press Enter. Python
interpreter immediately returns the response and the
prompt comes back to read the next expression.
 The interactive mode is especially useful to get
familiar with a library and test out its
functionality. You can try out small code snippets in
interactive mode before writing a program.

Python is multi-paradigm

 Python is a completely object-oriented


language. Everything in a Python program is an
object.
 However, Python conveniently encapsulates its object
orientation to be used as an imperative or
procedural language – such as C.
 Python also provides certain functionality
that resembles functional programming.
(Python has tools for functional programming, allowing
2
you to use functions as building blocks.)
 Moreover, certain third-party tools have been
developed to support other programming paradigms
such as aspect-oriented and logic programming.

Python's Standard Library

 Even though it has a very few keywords (only Thirty


Five), Python software is distributed with a standard
library made of large number of modules and packages.
 Thus, Python has out of box support for programming
needs such as serialization, data compression, internet
data handling, and many more. Python is known for its
batteries included approach. (The library covers many
common programming needs, so you often don’t need to
install extra tools.)

Python is Open Source and Cross Platform

 You can download pre-compiled binaries for various


operating system platforms. In addition, the source
code is also freely available, which is why it comes
under open source category.
 Python software (along with the documentation) is
distributed under Python Software Foundation License.
 It is a BSD (Berkeley Software Distribution) style
permissive software license and compatible to GNU GPL
(General Public License).
 Python is a cross-platform language. (Pre-compiled
Python versions exist for Windows, Linux, macOS, and
even Android, allowing it to run on many operating
systems.) Pre-compiled binaries are available for use
on various operating system platforms such as Windows,
Linux, Mac OS, and Android OS. The reference
implementation of Python is called CPython and is
written in C. You can download the source code and
compile it for your OS platform.
(CPython: The main version of Python, called CPython,
is written in C. You can even compile it from the
source if needed).

Python for GUI Applications

 Python's standard distribution has an excellent


graphics library called TKinter. It is a Python port
for the vastly popular GUI toolkit called TCL/Tk.
You can build
3
attractive user-friendly GUI applications in Python.
 GUI toolkits are generally written in C/C++. Many of
them have been ported to Python. Examples are PyQt,
WxWidgets, and PySimpleGUI etc.

Python's Database Connectivity

 Almost any type of database can be used as a backend


with the Python application.
 DB-API is a set of specifications for database driver
software to let Python communicate with a relational
database.
 With many third party libraries, Python can also work
with NoSQL databases such as MongoDB.
(NoSQL databases, like MongoDB, are designed to handle
a wide variety of data formats. Unlike traditional
relational databases, which organize data in tables
with rows and columns, NoSQL
databases use a more flexible, non-tabular
format.)

Python is Extensible
 The term extensibility implies the ability to add new
features or modify existing features. As stated
earlier, CPython (which is Python's reference
implementation) is written in C.
(You can add new features to Python by writing
modules in languages like C)
 Hence one can easily write modules/libraries in C and
incorporate them in the standard library. There are
other implementations of Python such as Jython (written
in Java) and IPython (written in C#).

Python's Active Developer Community

 As a result of Python's popularity and open-source


nature, a large number of Python developers often
interact with online forums and conferences.
 Python Software Foundation also has a significant
member base, involved in the organization's mission to
"Promote, Protect, and Advance the Python Programming
Language"
 Python also enjoys a significant institutional support.
Major IT companies Google, Microsoft, and Meta
contribute immensely by preparing documentation and
other resources.

VARIABLES AND ASSIGNMENT

4
4. DEFINE VARIABLE. (PART-B)
5. EXPLAIN ABOUT VARIABLES AND ASSIGNMENT. (PART-B)
Rules for variables:
1. Variable names must start with an alphabetic or an underscore _ character.
2. Python variables are case-sensitive. For example, "cAsE" is different from "CaSe."
3. Python is dynamically typed, that is no pre-declaration of a variable or its type is necessary.
4. The variable type (and value) is initialized on assignment.
5. Assignments are performed using the equal sign.
Example:
>>> counter = 0
>>> miles = 1000.0
>>> name = 'Bob'
>>> counter = counter + 1
>>> kilometers = 1.609 * miles

🙦 The first is an integer assignment followed by one each for floating point numbers, one for
strings, an increment statement for integers, and finally, a floating point operation and
assignment.
🙦 Python also supports augmented assignment, (which are shorthand ways of performing
operations) statements that both refer to and assign values to variables. For example:
n = n * 10 or n *= 10
🙦 Python does not support increment and decrement operators like the ones in C: n++ or --n.
Because + and -- are also unary operators, Python will interpret --n as -(-n) == n, and the same
is true for ++n.
PYTHON BASICS
STATEMENTS AND SYNTAX
6. DISCUSS ABOUT STATEMENTS AND SYNTAX IN PYTHON. (PART-B/C)
🙦 Some rules and certain symbols are used with regard to statements in Python:
1. Hash mark (#) indicates Python comments.
2. NEWLINE (\n) is the standard line separator (one statement per line).
3. Backslash (\) continues a line.
4. Semicolon (;) joins two statements on a line.
5. Colon (:) separates a header line from its suite.
6. Statements (code blocks) grouped as suites.
7. Python files organized as modules.
1. Comments (#)
🙦 Python comment statements begin with the hash symbol (#). A comment can begin anywhere on
a line. All characters following the # to the end of the line are ignored by the interpreter.
2. Continuation (\)
🙦 Python statements are, in general, delimited by NEWLINEs, meaning one statement per line.
Single statements can be broken up into multiple lines by use of the backslash.
🙦 The backslash symbol (\) can be placed before a NEWLINE to continue the current statement
onto the next line.
if (weather_is_hot == 1) and \
(shark_warnings == 0):
send_goto_beach_mesg_to_pager()
🙦 There are two exceptions where lines can be continued without backslashes.
1. A single statement can take up more than one line when enclosing operators are used, i.e.,
parentheses, square brackets, or braces.
2. When NEWLINEs are contained in strings enclosed in triple quotes.
# display a string with triple quotes
print ('''hi there, this is a long message for you
5
that goes over multiple lines... you will find
out soon that triple quotes in Python allows
this kind of fun! it is like a day on the beach!''')
3. Multiple Statement Groups as Suites (:)
🙦 Groups of individual statements making up a single code block are called "suites" in Python.
🙦 Compound or complex statements, such as if, while, def, and class, are those that require a
header line and a suite.
🙦 Header lines begin the statement (with the keyword) and terminate with a colon and are followed
by one or more lines that make up the suite. The combination of a header line and a suite as
a clause.
4. Suites Delimited via Indentation
🙦 Python employs indentation as a means of delimiting blocks of code. Code at inner levels is
indented via spaces or tabs. All the lines of code in a suite must be indented at the exact
same level (e.g., same number of spaces).
🙦 Indented lines starting at different positions or column numbers are not allowed; each line would
be considered part of another suite and would more than likely result in syntax errors.
(Inconsistent indentation (e.g., one line with 4 spaces and another with 2 spaces) causes syntax
errors.)
🙦 A new code block is recognized when the amount of indentation has increased, and its
termination is signaled by a "dedentation" (reducing) or a reduction of indentation
matching a previous level's.
🙦 The decision to create code blocks in Python to avoid "dangling-else"-type
problems(eliminates confusion), including ungrouped single statement clauses.
🙦 Finally, no "holy brace wars" (e.g., where to place braces {} in other languages) can occur when
using indentation.
5. Multiple Statements on a Single Line (;)
🙦 The semicolon (;) allows multiple statements on a single line given that neither statement starts a
new code block. Here is a sample snip using the semicolon:
import sys; x = 'foo'; [Link](x + '\n')
6. Modules
🙦 Each Python script is considered a module. Modules have a physical presence as disk files.
When a module gets large enough or has diverse enough functionality, it may make sense to
move some of the code out to another module.
🙦 Code that resides in modules may belong to an application (i.e., a script that is directly executed),
or may be executable code in a library-type module that may be "imported" from another
module for invocation.
🙦 Modules can contain blocks of code to run, class declarations, function declarations, or any
combination of all of those.
IDENTIFIERS
7. WRITE SHORT NOTES ON IDENTIFIERS. (PART-B)
🙦 Identifiers are the set of valid strings that are allowed as names in a computer language. The
identifiers are reserved words that may not be used for any other purpose, or else a syntax error
will occur.
🙦 Python also has an additional set of identifiers known as built-ins, and although they are not
reserved words, use of these special names is not recommended.
Valid Python Identifiers
🙦 The rules for Python identifier strings are like most other high-level programming languages that
come from the C world:
1. First character must be a letter or underscore ( _ ).
2. Any additional characters can be alphanumeric or underscore.
3. Case-sensitive.
🙦 No identifiers can begin with a number, and no symbols other than the underscore are ever
6
allowed.
🙦 Case-sensitivity means that identifier foo is different from Foo, and both of those are different
from FOO.
Keywords
🙦 Python is a growing and evolving language, a list of keywords as well as an iskeyword() function
are available in the keyword module.
Python Keywords
and as assert break class Continue Def del elif else except

exec finally for from global if import in is lambda not

or pass print raise return try while with yield none

Built-ins
🙦 Python has a set of "built-in" names available at any level of Python code that are either set and/or
used by the interpreter.
🙦 Built-ins should be treated as "reserved for the system" and not used for any other purpose.
🙦 Treat them like global variables that are available at any level of Python code.
BASIC STYLE GUIDELINES
8. DISCUSS PYTHON BASIC STYLE GUIDELINES. (PART-B)
Comments
🙦 Comments should not be absent, nor should there be novellas. Keep the comments explanatory,
clear, short, and concise, but get them in there. In the end, it saves time and energy for everyone.
Indentation
🙦 Indentation plays a major role, to decide on a spacing style that is easy to read as well as the least
confusing.
🙦 Common sense also plays a role in choosing how many spaces or columns to indent.
1 or 2 Probably not enough; difficult to determine
which block of code statements belong to.

8 to 10 May be too many; code that has many


embedded levels will wrap around, causing
the source to be difficult to read.

🙦 Four spaces is very popular, not to mention being the preferred choice of Python's creator.
Five and six are not bad, but text editors usually do not use these settings, so they are not as
commonly used. Three and seven are borderline cases.
Choosing Identifier Names
🙦 Decide on short yet meaningful identifiers for variables. Although variable length is no longer an
issue with programming languages of today, it is still a good idea to keep name sizes reasonable
length.
Python Style Guide(s)
🙦 Guido van Rossum wrote up a Python Style Guide ages ago. It has since been replaced by no
fewer than three PEPs: 7 (Style Guide for C Code)( (relevant for extending Python with C).), 8
(Style Guide for Python Code), and 257 (DocString Conventions). (Python has official style
guides called PEPs (Python Enhancement Proposals))
🙦 These PEPs are archived, maintained, and updated regularly.
🙦 There is also another PEP, PEP 20, which lists the Zen of Python, starting the journey to discover
what Pythonic really means.
MODULE STRUCTURE AND LAYOUT
9. EXPLAIN MODULE STRUCTURE FOR PYTHON. (PART-B)
🙦 Modules are simply physical ways of logically organizing all your Python code. Within each file,
7
to set up a consistent and easy-to-read structure.
🙦 One such layout is the
following: # (1) startup line
(Unix)
# (2) module documentation
# (3) module imports
# (4) variable declarations
# (5) class declarations
# (6) function declarations
# (7) "main" body

Typical Python file structure


1. Startup line
 The startup line allows for script execution by name only (invoking the interpreter is not
required).
2. Module documentation
 Summary of a module's functionality and significant global variables; accessible externally as
module. doc .
3. Module imports
 Import all the modules necessary for all the code in current module; modules are imported once
(when this module is loaded); imports within functions are not invoked until those functions are
called.
4. Variable declarations
 Declare global variables that are used by multiple functions in this module. The use of local
variables over globals, for good programming style mostly, and to a lesser extent, for improved
performance and less memory usage.
5. Class declarations
 A class is defined when this module is imported and the class statement executed.

8
Documentation variable is class. doc .
6. Function declarations
 Functions that are declared here are accessible externally as [Link](); function is
defined when this module is imported and the def statement executed.
a. (def is a keyword in Python used to define a function.)
b. (When you import a Python module, you can access its functions using this syntax:
module_name.function_name())
7. "main" body
 All code at this level is executed, whether this module is imported or started as a script;
generally does not include much functional code, but rather gives direction depending on mode
of execution.
🙦 Most projects tend to consist of a single application and import any required modules. Thus it is
important to bear in mind that most modules are created solely to be imported rather than to
execute as scripts.
🙦 All Python statements in the highest level of code that is, the lines that are not indented will
be executed on import, whether desired or not. Because of this "feature," safer code is written
such that everything is in a function except for the code that should be executed on an
import of a module.
(When a Python file runs, it executes all code not inside a function or class. This happens even if it
is imported.)

PYTHON OBJECTS
10. DISCUSS IN DETAIL ABOUT PYTHON OBJECTS. (PART-B)
 Python uses the object model abstraction for data storage. Although Python is classified as an
"object-oriented programming (OOP) language," OOP is not required to create perfectly
working Python applications.
 All Python objects have the following three characteristics: an identity, a type, and a
value.
 IDENTITY Unique identifier that differentiates an object from all others. TYPE An object's
type indicates what kind of values an object can hold, what operations can be applied to such
objects, and what behavioral rules these objects are subject to.
 VALUE Data item that is represented by an object.
 All three are assigned on object creation and are read-only with one exception, the value. If an
object supports updates, its value can be changed; otherwise, it is also read-only.
 An object's value can be changed is known as an object's mutability.
Object Attributes
 Python objects have attributes, data values or executable code such as methods, associated with
them. Attributes are accessed in the dotted attribute notation, which includes the name of the
associated object.
 The most familiar attributes are functions and methods, but some Python types have data
attributes associated with them. Objects with data attributes include (but are not limited to):
classes, class instances, modules, complex numbers, and files.
STANDARD TYPES
11. COMMENT ON STANDARD DATA TYPES IN PYTHON. (PART-B)
1. Numbers (separate subtypes; three are integer types)
1.1 Integer (Whole numbers (e.g., 5, -10))
1.1.1 Boolean (Special integer type (True = 1, False = 0)).
1.1.2 Long integer (merged with int in Python 3).
1.2 Floating point real number (Numbers with a decimal point (e.g., 3.14, -0.01).)
1.3 Complex number (Numbers with a real and imaginary part (e.g., 3 + 4j).)
2. String (e.g., "Hello", 'Python')
3. List
9
 Definition: An ordered, mutable collection of items.
 Key Features:
o Can store duplicate values.
o Items can be changed (mutable).
o Use square brackets [ ].
Example:
my_list = [1, 2, 3, "Python"]
my_list[0] = 10 # Mutates the list
print(my_list) # Output: [10, 2, 3, "Python"]

4. Tuple
 Definition: An ordered, immutable collection of items.
 Key Features:
o Cannot change values (immutable).
o Use parentheses ( ).
Example:
my_tuple = (1, 2, 3, "Python")
# my_tuple[0] = 10 # This will cause an error (immutable)
print(my_tuple) # Output: (1, 2, 3, "Python")

5. Dictionary

Definition: An unordered, mutable collection of key-value pairs.


Key Features:
Each item has a unique key and a corresponding value.
Use curly braces { }.
Example:
my_dict = {"name": "Alice", "age": 25}
my_dict["age"] = 30 # Updates the value for the key 'age'
print(my_dict) # Output: {"name": "Alice", "age": 30}

OTHER BUILT-IN TYPES


12. EXPLAIN OTHER BUILT-IN DATA TYPES IN PYTHON. (PART-B)
1. Type
2. Null object (None)
3. File
4. Set/Frozenset
5. Function/Method
6. Module
7. Class

Type Objects :
What is type?
 The type function determines the type (or class) of any Python object.
 Every Python object belongs to a type.

1. Why types are not simple strings?


o A type describes the behavior of an object (e.g., what operations it supports).
o This information is complex and cannot fit in a single string, so Python uses objects

10
to represent types instead.
2. Example 1: Finding the type of an object
type(42)
Output: <class 'int'>
o type(42) tells us that 42 is an integer (int).
o <class 'int'> is not just a string—it is an object representing the integer type.
3. Example 2: Finding the type of a type object
type(type(42))
Output: <class 'type'>
o type(42) is an object of the type int.
o type(type(42)) tells us that the type of all type objects (like int, str) is type.
 type is the base type of all Python types (called the "mother of all types").
 Objects have a type (int, str, etc.).

None, Python's Null Object:


What is None?
 None is a special Python object that represents no value or null.
 It belongs to a unique type called NoneType.

1. Single Value:
o None is the only value of the NoneType.
o Example:
print(type(None))
Output: <class 'NoneType'>
2. No Operators or Built-in Functions (BIFs):
o You cannot perform any operations on None.
o Example:
print(None + 1)
Error: unsupported operand type(s)
3. No Attributes:
o None has no attributes that can be used.
o Example:
print([Link])
Error: 'NoneType' object has no attribute
4. Boolean Value:
o None always evaluates to False in a Boolean context.
o Example:
if None:
print("True")
else:
print("False")
Output: False
Usage of None:
 Used as a placeholder to represent "no value" or "not initialized."
result = None
# Means no value is assigned yet

INTERNAL TYPES
13. WRITE SHORT NOTES ON INTERNAL TYPES. (PART-B)
1. Code
11
2. Frame
3. Traceback
4. Slice
5. Xrange
1. Code Objects
Definition: Code objects are compiled pieces of Python code.
They are created when you use the compile() function or define a function.
 Executable using exec or eval().
exec() and eval() in Python
1. exec()
 Purpose: Executes a string of Python code dynamically.
 Can execute statements (e.g., loops, function definitions).
Example:
code = """
for i in range(3):
print(i)
"""
exec(code)
Output:
0
1
2

2. eval()
 Purpose: Evaluates a single expression (not statements) and returns the result.
 Useful for calculations or dynamic expressions.
Example:
result = eval("3 + 4")
print(result) # Output: 7

Key Differences
Feature exec() eval()
Use Executes statements Evaluates expressions
Return Value None Result of the expression
Example Input Loops, function defs Mathematical or logical expressions

 Contain only code, no execution context (e.g., no variable values or environment).


 Functions include additional details like the code object, function name, docstring, default
arguments, and global namespace.

2. Frame Objects
🙦 These are objects representing execution stack frames in Python. Frame objects contain all
the information (Such as variables, instructions to execute next, and the execution environment)
the Python interpreter needs to know during a runtime execution environment.
3. Traceback Objects
🙦 If exceptions are not caught or "handled," the interpreter exits with some diagnostic
information similar to the output shown below:
Traceback (innermost last): File "<stdin>", line N?, in ???
ErrorName: error reason
("innermost last" means that the one where the error happened)
<stdin>", display the filename
line N?,  Refers to the specific line number in the file where the exception occurred.
in??? Refers to the function or block name where the error occurred.

12
ErrorName: error reason  FileNotFoundError, the reason might be No such file or
directory.
4. Slice Objects
A slice object is a Python data structure that defines how to extract a portion of a sequence (like a
list, tuple, or string). Slicing provides flexible ways to access subsections of data.

Slice objects are created using the Python extended slice syntax.
This extended syntax allows for different types of indexing. These various types of indexing
include stride indexing
(Stride indexing allows for "step-like" access to elements in a
sequence. A positive stride iterates from left to right.
A negative stride iterates from right to left (reverse slicing).), multi-dimensional indexing, and
indexing using the Ellipsis type (The ellipsis (...) is used as a placeholder for unspecified
dimensions in multi-dimensional slicing,).
🙦 The syntax for multi-dimensional indexing:
o Sequence [start1 : end1, start2 : end2], or using the ellipsis, sequence [..., start1 :
end1].
🙦 Slice objects can also be generated by the slice()function (Built-in Function).
🙦 Stride indexing for sequence types allows for a third slice element that allows for "step"-like
access with a syntax of sequence[starting_index : ending_index ;: stride]

5. XRange Objects
In Python 2, xrange() is an efficient version of range() designed for generating large
ranges without consuming too much memory.

o range(): Generates and stores the entire list of numbers in memory.


o xrange(): Does not store the entire list in memory. Instead, it generates numbers lazily
o (on-demand) as you iterate through it.
 Memory Efficiency:
o If you use range(1, 1000000), Python creates a list containing 1,000,000 numbers,
consuming a significant amount of memory.
o With xrange(1, 1000000), numbers are generated one by one when needed, reducing
memory usage.
 When to Use xrange()?
o Use xrange() when working with extremely large ranges to conserve memory,
especially when iterating without needing the full list of numbers at once.

STANDARD TYPE OPERATORS


14. DISCUSS IN DETAIL ABOUT STANDARD TYPE OPERATORS. (PART-B)
Object Value Comparison
🙦 Comparison operators are used to determine equality of two data values between members of the
same type.
🙦 These comparison operators are supported for all built-in types. Comparisons yield Boolean TRue
or False values, based on the validity of the comparison expression.

13
Standard Type Value Comparison
Operator Operator Function

expr1 < expr1 is less than expr2


expr2
expr1 > expr2 expr1 is greater than expr2

expr1 <= expr2 expr1 is less than or equal to expr2

expr1 >= expr2 expr1 is greater than or equal to expr2

expr1 == expr2 expr1 is equal to expr2

expr1 != expr2 expr1 is not equal to expr2

expr1 <> expr2 expr1 is not equal to expr2

🙦 Numeric types will be compared according to numeric value in sign and magnitude, strings will
compare lexicographically, etc.
>>> 2 == 2 True
>>> 2.46 <= 8.33 True
>>> 5+4j >= 2-3j True
>>> 'abc' == 'xyz' False
>>> 'abc' < 'xyz' True
# Unicode value of 'a' 97 >>> # Unicode value of 'x' 120;
Python compares strings character by character from left to
right; 'a' (97) < 'x' (120): True.
No need to compare further; Python concludes 'abc' < 'xyz'.

>>> [3, 'abc'] == ['abc', 3] False


Python compares lists element by element in both value and
order. The comparison proceeds from left to right, and the first unequal element determines
the result. If all elements match in both value and order, the lists are considered equal.

Example: [3, 'abc'] == ['abc', 3]


 The two lists are compared element by element:
o First element: 3 (in the first list) ≠ 'abc' (in the second list). Mismatch here → Result:
False.
 The comparison stops after finding the first mismatch.
 All elements match in value and order, so the result is True.

>>> [3, 'abc'] == [3, 'abc'] True


 The two lists are compared element by element:
o First element: 3 == 3 → Match.
o Second element: 'abc' == 'abc' → Match.
🙦 Multiple comparisons can be made on the same line, evaluated in left-to-right order:
>>> 3 < 4 < 7 # same as ( 3 < 4 ) and ( 4 < 7 ) True
>>> 4 > 3 == 3 # same as ( 4 > 3 ) and ( 3 == 3 ) True
>>> 4 < 3 < 5 != 2 < 7 False

14
Object Identity Comparison
🙦 Python also supports the notion of directly comparing objects themselves. Objects can be
assigned to other variables (by reference).
🙦 Because each variable points to the same (shared) data object, any change effected through one
variable will change the object and hence be reflected through all references to the same object.

Example 1: foo1 and foo2 reference the same object


foo1 = foo2 = 4.3
🙦 The object's reference is assigned to both foo1 and foo2, resulting in both foo1 and foo2 aliased
to the same object.

Example 2: foo1 and foo2 reference the same object


foo1 = 4.3
foo2 = foo1
🙦 A numeric object with value 4.3 is created, then assigned to one variable. When foo2 = foo1
occurs, foo2 is directed to the same object as foo1 since Python deals with objects by
passing references. foo2 then becomes a new and additional reference for the original value. So
both foo1 and foo2 now point to the same object.
Example 3: foo1 and foo2 reference different objects
foo1 = 4.3
foo2 = 1.3 + 3.0
🙦 A numeric object is created, then assigned to foo1. Then a second numeric object is created, and
this time assigned to foo2.
🙦 Although both objects are storing the exact same value, there are indeed two distinct objects
in the system, with foo1 pointing to the first, and foo2 being a reference to the second.

🙦 Each object has associated with it a counter that tracks the total number of references that exist to
that object. This number simply indicates how many variables are "pointing to" any
particular object. This is called the reference count.
🙦 Python provides the is and is not operators to test if a pair of variables do indeed refer to the
same object. For example:
🙦 a is b is an equivalent expression to id(a) == id(b)
Standard Type Object Identity Comparison Operators
Operator Function

obj1 is obj2 obj1 is the same object as obj2

obj1 is not obj2 obj1 is not the same object as obj2

🙦 For example:
>>> a = [5, 'hat', -9.3]
>>> b = a
>>> a is b
True
>>> a is not b
False
15
>>>
>>> b = 2.5
>>> a is b
False

>>> a is not b
True
Boolean
In Python, you can link or negate logical expressions using the Boolean operators: and, or,
and not. These operators are Python keywords.

Operator Precedence
 The not operator has the highest precedence among Boolean operators.
 It is one level below comparison operators like <, >, or ==.
 and has a higher precedence than or.

Standard Type Boolean Operators


Operator Function

not expr Logical NOT of expr (negation)

Logical NOT: Negates expr (True → False, False


→ True).
expr1 and expr2 Logical AND of expr1 and expr2 (conjunction)

Logical AND: True if both expr1 and expr2 are True.

expr1 orexpr2 Logical OR of expr1 and expr2 (disjunction)

Logical OR: True if either expr1 or expr2 is True.

🙦 For example:
1. Negation with not

The not operator reverses the Boolean value of an expression.

x = 3.14

print(x < 5.0) # True (3.14 is less than 5.0)


print(not (x < 5.0)) # False (not reverses True to False)

2. Logical and (Conjunction)


The and operator returns True only if both conditions are True.

x, y = 3.14, -1024

print((x < 5.0) and (y > 2.71)) # False


# Explanation:
# x < 5.0 → True
16
# y > 2.71 → False
# True and False → False

3. Logical or (Disjunction)
The or operator returns True if at least one condition is True.
print((x < 5.0) or (y > 2.71)) # True
# Explanation:
# x < 5.0 → True
# y > 2.71 → False
# True or False → True

4. Using not with Identity Comparison


The is operator checks if two variables refer to the same object in memory. not can negate this
check.
print(not (x is y)) # True
# Explanation:
# x is y → False (x and y are not the same object)
# not False → True

Chained Comparisons
Python allows chaining comparisons, where multiple conditions are evaluated together using an
implicit and.
Example:
print(3 < 4 < 7) # True
# Explanation:
# (3 < 4) → True
# (4 < 7) → True
# True and True → True
The above is equivalent to: print((3 < 4) and (4 < 7)) # True

STANDARD TYPE BUILT-IN FUNCTIONS


15. EXPLAIN ABOUT STANDARD TYPE BUILT-IN FUNCTIONS. (PART-B)
🙦 Python also provides some BIFs that can be applied to all the basic object types: cmp(),
repr(), str(), type(), and the single reverse or back quotes (``) operator, which is functionally
equivalent to repr().
Standard Type Built-in Functions
Operator Function

cmp(obj1, obj2) Compares obj1 and obj2, returns integer i where:

(It has been removed in i < 0 if obj1 < obj2


Python 3 and replaced with
the == and is operators) i > 0 if obj1 > obj2

i == 0 if obj1 == obj2

repr(obj) or `obj` Returns evaluatable string representation of obj

str(obj) Returns printable string representation of obj

17
type(obj) Determines type of obj and return type object

1. type()
 Returns the type of an object.
 Syntax: type(object)
 Example:
print(type(4)) # <class 'int'>
print(type("Hello")) # <class 'str'>
print(type(type(4))) # <class 'type'>

🙦 The format is usually of the form: <object_something_or_another>. Any object displayed in this
manner generally gives the object type, an object ID or location, or other pertinent information.

cmp( ):
🙦 The cmp() BIF Compares two objects, say, obj1 and obj2, and returns a negative number
(integer) if obj1 is less than obj2, a positive number if obj1 is greater than obj2, and zero if obj1
is equal to obj2.
Purpose: Compares two objects and returns:

A negative number if obj1 < obj2

A positive number if obj1 > obj2

0 if obj1 == obj2

🙦 Here are some samples of using the cmp() BIF with numbers and strings.
print(cmp(3, 5)) # Output: -1 (3 < 5)
print(cmp(5, 3)) # Output: 1 (5 > 3)
print(cmp(3, 3)) # Output: 0 (3 == 3)

str( ) and repr( ) (and `` Operator):


🙦 The str( ) String and repr( ) Representation BIFs or the single back or reverse quote operator ( ``
) to either re-create an object through evaluation or obtain a human-readable view of the contents
of objects, data values, object types, etc.
🙦 To use these operations, a Python object is provided as an argument and some type of string
representation of that object is returned.
🙦 In the examples that follow, we take some random Python types and convert them to their string
representations.
>>> s="welcome"
>>> print(str(s))
welcome
>>> print(str(3+5))
8
>>> print(str(4))
4
>>> print(repr(3))
3
>>> print(repr(3+4))
7
>>> print(repr(s))
18
'welcome'
type( ) and isinstance( ):
🙦 Python does not support method or function overloading, so we are responsible for any
"introspection" of the objects that our functions are called with.
🙦 Fortunately, Python provides a BIF just for that very purpose. type() returns the type for any
Python object, not just the standard types.
🙦 Example: A script that shows how we can use isinstance() and type() in a runtime environment.
Checking the Type ([Link])
🙦 The function displayNumType() takes a numeric argument and uses the type() built-in to indicate
its type.
#!/usr/bin/env python
def displayNumType(num):
print (num, 'is', end=' ')
if isinstance(num, (int, float, complex)):
print (' a number of type:', type(num). name )
else:
print (' not a number at all!!')
displayNumType(-69)
displayNumType(98.6)
displayNumType(-5.2+1.9j)
displayNumType('xxx')
🙦 Running [Link], we get the following output:
-69 is a number of type: int
98.6 is a number of type: float
(-5.2+1.9j) is a number of type: complex
xxx is not a number at all!!
Python Type Operator and BIF Summary
🙦 The progressing shaded groups indicate hierarchical precedence from highest-to-lowest order.
Elements grouped with similar shading all have equal priority.
Standard Type Operators and Built-in Functions

Operator/Function Description

String representation

String representation

Built-in functions

cmp(obj1, obj2) Compares two objects

repr(obj) String representation

str(obj) String representation

type(obj) Determines object type

Value comparisons

< Less than

> Greater than

19
<= Less than or equal to

>= Greater than or equal to

== Equal to

!= Not equal to

<> Not equal to

Object comparisons

is The same as

is not Not the same as

Boolean operators

not Logical negation

and Logical conjunction

or Logical disjunction

REFERENCE BOOK:
1. Wesley J. Chun, "Core Python Programming", Pearson Education Publication, 2012.
IMPORTANT / POSSIBLE QUESTIONS
PART – A (1 MARK)
1. Who developed Python Programming Language?
a) Wick van Rossum b) Rasmus Lerdorf
c) Guido van Rossum d) Niene Stom
2. Which type of Programming does Python support?
a) object-oriented programming b) structured programming
c) functional programming d) all of the mentioned
3. Is Python case sensitive when dealing with identifiers?
a) no b) yes
c) machine dependent d) none of the mentioned
4. Which of the following is the correct extension of the Python file?
a) .python b) .pl
c) .py d) .p
5. All keywords in Python are in
a) Capitalized b) lower case
c) UPPER CASE d) None of the mentioned
6. Which of the following is used to define a block of code in Python language?
a) Indentationb) Key
c) Brackets d) All of the mentioned
20
7. Which of the following character is used to give single-line comments in Python?
a) // b) # c) ! d) /*
8. Python supports the creation of anonymous functions at runtime, using a construct called

a) pi b) anonymous
c) lambda d) none of the mentioned
9. What will be the output of the following Python code snippet if x=1?
x<<2
a) 4 b) 2 c) 1 d) 8
10. Which of the following functions is a built-in function in python?
a) factorial() b) print() c) seed() d) sqrt()
11. Which of the following is not a core data type in Python programming?
a) Tuples b) Lists c) Class d) Dictionary
12. Which one of the following is not a keyword in Python language?
a) pass b) eval c) assert d) nonlocal
13. Which of the following results in a SyntaxError?
a) ‘”Once upon a time…”, she said.’ b) “He said, ‘Yes!'”
c) ‘3\’ d) ”’That’s okay”’
14. What is the output of this expression, 3*1**3?
a) 27 b) 9 c) 3 d) 1
15. Which one of the following has the highest precedence in the expression?
a) Exponential b) Addition
c) Multiplication d) Parentheses

PART – B (5 MARKS)
1. Define Python.
2. Where did the Python originated from?
3. Define Variable.
4. Write short notes on Identifiers.
5. Discuss Python Basic Style Guidelines.
6. Explain Module Structure for Python.
7. Comment on Standard Data Types in Python.
8. Explain Other Built-In Data Types in Python.
9. Write short notes on Internal Types.
PART – C (10 MARKS)
1. Discuss in detail about Features of Python.
2. Explain about Variables and Assignment.
3. Discuss about Statements and Syntax in Python.
4. Discuss in detail about Python Objects.
5. Discuss in detail about Standard Type Operators.
6. Explain about Standard Type Built-In Functions.
7.
*** UNIT – I – COMPLETED ***

21

You might also like