UNIT-I Python
UNIT-I Python
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 Interactive
Python is multi-paradigm
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#).
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
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.
🙦 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
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
Type Objects :
What is type?
The type function determines the type (or class) of any Python object.
Every Python object belongs to a type.
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.).
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
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.
13
Standard Type Value Comparison
Operator Operator Function
🙦 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'.
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.
🙦 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
🙦 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.
🙦 For example:
1. Negation with not
x = 3.14
x, y = 3.14, -1024
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
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
i == 0 if obj1 == obj2
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:
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)
Operator/Function Description
String representation
String representation
Built-in functions
Value comparisons
19
<= Less than or equal to
== Equal to
!= Not equal to
Object comparisons
is The same as
Boolean operators
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