Python Programming Notes-III Cs
Python Programming Notes-III Cs
UNIT-I
Python – origins – features – variable and assignment - Python basics – statement and syntax –
Identifiers – Basic style guidelines – Python objects – Standard types and other built-in types –
Internal types – Standard type operators – Standard type built-in functions.
UNIT-II
UNIT-III
Mapping type: Dictionaries – Mapping type operators – Mapping type Built-in and Factory
Functions - Mapping type built in methods – Conditionals and loops – if statement – else
Statement – elif statement – conditional expression – while statement – for statement – break
statement – continue statement – pass statement – Iterators and the iter( ) function - Files and
Input/Output – File objects – File built-in functions – File built-in methods – File built-in
attributes – Standard files – command line arguments.
UNIT-IV
UNIT-V
Database Programming – Introduction - Basic Database Operations and SQL - Example of using
Database Adapters, Mysql - Regular Expression – Special Symbols and Characters – REs and
Python.
Learning Resources
Text Books
Title of Book Publisher Year of Publication 1 Wesley J. Chun Core Python Programming
Pearson Education Publication 2012
1. Wesley J. Chun Core Python Application Programming Pearson Education Publication 2015
3. Zed Shaw Learn Python the hard way Addition Wesley 2017
Python is Interpreted
Python is Interactive
Python is Object-Oriented
History of python
• Python was developed by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in Netherlands in 1990.
• Rossum wanted the name of his new language to be short, unique and mysterious.
• Inspired by Monty Python‘s Flying Circus, a BBC comedy series, he named the language
Python.
• Python became a popular programming language.
• It is widely used in both industry and academia because of its simple, concise and
extensive support of libraries.
• It is a general purpose, interpreted and object-oriented programming language.
• This is one of the most important reasons for the popularity of Python. Python has a
limited set of keywords.
• Its features such as simple syntax, usage of indentation 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 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.
>>>2*3+1
Hello World
• 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.
• 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.
➢ 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.
The assignment operator, denoted by the “=” symbol, is the operator that is used to assign
values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to
the variable with name “x”.
Note that the equal sign in programming is not the same as a truth statement in mathematics.
In math, the statement x = 2 declares the universal truth within the given framework, x is 2. In
programming, the statement x=2 means a known value is being associated with a variable
name, store 2 in x. Although it is perfectly valid to say 1 = x in mathematics, assignments in
Python always go left: meaning the value to the right of the equal sign is assigned to the variable
on the left of the equal sign. Therefore, 1=x will generate an error in Python. The assignment
operator is always last in the order of operations relative to mathematical, logical, and
comparison operators.
EXAMPLE: What value will y have after the following lines of code are executed?
x=1
y=x+1
x=2
y
While Python has become an essential language and a very useful skill for data analysts, it
requires some basic terminology to get started. If you have a limited programming background,
here are a few important terms to know:
Use a hashtag to leave comments, or notes, to yourself or others explaining elements of your
code. In Python, comments are ignored so they are not incorrectly included in the final product.
Keywords
Every programming language relies on certain words to convey meanings or perform specific
functions. For example, True and False are used to represent the truth value of an expression
within the Python Boolean, one of Python’s built-in data types.
Because variables can store different types of data, it’s important to input the correct data types
while programming. Python uses several data types, including numerics, strings, Booleans, lists,
and tuples.
Loops
Loops simplify the process of repeating an action for a specific number of steps or until a
condition is met. Python presents two types of loops when code needs to be
repeated: for and while.
Some rules and certain symbols are used with regard to statements in Python:
Some rules and certain symbols are used with regard to statements in Python: Hash mark (#)
indicates Python comments. NEWLINE (\n) is the standard line separator (one statement per
line) Backslash (\) continues a line.
classCls:
x=3# class variable
inst=Cls()
inst.x=inst.x+1# writes inst.x as 4 leaving Cls.x as 3
1.6 Identifiers
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.
Valid identifiers:
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
For Example
print(True or False)
print(not False)
Output
The 4 space rule is not always mandatory and can be overruled for continuation line.
2. Use docstrings :
There are both single and multi-line docstrings that can be used in Python. However, the
single line comment fits in one line, triple quotes are used in both cases. These are used to define
a particular program or define a particular function.
Example:
def exam():
"""This is single line doctoring"""
"""This is a multiline comment"""
The Python standard library is conservative and requires limiting lines to 79 characters.
The lines can be wrapped using parenthesis, brackets, and braces. They should be used in
preference to backslashes.
Example:
4. Use of regular and updated comments are valuable to both the coders and users:
There are also various types and conditions that if followed can be of great help from
programs and users point of view. Comments should form complete sentences. If a comment is a
full sentence, its first word should be capitalized, unless it is an identifier that begins with a
lower case letter. In short comments, the period at the end can be omitted. In block comments,
5. Use of trailing commas : This is not mandatory except while making a tuple.
Example:
tup = ("geek",)
5. Use Python’s default UTF-8 or ASCII encodings and not any fancy encodings, if it is
meant for international environment.
6. Use spaces around operators and after commas, but not directly inside bracketing
constructs:
a = f(1, 2) + g(3, 4)
7. Naming Conventions :
There are few naming conventions that should be followed in order to make the program
less complex and more readable. At the same time, the naming conventions in Python is a bit of
mess, but here are few conventions that can be followed easily.
There is an overriding principle that follows that the names that are visible to the user as
public parts of API should follow conventions that reflect usage rather than implementation.
Here are few other naming conventions:
9. Don’t use non-ASCII characters in identifiers if there is only the slightest chance people
speaking a different language will read or maintain the code.
10. Name your classes and functions consistently: The convention is to use CamelCase for
classes and lower_case_with_underscores for functions and methods. Always use self as the
name for the first method argument.
11. While naming of function of methods always use self for the first argument to instance
methods and cls for the first argument to class methods.If a functions argument name matches
with reserved words then it can be written with a trailing comma.
For example
num = 7
factorial = 1
if num < 0:
elif num == 0:
else:
factorial = factorial*i
Output
The factorial of 7 is 5040
o State - The attributes of an object represents its state. It also reflects the properties of an
object.
o Behavior - The method of an object represents its behavior.
o Identity - Each object must be uniquely identified and allow interacting with the other
objects.
The syntax of creating a class is given below.
Syntax:
class ClassName:
#statement_suite
The object is essential to work with the class attributes. Instantiate is a term used when we create
the object of any class, and the instance is also referred to as an object. The object is created
using the class name. The syntax is given below.
Syntax:
<object-name> = <class-name>(<arguments>)
Example –
Python’s built-in object types and some of the syntax used to code their literals that is, the
expressions that generate these objects.
Some of these types will probably seem familiar if you’ve used other languages; for instance,
numbers and strings represent numeric and textual values, respectively, and files provide an
interface for processing files stored on your computer.
1. Numbers
Python’s core object set includes the usual suspects: integers (numbers without a
fractional part), floating-point numbers (roughly, numbers with a decimal point in them), and
more exotic types (unlimited-precision “long” integers, complex numbers with imaginary parts,
fixed-precision decimals, and sets).
Although it offers some fancier options, Python’s basic number types are, well, basic.
Numbers in Python support the normal mathematical operations. For instance, the plus sign (+)
performs addition, a star (*) is used for multiplication, and two stars (**) are used for
exponentiation
a=5
b = 5.0
c = 2 + 4j
OUTPUT
• Sequence Operations
>>>S = 'Spam'
>>>len(S)# Length
4
>>>S[0]# The first item in S, indexing by zero-based position
'S'
>>>S[1]# The second item from the left
'p'
3. Lists
The Python list object is the most general sequence provided by the language. Lists are
positionally ordered collections of arbitrarily typed objects, and they have no fixed size. They are
also mutable unlike strings; lists can be modified in-place by assignment to offsets as well as a
variety of list method calls.
4. Tuples
He tuple object (pronounced “toople” or “tuhple,” depending on who you ask) is roughly
like a list that cannot be changed—tuples are sequences, like lists, but they are immutable, like
strings. Syntactically, they are coded in parentheses instead of square brackets, and they support
arbitrary types, nesting, and the usual sequence operations.
5. Files
File objects are Python code’s main interface to external files on your computer. They are
a core type, but they’re something of an oddball there is no specific literal syntax for creating
them. Rather, to create a file object, you call the built-in open function, passing in an external
filename as a string, and a processing mode string. For example, to create an output file, you
would pass in its name and the 'w' processing mode string to write data.
Python has many useful built in data types. Python variables can store different types of data
and can be created dynamically, without first defining a data type.
1.9.1 Integers
Integers are one of the Python data types. An integer is a whole number, negative, positive
or zero. In Python, integer variables can be defined by simply assigning a whole number to a
variable name. We can determine data type of a variable using the type() function.
>>> a = 5
>>> type(a)
<class 'int'>
>>> b = -2
>>> type(b)
<class 'int'>
>>> z = 0
Floating point numbers or floats are another Python data type. Floats are decimals, positive,
negative and zero. Floats can also be numbers in scientific notation which contain exponents. In
Python, a float can be defined using a decimal point when a variable is assigned.
>>> c = 6.2
>>> type(c)
<class 'float'>
>>> d = -0.03
>>> type(d)
<class 'float'>
>>> e = 6.02e23
>>> e
6.02e+23
>>> type(e)
<class 'float'>
To make sure a variable is a float instead of an integer even if it is a whole number, a trailing
decimal point is used. Note the difference when a decimal point comes after a whole number:
1.9.3 Boolean
The Boolean data type is either True or False. In Python, Boolean variables are defined
by the True and False key words. Note that True and False must have an Upper Case first letter.
Using a lowercase true returns an error.
a = True
1.9.4 String
Strings are sequences of letters, numbers, spaces and symbols. In Python, strings can be
almost any length and can contain spaces. String variables are assigned in Python using
quotation marks ' '.
string = 'z'
type(string)
<class 'str'>
string = 'Engineers'
type(string)
<class 'str'>
A numbers and decimals can be defined as strings too. If a decimal number is defined
using quotes ' ', it will be saved as a string rather than as a float. This is true of whole numbers as
well. Whole numbers defined using quotes will become strings just like decimal numbers defined
using quotes.
num = '5.2'
type(num)
<class 'str'>
num = '2'
type(num)
One final data type useful to engineers are complex numbers. A complex number is
defined in Python using a real component + imaginary componentj. The letter j must be used in
the imaginary component. Using the letter i will return an error. Note how imaginary numbers
can be added to integers and floats.
comp = 4 + 2j
type(comp)
<class 'complex'>
comp2 = 4 + 2i
^
SyntaxError: invalid syntax
intgr = 3
type(intgr)
<class 'int'>
comp_sum = comp + intgr
print(comp_sum)
(7+2j)
flt = 2.1
comp_sum = comp + flt
print(comp_sum)
(6.1+2j)
• Code
• Frame
• Traceback
• Slice
• Ellipsis
• Xrange
In case you were wondering about exceptions, they are now implemented as classes. In
older versions of Python, exceptions were implemented as strings. In Particular built in types
such as int, float, list, str, tuple, set, and dict all work this way. The attributes of the types
module are the built in types each with one or more names.
Code objects are executable pieces of Python source that are byte-compiled, usually as
return values from calling the compile() built-in function. Such objects are appropriate for
execution by either exec or by the eval() built-in function.
Code objects themselves do not contain any information regarding their execution
environment, but they are at the heart of every user-defined function, all of which do contain
some execution context. (The actual byte-compiled code as a code object is one attribute
belonging to a function). Along with the code object, a function's attributes also consist of the
administrative support which a function requires, including its name, documentation string,
default arguments, and global namespace.
1.10.2. Frames
These are objects representing execution stack frames in Python. Frame objects contain all
the information the Python interpreter needs to know during a runtime execution environment.
Some of its attributes include a link to the previous stack frame, the code object (see above) that
is being executed, dictionaries for the local and global namespaces, and the current instruction.
Each function call results in a new frame object, and for each frame object, a C stack frame is
created as well. One place where you can access a frame object is in a traceback object (see
below).
1.10.3. Tracebacks
When you make an error in Python, an exception is raised. If exceptions are not caught or
“handled,” the interpreter exits with some diagnostic information similar to the output shown
below:
The traceback object is just a data item that holds the stack trace information for an
exception and is created when an exception occurs. If a handler is provided for an exception, this
handler is given access to the traceback object.
Slice objects are created when using the Python extended slice syntax. This extended
syntax allows for different types of indexing. These various types of indexing include stride
indexing, multi-dimensional indexing, and indexing using the Ellipsis type. The syntax for multi-
dimensional indexing is sequence[start1 : end1, start2 : end2], or using the
ellipsis, sequence[…, start1 : end1]. Slice objects can also be generated by the slice() built-in
function. Extended slice syntax is currently supported only in external third party modules such
as the NumPy module and JPython.
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]. We will demonstrate an
example of stride indexing using JPython here:
1.10.5. Ellipsis
Ellipsis objects are used in extended slice notations as demonstrated above. These objects
are used to represent the actual ellipses in the slice syntax (…). Like the Null object, ellipsis
objects also have a single name, Ellipsis, and has a Boolean true value at all times.
All standard type objects can be tested for truth value and compared to objects of the same type.
Objects have inherent true or false values. Objects take a false value when they are empty, any
numeric representation of zero, or the Null object None.
• None
• Any numeric zero:
• 0 ([plain] integer)
• 0.0 (float)
• 0L (long integer)
• 0.0+0.0j (complex)
• "" (empty string)
• [] (empty list)
• () (empty tuple)
• {} (empty dictionary)
Any value for an object other than the those above is considered to have a true value, i.e., non-
empty, non-zero, etc. User-created class instances have a false value when their nonzero
( __nonzero__() ) or length ( __len__() ) special methods, if defined, return a zero value.
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 true or false values, based on the validity of the comparison expression. Python chooses to
interpret these values as the plain integers 0 and 1 for false and true, respectively, meaning that
each comparison will result in one of those two possible values. A list of Python's value
comparison operators is given in Table 1.
operator function
Note that comparisons performed are those that are appropriate for each data type. In other
words, numeric types will be compared according to numeric value in sign and magnitude,
strings will compare lexicographically, etc.
>>> 2 == 2
1
>>> 2.46 <= 8.33
1
>>> 5+4j >= 2-3j
Also, unlike many other languages, multiple comparisons can be made on the same line,
evaluated in left-to-right order:
The comparisons are strictly between object values, meaning that the comparisons are between
the data values and not the actual data objects themselves.
In addition to value comparisons, 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.
In order to understand this, you will have to think of variables as linking to objects now and be
less concerned with the values themselves. Let us take a look at three examples.
When you look at this statement from the value point-of-view, it appears that you are
performing a multiple assignment and assigning the numeric value of 4 to both
the foo1 and foo2 variables. This is true to a certain degree, but upon lifting the covers, you will
find that a numeric object with the contents or value of 4 has been created. Then that object's
reference is assigned to both foo1 and foo2, resulting in both foo1 and foo2 aliased to the same
object. Figure 4-1 shows an object with two references.
foo1 = 4
foo2 = foo1
This example is very much like the first: A numeric object with value 4 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. The same
figure above applies here as well.
foo1 = 4
foo2 = 1 + 3
This example is different. First, 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
Why did we choose to use boxes in our diagrams above? Well, a good way to visualize
this concept is to imagine a box (with contents inside) as an object. When a variable is assigned
an object, that creates a “label” to stick on the box, indicating a reference has been made. Each
time a new reference to the same object is made, another sticker is put on the box. When
references are abandoned, then a label is removed. A box can be “recycled” only when all the
labels have been peeled off the box. How does the system keep track of how many labels are on
a box?
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 the reference count that we introduced in the last chapter in Sections 3.5.5–3.5.7.
Python provides the is and is not operators to test if a pair of variables do indeed refer to the
same object. Performing a check such as
The object identity comparison operators all share the same precedence level and are presented
in Table 2.
operator function
operator function
In the example below, we create a variable, then another that points to the same object.
1.11.2. Boolean
operator function
Earlier, we introduced the notion that Python supports multiple comparisons within one
expression. These expressions have an implicit and operator joining them together.
Python anext() used for getting the next item from an asynchronous iterator
Function
Python bool() Return or convert a value to a Boolean value i.e., True or False
Function
Python breakpoint() It is used for dropping into the debugger at the call site during
Function runtime for debugging purposes
Python bytearray() Returns a byte array object which is an array of given bytes
Function
Python dir() Function Returns a list of the attributes and methods of any object
Python divmod() Takes two numbers and returns a pair of numbers consisting of their
Function quotient and remainder
Function object
Example:
Input: -29
Output: 29
Syntax
abs(number)
• number: Integer, floating-point number, complex number.
Example.
abs() Function with an Integer Argument
In this example, we will pass an Integer value as an argument to the abs() function in Python and
print its value to see how it works.
# An integer
var = -94
print('Absolute value of integer is:', abs(var))
Output:
Absolute value of integer is: 94
Output:
False
Example
Input: [True, False, False]
Output: True
Example
Python any() Function on Lists in Python. The below example returns True since at least one
element in the list (3rd element) is True.
print(any(l))
Output:
True
5 Mark :
10 Mark:
********UNIT I COMPLETED********
Integers
>>>type(1)
<class 'int'>
Floating-Point Numbers
A floating-point number, or float for short, is a number with a decimal place. 1.0 is a
floating-point number, as is -2.75. The name of the floating-point data type is float
>>>float("1.25")
1.25
import cmath
x=5
y=3
z = complex(x,y);
print (z.real)
print (z.imag)
Output:
They serve as a basis for expressions, which are used to modify data and execute
computations. Python contains several operators, each with its unique purpose.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
In addition to the standard arithmetic operators, there are operators for modulus,
exponentiation, and floor division.
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
** Exponent 4**2 = 16
The two variables "a" and "b" are defined in this code, which then applies several arithmetic
operations to them (including addition, subtraction, multiplication, division, modulus,
exponentiation, and floor division) and outputs the results.
Output
a + b :31
a - b :11
a * b :210
a / b :2.1
a % b :1
a ** b :16679880978201
a // b : 2
This code compares the values of python variables 'a' and 'b' and prints if they are equal, not
equal, greater than, less than, more than or equal to, and less than or equal to each other.
Output
a == b : False
a != b : True
PYTHON NOTES Page 40
a >b : False
a <b : True
a >= b : False
a <= b : True
= Assignment Operator a = 10
The Python assignment operators are shown in this code. It begins with the value of 'a' equal to
10, and then goes through the steps of addition, subtraction, multiplication, division, remainder,
exponentiation, and floor division, updating 'a' as necessary and outputting the results.
Output
a += 5 :105
a -= 5 :100
a *= 5 :500
a /= 5 :100.0
a %= 3 :1.0
a **= 2 :1.0
a //= 3 : 0.0
They work with integer binary representations, performing logical operations on each bit
location.
Python includes various bitwise operators, such as AND (&), OR (|), NOT (), XOR (), left shift
(), and right shift (>>).
Binary Ones
~ Inverts all the bits
Complement
Binary Ones
~ Inverts all the bits
Complement
Shift left by pushing zeros in from the right and let the leftmost bits fall
<< Binary Left Shift
off
Shift right by pushing copies of the leftmost bit in from the left, and let
>> Binary Right Shift
the rightmost bits fall off
The binary representations of the numbers 'a and b' are subjected to bitwise operations in this
code. It displays the results of binary AND, OR, XOR, Ones Complement, Left Shift, and Right
Shift operations.
Output
a &b :12
a | b :61
a ^ b :49
~a : -61
a >>2 :240
a >>2 :15
Python logical operators are used to compose Boolean expressions and evaluate their truth
values.
They are required for the creation of conditional statements as well as for managing the flow of
execution in programs.
Python has three basic logical operators: AND, OR, and NOT.
and Logical
If both of the operands are true then the condition becomes true. (a and b) is true.
AND
The code assigns the values 5 and 10 to variables x and y. It determines whether x is larger than
3 and y is less than 15. If both conditions are met, it writes "Both x and y are within the specified
range."
Output
Both x and y are within the specified range
Python membership operators are used to determine whether or not a certain value occurs within
a sequence.
They make it simple to determine the membership of elements in various data structures such
as lists, tuples, sets, and strings.
Python has two primary membership operators: the in and not in operators.
Evaluates to true if it does not find a variable in the x not in y, here not in results in a 1 if x
not in
specified sequence and false otherwise. is not a member of sequence y.
Output
Yes, banana is a fruit!
7. Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:
is not Returns true if both variables are not the same x is not y
object
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
print(x is y)
# returns False because x is not the same object as y, even if they have the same content
print(x == y)
Python provides several built-in functions that are useful for working with numeric data types
such as `int`, `float`, and `complex`. Here’s an overview of some of the most commonly used
numeric functions, along with examples:
1. `abs()`
The `abs()` function returns the absolute value of a number. It can be used with both integers
and floating-point numbers.
Syntax
abs(x)
x: A number (integer or float)
Example:
print(abs(-5)) # Output: 5
print(abs(3.7)) # Output: 3.7
print(abs(-7.4)) # Output: 7.4
2. `round()`
The `round()` function returns a number rounded to a specified number of decimal places. If
no number of decimals is specified, it rounds to the nearest integer.
Syntax:
round(number, ndigits)
Example:
print(round(3.14159, 2)) # Output: 3.14
print(round(2.718, 1)) # Output: 2.7
print(round(4.5)) # Output: 4
Syntax:
pow(base, exp[, mod])
Example:
print(pow(2, 3)) # Output: 8 (2 raised to the power of 3)
print(pow(3, 2)) # Output: 9 (3 raised to the power of 2)
print(pow(2, 3, 5)) # Output: 3 ((2^3) % 5 = 8 % 5 = 3)
Syntax:
min(iterable) or min(x, y, z, ...)
max(iterable) or max(x, y, z, ...)
Example:
numbers = [3, 1, 9, 7, 4]
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 9
print(min(5, 10, 2)) # Output: 2
print(max(5, 10, 2)) # Output: 10
5. `sum()`
The `sum()` function returns the sum of all elements in an iterable (e.g., list or tuple).
Syntax:
sum(iterable, start)
Example:
numbers = [1, 2, 3, 4]
print(sum(numbers)) # Output: 10
print(sum(numbers, 5)) # Output: 15 (adding 5 to the sum)
6. `divmod()`
The `divmod()` function takes two numbers and returns a tuple containing the quotient and
the remainder when dividing the first number by the second.
Syntax:
divmod(a, b)
Example:
result = divmod(9, 4)
print(result) # Output: (2, 1) (quotient = 2, remainder = 1)
7. `int()`
The `int()` function converts a number or string to an integer.
Syntax:
int(x)
Example:
print(int(3.5)) # Output: 3 (converts float to int)
print(int("123")) # Output: 123 (converts string to int)
8. `float()`
The `float()` function converts a number or a string to a floating-point number.
Syntax:
float(x)
Example:
print(float(5)) # Output: 5.0
print(float("3.14")) # Output: 3.14
9. `complex()`
The `complex()` function creates a complex number from real and imaginary parts.
Syntax:
complex(real, imag)
Example:
c1 = complex(2, 3)
c2 = complex(1, -4)
print(c1) # Output: (2+3j)
print(c2) # Output: (1-4j)
10. `isinstance()`
The `isinstance()` function is used to check whether an object is an instance of a specified
class or a tuple of classes.
Syntax
isinstance(object, classinfo)
Example:
print(isinstance(5, int)) # Output: True
print(isinstance(5.5, float)) # Output: True
print(isinstance("hello", str)) # Output: True
print(isinstance(5, float)) # Output: False
Example
import math
.
2.6 Sequences
In Python, sequence is the generic term for an ordered set. There are several types of sequences
in Python, the following three are the most important.
Lists are the most versatile sequence type. The elements of a list can be any object, and lists
are mutable - they can be changed. Elements can be reassigned or removed, and new elements
can be inserted.
Tuples are like lists, but they are immutable - they can't be changed.
Strings are a special type of sequence that can only store characters, and they have a special
notation. However, all of the sequence operations described below can also be used on strings.
2.6.1 Strings:
In other languages, the elements in arrays and sometimes the characters in strings may be
accessed with the square brackets, or subscript operator.
>>>"Hello, world!"[0]
'H'
>>>"Hello, world!"[1]
'e'
>>>"Hello, world!"[2]
Indexes are numbered from 0 to n-1 where n is the number of items (or characters), and they are
given to the characters from the start of the string:
H e l l o , w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12
Negative indexes (numbered from -1 to -n) are counted from the end of the string:
H e l l o , w o r l d !
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
str1 = "Hello"
str2 = " World"
print(str1*3) # prints HelloHelloHello
print(str1+str2) # prints Hello world
print(str1[4]) # prints o
print(str1[2:4]) # prints ll
print('w' in str1) # prints false as w is not present in str1
print('Wo' not in str2) # prints false as Wo is present in str2.
print(r'Hello\n world') # prints Hello\n world as it is written
print("The string str1 : %s"%(str1)) # prints The string str : Hello
OUTPUT
HelloHelloHello
Hello World
o
• len()
• lower()
• upper()
• replace()
• join()
• split()
• find()
• index()
• isalnum()
• isdigit()
• isnumeric()
• islower()
• isupper()
1. len()
len(string)
Example:
str1="Python Language"
print(len(str1))
Output:
15
str.lower()
Example:
str=”PyTHOn”
print(str.lower())
Output:
python
3. upper ()
In python upper() method converts all the character to uppercase and returns a uppercase string.
Syntax:
str.upper()
Example:
str=”PyTHOn”
print(str.upper())
Output:
PYTHON
4. replace()
In python replace() method replaces the old sequence of characters with the new sequence. If the
optional argument count is given, only the first count occurrences are replaced.
Syntax:
Output:
python
PYTHON
Old String:
Java is Object-Oriented and Java is Portable
New String:
Python is Object-Oriented and Python is Portable
Old String:
Java is Object-Oriented and Java is Portable
New String:
Python is Object-Oriented and Java is Portable
New String:
Python is Object-Oriented and Portable
Python join() method is used to concat a string with iterable object. It returns a new string which
is the concatenation of the strings in iterable. It allows various iterables like: List, Tuple, String
etc.
Syntax:
str.join(sequence)
Example:
Output:
N:N:R:G
6. split()
In python split() method splits the string into a comma separated list. It separates string based on
the separator delimiter. The string splits according to the space if the delimiter is not provided.
Syntax:
str.split([sep=”delimiter”])
Output:
7. find()
In python find() method finds substring in the whole string and returns index of the first match. It
returns -1 if substring does not match.
Syntax:
str.find(sub[, start[,end]])
Output:
7 -1 12 7
In python index() method is same as the find() method except it returns error on failure. This
method returns index of first occurred substring and an error if there is no match found.
Syntax:
index(sub[, start[,end]])
1.8 Lists:
In Python, a list is a built-in data structure that is used to store an ordered
collection of items. Lists are mutable, meaning that their contents can be changed after the list
has been created. They can hold a various of data types, including integers, floats, strings, and
even other lists.
Example:
print(a)
Output
[1, 'apple', 3.14, [5, 6]]
A list is created using square brackets. For example, an empty list would be initialized like this:
spam=[]
Example:
# List of integers
a = [1, 2, 3, 4, 5]
# List of strings
print(a)
print(b)
print(c)
Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in
Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with
different qualities and usage.
List Methods
• append(): Adds an element to the end of the list.
• copy(): Returns a shallow copy of the list.
• clear(): Removes all elements from the list.
• count(): Returns the number of times a specified element appears in the list.
• extend(): Adds elements from another list to the end of the current list.
• index(): Returns the index of the first occurrence of a specified element.
• insert(): Inserts an element at a specified position.
• pop(): Removes and returns the element at the specified position (or the last element if no
index is specified).
• remove(): Removes the first occurrence of a specified element.
• reverse(): Reverses the order of the elements in the list.
• sort(): Sorts the list in ascending order (by default).
1. append():
a = [1, 2, 3]
a.append(4)
print(a)
Output
[1, 2, 3, 4]
2. copy():
Syntax: list_name.copy()
a = [1, 2, 3]
b = a.copy()
print(b)
Output
[1, 2, 3]
3. clear():
Syntax: list_name.clear()
In the code below, we will clear all elements from the list.
a = [1, 2, 3]
a.clear()
print(a)
Output
4. count():
Syntax: list_name.count(element)
In the code below, we will count the occurrences of a specific element in the list.
a = [1, 2, 3, 2]
print(a.count(2))
Output
2
5. extend():
Syntax: list_name.extend(iterable)
In the code below, we will extend the list by adding elements from another list.
a = [1, 2]
a.extend([3, 4])
print(a)
Output
[1, 2, 3, 4]
6. index():
Syntax: list_name.index(element)
In the code below, we will find the index of a specific element in the list.
a = [1, 2, 3]
print(a.index(2))
7. insert():
Syntax: list_name.insert(index, element)
In the code below, we will insert an element at a specific position in the list.
a = [1, 3]
# Insert 2 at index 1
a.insert(1, 2)
print(a)
Output
[1, 2, 3]
8. pop():
Syntax: list_name.pop(index)
In the code below, we will remove the last element from the list.
Python
a = [1, 2, 3]
a.pop()
print(a)
Output
[1, 2]
9. remove():
Syntax: list_name.remove(element)
In the code below, we will remove the first occurrence of a specified element from the list.
a = [1, 2, 3]
a.remove(2)
print(a)
Output
[1, 3]
10. reverse():
Syntax: list_name.reverse()
In the code below, we will reverse the order of the elements in the list.
a = [1, 2, 3]
a.reverse()
print(a)
Output
[3, 2, 1]
11. sort():
Syntax: list_name.sort(key=None, reverse=False)
In the code below, we will sort the elements of the list in ascending order
Python
a = [3, 1, 2]
a.sort()
print(a)
Output
[1, 2, 3]
2.9 Tuples:
o Tuples are an immutable data type, meaning their elements cannot be changed after they
are generated.
o Each element in a tuple has a specific order that will never change because tuples are
ordered sequences.
What is Immutable in Tuples?
Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in Python.
• Like Lists, tuples are ordered and we can access their elements using their index values
• We cannot update items to a tuple once it is created.
• Tuples cannot be appended or extended.
• We cannot remove items from a tuple once it is created.
t = (1, 2, 3, 4, 5)
print(t[1])
print(t[4])
t = (1, 2, 3, 4, 2, 3)
print(t)
# updating an element
t[1] = 100
print(t)
Output:
Forming a Tuple:
Example:
print(t)
print(type(t))
Output
(10, 20, 30)
<class 'tuple'>
t = (10, 5, 20)
Output
Value in t[0] = 10
Value in t[1] = 5
Value in t[2] = 20
2. Access Tuple using Negative Index
In the above methods, we use the positive index to access the value in Python, and here we will
use the negative index within [].
Python
t = (10, 5, 20)
t = ( 0, 1)
del t
print(t)
5 Mark:
Write about the Lists with example?
Discuss the Tuples?
Write the Strings with example?
Write the Floating points numbers ?
10 Mark:
Explain about the Numeric type functions?
Write the numbers and operators?
Discuss about the Strings and strings operators?
Write the string build in methods?
********UNIT II COMPLETED********
• The keys of the dictionary are arbitrary. As the value, we can use different kind of
elements like lists, integers or any other mutable type objects.
• Method len(d)
• Operation d[k]
It will return the item of d with the key ‘k’. It may raise KeyError if the key is not mapped.
• Method iter(d)
This method will return an iterator over the keys of dictionary. We can also perform this taks by
using iter(d.keys()).
The get() method will return the value from the key. The second argument is optional. If the key
is not present, it will return the default value.
• Method keys()
• Method values()
• Method update(elem)
Example,
myDict={'ten':10,'twenty':20,'thirty':30,'forty':40}
print(myDict)
print(list(myDict.keys()))
print(list(myDict.values()))
myDict.update({'fifty':50})
print(myDict)
Output
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40}
['ten', 'twenty', 'thirty', 'forty']
[10, 20, 30, 40]
[('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)]
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50}
3.2 DICTIONARIES
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and
must be immutable.
Example: Here, The data is stored in key: value pairs in dictionaries, which makes it easier to
find values.
PYTHON NOTES Page 70
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
2
print(d)
Output
print(d1)
print(d2)
Output
Dictionary with the use of Integer Keys:
{1: 'Python', 2: 'For', 3: 'Python'}
The addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Output
ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO
The items of the dictionary can be deleted by using the del keyword as given below.
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.
How are all these comparisons performed? Like lists and tuples, the process is a bit more
complex than it is for numbers and strings.
For sequence types, an index offset is the sole argument or subscript to access a single element of
a sequence. For a dictionary, lookups are by key, so that is the argument rather than an index.
The key-lookup operator is used for both assigning values to and retrieving values from a
dictionary:
d[k] = v # set value 'v' in dictionary with key 'k' d[k] # lookup value in dictionary with
key 'k'
In the first comparison, dict1 is deemed smaller because dict2 has more elements (2 items vs. 0
items). After adding one element to dict1, it is still smaller (2 vs. 1), even if the item added is
also in dict2.
If the argument is an iterable, i.e., a sequence, an iterator, or an object that supports iteration,
then each element of the iterable must come in pairs. For each pair, the first element will be a
new key in the dictionary with the second item as its value. Taking a cue from the official Python
documentation for dict():
>>> dict(zip(('x', 'y'), (1, 2))) {'y': 2, 'x': 1} >>> dict([['x', 1], ['y', 2]]) {'y': 2, 'x': 1} >>>
dict([('xy'[i-1], i) for i in range(1,3)]) {'y': 2, 'x': 1}
• len()
The len() BIF is flexible. It works with sequences, mapping types, and sets (as we will find out
later on in this chapter). For a dictionary, it returns the total number of items, that is, key-value
pairs:
>>> dict2 = {'name': 'earth', 'port': 80} >>> dict2 {'port': 80, 'name': 'earth'} >>> len(dict2) 2
PYTHON NOTES Page 77
• hash()
The hash() BIF is not really meant to be used for dictionaries per se, but it can
be used to determine whether an object is fit to be a dictionary key (or not). Given an object as
its argument, hash() returns the hash value of that object. The object can only be a dictionary key
if it is hashable (meaning this function returns a[n integer] value without errors or raising an
exception). Numeric values that are equal (when pitted against each other using a comparison
operator) hash to the same value (even if their types differ). A TypeError will occur if an
unhashable type is given as the argument to hash() (and consequently if an attempt is made to
use such an object as the key when assigning a value to a dictionary):
>>> hash([]) Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: list objects are
unhashable >>> >>> dict2[{}] = 'foo' Traceback (most recent call last): File "<stdin>", line 1,
in ? TypeError: dict objects are unhashable
Basic dictionary methods focus on their keys and values. These are keys(), which returns a
list of the dictionary's keys, values(), which returns a list of the dictionary's values, and items(),
which returns a list of (key, value) tuple pairs. These are useful when you wish to iterate through
a dictionary's keys or values, albeit in no particular order.
In Python versions prior to 2.4, you would have to call a dictionary’s keys() method to get
the list of its keys, then call that list’s sort() method to get a sorted list to iterate over. Now a
built-in function named sorted(), made especially for iterators, exists, which returns a sorted
iterator:
The update() method can be used to add the contents of one dictionary to another.
Any existing entries with duplicate keys will be overridden by the new incoming entries.
Nonexistent ones will be added. All entries in a dictionary can be removed with
the clear() method.
o if statement
o if else statement
o if elif else statement
o nested if else statement
3.6.1. if statement
General form:
if BOOLEAN EXPRESSION:
STATEMENTS
Flowchart of an if statement
Here’s an example:
age = 18
In this example, the if statement checks if the value of the variable age is greater than or equal to
18. If it is, the code inside the if statement is executed, which in this case is simply printing a
message to the console.
The if else statement is used to execute one block of code if a condition is true, and another block
of code if the condition is false.
if BOOLEAN EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False
Here’s an example:
age = 16
The if elif else statement is used to check multiple conditions, and execute a specific block of
code based on which condition is true.
if x < y:
STATEMENTS_A
elif x > y:
STATEMENTS_B
else:
STATEMENTS_C
Here’s an example:
age = 16
In this example, the first if statement checks if the value of age is greater than or equal to 18. If it
is, the message "You are old enough to vote." is printed. If not, the elif statement checks if age is
greater than or equal to 16. If it is, the message "You can drive but cannot vote." is printed. If
neither of these conditions are true, the else statement executes, and the message "You cannot
drive or vote yet." is printed.
The nested if else statement is used when we need to check a condition inside another condition.
if x < y:
STATEMENTS_A
else:
if x > y:
STATEMENTS_B
else:
STATEMENTS_C
age = 18
gender = "female"
In this example, the first if statement checks if age is greater than or equal to 18. If it is, the
nested if statement checks if the value of gender is "male". If it is, the message "You are a male
and old enough to vote." is printed. If not, the message "You are a female and old enough.
A while loop statement in Python is used to repeatedly execute a block of code as long as a
condition is true.
It is typically used when you don’t know how many times the loop will run in advance.
>> P
>> Y
>> T
>> H
>> O
>> N
The break statement is used to immediately leave the body of its loop. The next statement to be
executed is the first one after the body
foriin[12,16,17,24,29]:
output:
12
16
done
Continue statement is a loop control statement that forces to execute the next iteration of
the loop while skipping the rest of the code inside the loop for the current iteration only,
i.e. when the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped for the current iteration and the next
iteration of the loop will begin.
Example,
a = 33
b = 200
if b> a:
pass
The python iter function is used to return an iterator for the object. The iter() is used to create an
object that will iterate one element at a time. The iter() takes two optional arguments as input.
iter(object, sentinel)
The python iter() takes 2 optional parameters. The two optional parameters are:
object- this parameter is the object whose iterator must be created (tuples, sets, and so on)
For the provided object, the iter() function returns an iterator object.
The TypeError exception is raised if the user-defined function does not implement the _next_(),
the _iter_(), or the _getitem()_.
Iter() produces an iterator until the sentinel character isn’t found if the sentinel parameter is also
provided.
EXAMPLE,
# list of vowels
vowels =['a','e','i','o','u']
vowels_iter=iter(vowels)
print(next(vowels_iter))# 'a'
print(next(vowels_iter))# 'e'
print(next(vowels_iter))# 'i'
print(next(vowels_iter))# 'u'
Output:
The _iter_() in Python is used to return an iterator object each element at a time.
Example:
iter_lst = iter(lst123)
while True:
try:
print(iter_lst.__next__())
except:
break
Output:
11
22
44
55
• A file object allows us to use, access and manipulate all the user accessible files.
• One can read and write any such files.
• When a file operation fails for an I/O-related reason, the exception IOError is raised.
• This includes situations where the operation is not defined for some reason, like seek() on
a tty device or writing a file opened for reading.
• Files have the following methods:
open(file_address, access_mode)
The mode parameter is optional and defaults to ‘r‘, which means opening the file in read mode.
There are several modes in which we can open a file:
Once we have opened a file, we can read from or write to a file using Python methods
like read(), readline(), write(), and writelines().
# Reading a file
f = open(__file__, 'r')
#read()
text = f.read(10)
print(text)
f.close()
3) readline([size]): It reads the first line of the file i.e till a newline character or an EOF in
case of a file having a single line and returns a string. If the size argument is present and
non-negative, it is a maximum byte count (including the trailing newline) and an
incomplete line may be returned. An empty string is returned only when EOF is
encountered immediately.
f = open(__file__, 'r')
#readline()
text = f.readline(20)
print(text)
f.close()
Failing to do so can lead to resource leaks, which can slow down our program and potentially
cause other issues.
For example:
Python has a built-in function open() to open a file. Which accepts two arguments, file name and
access mode in which the file is accessed. The function returns a file object which can be used to
perform various operations like reading, writing, etc.
Syntax:
access-mode Description
"w" Write - Opens a file for writing, creates the file if it does not exist.
"r" Read - Default value. Opens a file for reading, error if the file does not exist.
"a" Append - Opens a file for appending, creates the file if it does not exist.
"x" Create - Creates the specified file, returns an error if the file exists.
"w+" Open a file for updating (reading and writing), overwrite if the file exists.
"r+" Open a file for updating (reading and writing), doesn’t overwrite if the file exists.
In addition you can specify if the file should be handled as binary or text mode
access-mode Description
Example:
fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully with read mode only")
Output:
fileptr = open("myfile1.txt","x")
if fileptr:
file.close()
1
Close the file. A closed file cannot be read or written any more.
file.flush()
2
Flush the internal buffer, like stdio'sfflush. This may be a no-op on some file-like objects.
file.fileno()
3
Returns the integer file descriptor that is used by the underlying implementation to request
I/O operations from the operating system.
file.isatty()
4
Returns True if the file is connected to a tty(-like) device, else False.
5 file.next()
file.read([size])
6
Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
file.readline([size])
7
Reads one entire line from the file. A trailing newline character is kept in the string.
file.readlines([sizehint])
8 Reads until EOF using readline() and return a list containing the lines. If the optional
sizehint argument is present, instead of reading up to EOF, whole lines totalling
approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.
file.seek(offset[, whence])
9
Sets the file's current position
file.tell()
10
Returns the file's current position
file.truncate([size])
11
Truncates the file's size. If the optional size argument is present, the file is truncated to (at
most) that size.
file.write(str)
12
Writes a string to the file. There is no return value.
file.writelines(sequence)
13
Writes a sequence of strings to the file. The sequence can be any iterable object producing
strings, typically a list of strings.
• flush() method
The Python File flush() method flushes the internal buffer. This internal buffer is
maintained to speed up file operations.
PYTHON NOTES Page 98
For instance, whenever a write operation is performed on a file, the contents are first
written in the internal buffer; which is then transferred into the destination file once the buffer is
full. This is done to prevent frequent system calls for every write operation. And once the file is
closed, Python automatically flushes the buffer. But you may still want to flush the data before
closing any file.
Syntax
fileObject.flush();
Parameters
Example:
# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
# Here it does nothing, but you can call it with read operation.
fo.flush()
fo.close()
Output:
Name of the file: foo.txt
• fileno() method
The Python File fileno() method returns the file descriptor (or file handle) of an open
file. A file descriptor is an unsigned integer that is used by the operating system to identify the
open files in an os kernel. It only holds non-negative values.
Syntax
fileObject.fileno();
Parameters
Return Value
Example
The following example shows the usage of the Python File fileno() method. Here, we are trying
to open a file "foo.txt" in the writing binary(wb) mode using a file object. Then, the fileno()
method is called on this file object to retrieve the file descriptor referring to the current file.
# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
fid = fo.fileno()
print("File Descriptor: ", fid)
• readline() method
The Python File readline() method reads one entire line from the file. This method
appends a trailing newline character ('\n') at the end of the line read.
The readline() method also accepts an optional argument where one can specify the number
of bytes to be read from a line including the newline character. By default, this optional
argument will be 0, therefore, reading the entire line.
Syntax
fileObject.readline(size);
Parameters
• size − This is the number of bytes to be read from the file.
Return Value
Example
Let us use an existing file "foo.txt" to read a line from it using the Python File readline() method.
The contents in the foo.txt file are as follows −
The following example shows the usage of readline() method on the demo file mentioned above.
# Open a file
fo = open("foo.txt", "r+")
print("Name of the file: ", fo.name)
line = fo.readline()
print("Read Line:", line)
• truncate() method
The Python File truncate() method truncates or shortens a file's size. In other words,
this method removes or deletes the contents of a file, and replaces them with some garbage (or
null) values to maintain the size. The size of this file is defaulted to the current position in it.
This method accepts an optional size argument where the file is truncated to (at most)
that size. The default value of this argument is the current file position. However, if the size
argument exceeds the current size of the file, the file is increased to that specified size by adding
either undefined content to the file, or zeroes. The result becomes platform-dependent.
Note − The truncate() method would not work in case a file is opened in read-only mode.
Syntax
fileObject.truncate(size)
Parameters
• size − (Optional) The size at which a file is to be truncated.
Return Value
Example
The following example shows the usage of the Python File truncate() method.
# Open a file
fo = open("foo.txt", "w+")
print("Name of the file: ", fo.name)
line = fo.readline()
print("Read Line:", line)
• The built-in class attributes provide us with information about the class.
• Using the dot (.) operator, we may access the built-in class attributes.
def __init__(self):
print("The __init__ method")
Open Compiler
# creating a class say Tutorialspoint
class pythoncls:
'Welcome to Python'
def __init__(self):
print("The __init__ method")
In the Python code below, we print the name of the class using the __name__ class attribute
Open Compiler
class pythoncls:
'Welcome to Python'
def __init__(self):
print("The __init__ method")
# getting the name of the class using built-in __name__ class attribute
print(pythoncls.__name__)
1. Text Files:
• Python's built-in `open()` function is used for reading from and writing to text files.
Example:
content = f.read()
2. CSV Files
• CSV (Comma Separated Values) files are used to store tabular data.
• Python's `csv` module provides methods to work with CSV files.
Example:
import csv
reader = csv.reader(f)
print(row)
3. JSON Files
• JSON (JavaScript Object Notation) is commonly used for data exchange.
• Python’s `json` module allows for parsing and serializing JSON data.
Example:
import json
data = json.load(f)
INI Files - Often used to store configurations in sections, they are handled with the
`configparser` module.
Example:
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
Logging
Example:
import logging
logging.basicConfig(filename='app.log', level=logging.DEBUG)
Pickling
• Python has a `pickle` module for serializing and deserializing Python objects to/from
files.
• Useful for saving and loading complex Python objects.
Example:
import pickle
pickle.dump(data, f)
loaded_data = pickle.load(f)
Here are a few commonly used standard Python modules (files) from the standard library:
• os: Provides functions to interact with the operating system, such as file manipulation,
directories, and environment variables.
Example:
import os
Example:
Example:
import math
Example:
now = datetime.now()
• random: Provides functions for generating random numbers and performing random
operations.
Example:
import random
Example:
import re
Example:
import subprocess
subprocess.run(['ls', '-l'])
There are many options to read python command line arguments. The three most common ones
are:
1. Python sys.argv
2. Python getopt module
3. Python argparse module
import sys
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Below image illustrates the output of a sample run of above program.
Python getopt module is very similar in working as the C getopt() function for parsing
command-line parameters. Python getopt module is useful in parsing command line arguments
where we want user to enter some options too. Let’s look at a simple example to understand this.
import getopt
import sys
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)
Above example is very simple, but we can easily extend it to do various things. For example, if
help option is passed then print some user friendly message and exit. Here getopt module will
automatically parse the option value and map them. Below image shows a sample run.
Python argparse module is the preferred way to parse command line arguments. It provides a lot
of option such as positional arguments, default value for arguments, help message, specifying
data type of argument etc. At the very simplest form, we can use it like below.
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
5 MARK
10 MARK
UNIT – IV
Recursion: There are no “for” or “while” loop in functional languages. Iteration in functional
languages is implemented through recursion.
Functions are First-Class and can be Higher-Order: First-class functions are treated as first-
class variable. The first-class variables can be passed to functions as a parameter, can be returned
from functions or stored in data structures.
Variables are Immutable: In functional programming, we can’t modify a variable after it’s
been initialized. We can create new variables – but we can’t modify existing variables.
Example,
# pure functions
def pure_func(List):
New_List = []
for i in List:
New_List.append(i**2)
return New_List
# Driver's code
Original_List = [1, 2, 3, 4]
Modified_List = pure_func(Original_List)
Output,
• Built-in library function: These are Standard functions in Python that are available to
use.
• User-defined function: We can create our own functions based on our requirements.
Example,
def fun():
print("Welcome to GFG")
After creating a function in Python we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
Example,
def fun():
print("Welcome to GFG")
fun()
Output:
Welcome to GFG
def shout(text):
print(shout('Hello'))
yell = shout
print(yell('Hello'))
Output,
HELLO
HELLO
The map, filter, and reduce functions in Python are higher-order functions that work on
sequences of data, such as lists or other iterable objects.
1.map() - Python's map() method applies a specified function to each item of an iterable (such as
a list, tuple, or string) and then returns a new iterable containing the results.
map(function, iterable)
The first argument passed to the map function is itself a function, and the second argument
passed is an iterable (sequence of elements) such as a list, tuple, set, string, etc.
2. filter() - The filter() function in Python filters elements from an iterable based on a given
condition or function and returns a new iterable with the filtered elements.
filter(function, iterable)
Here also, the first argument passed to the filter function is itself a function, and the second
argument passed is an iterable (sequence of elements) such as a list, tuple, set, string, etc.
You are given a list of integers and should filter the even numbers from the list.
Output:
24
Evens = [2, 4]
The function argument is a function that takes two arguments and returns a single value. The
first argument is the accumulated value, and the second argument is the current value from the
iterable.
The optional initializer argument is used to provide an initial value for the accumulated result. If
no initializer is specified, the first element of the iterable is used as the initial value.
Here's an example that demonstrates how to use reduce() to find the sum of a list of numbers:
Example 1:
You are given a list containing some integers and you should find the sum of all elements in the
list using reduce function. Below is the solution of the problem:
# Our Iterable
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# add function is passed as the first argument, and num_list is passed as the second argument
sum = reduce(add, num_list)
print(f"Sum of the integers of num_list : {sum}")
4.apply():The apply() method is one of the most common methods of data preprocessing. It
simplifies applying a function on each element in a pandas Series and each row or column in a
pandas DataFrame. In this tutorial, we'll learn how to use the apply() method in pandas — you'll
need to know the fundamentals of Python and lambda functions. If you aren't familiar with these
or need to brush up your Python skills, you might like to try our free Python Fundamentals
course.
Series form the basis of pandas. They are essentially one-dimensional arrays with axis labels
called indices.There are different ways of creating a Series object (e.g., we can initialize a Series
with lists or dictionaries). Let’s define a Series object with two lists containing student names as
indices and their heights in centimeters as data:
import pandas as pd
import numpy as np
from IPython.display import display
OUTPUT:
Vik 180
Mehdi 175
Bella 168
Chriss 190
dtype: int64
4.7. MODULES
In Python, Modules are simply files with the “. py” extension containing Python code that can be
imported inside another Python Program. In simple terms, we can consider a module to be the
return (x+y)
return (x-y)
Note: This does not import the functions or classes directly instead imports the module only. To
access the functions inside the module the dot(.) operator is used.
import calc
Output:
12
pydoc
You can use pydoc to search through the Python libraries installed on your system. At
the command prompt type.
$ pydoc -g
• Classes in pink
• Functions in orange
• Data in green
The keyword module contains a single function, iskeyword, which as its name suggests is a
boolean function that returns True if a string passed to it is a keyword:
>>>fromkeywordimport*
>>>iskeyword('for')
True
>>>iskeyword('all')
False
>>>
import json
data = {
"name": "Jonny",
"age": 30,
"is_student": True,
Output
{
"name": "Jonny",
"age": 30,
"is_student": true,
"courses": [
"Web Dev",
"CP"
]
}
II. Tkinter module in Python
"tkinter" is the standard GUI (Graphical User Interface) library in
Python. "tkinter" module is used to create windows, buttons, text boxes, and other UI elements
for desktop applications.
Example
Firstly we imports the "tkinter" module as "tk" and defines a function, "on_button_click",
which updates a label's text. A main GUI window titled "Tkinter Example" is created,
containing a label and a button. The label displays "Click the button below", and the button,
labeled "Click Me", triggers the previously defined function when pressed. The application
remains responsive to user interactions by using the "root.mainloop()" event loop, allowing the
label's message to change upon button clicks.
import tkinter as tk
def on_button_click():
label.config(text="Hello, Geeks!")
root = tk.Tk()
root.title("Tkinter Example")
label.pack(pady=40)
root.mainloop()
import random
num = random.randint(1, 10)
print(f"Random integer between 1 and 10: {num}")
fruits = ["Java", "C", "C++", "Python"]
chosen_fruit = random.choice(fruits)
print(f"Randomly chosen language: {chosen_fruit}")
Output
Random integer between 1 and 10: 9
Randomly chosen language: Python
If a list is used, the first element could be the dog’s breed while the second element
could represent its age. Let’s suppose there are 100 different dogs, then how would you know
which element is supposed to be which? What if you wanted to add other properties to these
dogs? This lacks organization and it’s the exact need for classes.
Here, the class keyword indicates that you are creating a class followed by the name of the class
(Dog in this case).
EXAMPLE
# a class
class Dog:
# A simple class
classDog:
sound ="bark"
# attribute
attr1 = "mammal"
attr2 = "dog"
def fun(self):
# Driver code
# Object instantiation
Rodger = Dog()
print(Rodger.attr1)
Rodger.fun()
• Attributes are defined within a class and can be accessed and modified by both the class
and its objects.
• In Python, class attributes are defined directly within the class definition and are shared
among all instances of the class.
• They can be accessed using the class name and through an instance of the class.
EXAMPLE PROGRAM
class sampleclass:
def increase(self):
sampleclass.count += 1
s1 = sampleclass()
print(s1.count)
# object
s2 = sampleclass()
s2.increase()
print(s2.count)
print(sampleclass.count)
OUTPUT
1
2
2
4.11. INSTANCE
Every object has its own copy of the instance attribute (In case of class attributes all object refer
to single copy).
classes.
defshow(self):
print(self.name)
print(self.salary)
e1 =emp()
print("Dictionary form :", vars(e1))
print(dir(e1))
Output
5 MARK:
10 MARK:
********UNIT IV COMPLETED********
5.1. Introduction
In any application, there is a need for persistent storage. Generally, there are three
basic storage mechanisms: files, a relational database system (RDBMS), or some sort of hybrid,
i.e., an API (application programmer interface) that "sits on top of" one of those existing
systems, an object relational mapper (ORM), file manager, spreadsheet, configuration file, etc.
In an earlier chapter, we discussed persistent storage using both plain file access as
well as a Python and DBM overlay on top of files, i.e., *dbm, dbhash/bsddb files, shelve
(combination of pickle and DBM), and using their dictionary-like object interface. This chapter
will focus on using RDBMSs for the times when files or writing your own system does not
suffice for larger projects.
Underlying Storage
Databases usually have a fundamental persistent storage using the file system, i.e., normal
operating system files, special operating system files, and even raw disk partitions.
User Interface
Most database systems provide a command-line tool with which to issue SQL commands
or queries. There are also some GUI tools that use the command-line clients or the database
client library, giving users a much nicer interface.
Databases
An RDBMS can usually manage multiple databases, e.g., sales, marketing, customer
support, etc., all on the same server (if the RDBMS is server-based; simpler systems are usually
not). In the examples we will look at in this chapter, MySQL is an example of a server-based
Components
The table is the storage abstraction for databases. Each row of data will have fields that
correspond to database columns. The set of table definitions of columns and data types per table
all put together define the database schema.
Databases are created and dropped. The same is true for tables. Adding new rows to a database is
called inserting, changing existing rows in a table is called updating, and removing existing rows
in a table is called deleting. These actions are usually referred to as database commands or
operations.
Requesting rows from a database with optional criteria is called querying. each resulting row.
Some databases use the concept of a cursor for issuing SQL commands, queries, and grabbing
results, either all at once or one row at a time.
SQL
Database commands and queries are given to a database by SQL. Not all databases use
SQL, but the majority of relational databases do. Here are some examples of SQL commands.
Most databases are configured to be caseinsensitive, especially database commands. The
accepted style is to use CAPS for database keywords. Most command-line programs require a
trailing semicolon ( ; ) to terminate a SQL statement.
1.Creating a Database
The first line creates a database named "test," and assuming that you are a database
administrator, the second line can be used to grant permissions to specific users (or all of them)
so that they can perform the database operations below.
2.Using a Database
USE test;
If you logged into a database system without choosing which database you want to use, this
simple statement allows you to specify one with which to perform database operations.
This simple statement removes all the tables and data from the database and deletes it from the
system.
4.Creating a Table
This statement creates a new table with a string column login and a pair of integer fields uid and
prid.
5.Dropping a Table
DROP TABLE users;
This simple statement drops a database table along with all its data.
6.Inserting a Row
INSERT INTO users VALUES('leanna', 311, 1);
You can insert a new row in a database with the INSERT statement. Specify the table and the
values that go into each field. For our example, the string 'leanna' goes into the login field, and
311 and 1 to uidandprid, respectively.
7.Updating a Row
UPDATE users SET prid=4 WHERE prid=2;
To change existing table rows, you use the UPDATE statement. Use SET for the columns that
are changing and provide any criteria for determining which rows should change. In the first
example, all users with a "project ID" or prid of 2 will be moved to project #4. In the second
example, we take one user (with a UID of 311) and move them to project #1.
8.Deleting a Row
DELETE FROM users WHERE prid=%d;
Now that you are up to speed on basic database concepts, it should make following the rest of the
chapter and its examples much easier. If you need additional help, there are plenty of database
books out in the market that you can check out.
Topics such as database principles, concurrency, schema, atomicity, integrity, recovery, proper
complex left JOINs, triggers, query optimization, transactions, stored procedures, etc., are all
outside the scope of this text, and we will not be discussing these in this chapter other than direct
use from a Python application. There are plenty of resources you can refer to for general
information. Rather, we will present how to store and retrieve data to/from RDBMSs while
playing within a Python framework. You can then decide which is best for your current project
or application and be able to study sample code that can get you started instantly. The goal is to
get you up to speed as quickly as possible if you need to integrate your Python application with
some sort of database system.
We are also breaking out of our mode of covering only the "batteries included" features of the
Python standard library. While our original goal was to play only in that arena, it has become
clear that being able to work with databases is really a core component of everyday application
development
Use MySQL as the example here, along with the only MySQL Python adapter:
MySQLdb, aka MySQL-python. In the various bits of code, we will also show you (deliberately)
examples of error situations so that you have an idea of what to expect, and what you may wish
to create handlers for.
First log in as an administrator to create a database and grant permissions, then log back in as a
normal client.
>>>cxn.commit()
>>>cxn.close()
In the code above, we did not use a cursor. Some adapters have Connection objects, which can
execute SQL queries with the query() method, but not all. We recommend you either not use it or
check your adapter to make sure it is available.
The commit() was optional for us as auto-commit is turned on by default in MySQL. We then
connect back to the new database as a regular user, create a table, and perform the usual queries
and commands using SQL to get our job done via Python. This time we use cursors and their
execute()method.
The next set of interactions shows us creating a table. An attempt to create it again (without first
dropping it) results in an error.
>>>cxn = MySQLdb.connect(db='test')
3L
1L
0L
>>>cur.close()
>>>cxn.commit()
>>>cxn.close()
MySQL is one of the most popular open source databases in the world, and it is no surprise that a
Python adapter is available for it. Keep in mind that no database modules are available in the
Python standard libraryall adapters are third-party packages that have to be downloaded and
installed separately from Python. Please see the References section toward the end of the chapter
to find out how to download it.
PostgreSQL
Another popular open source database is PostgreSQL. Unlike MySQL, there are no less
than three current Python adapters available for Postgres: psycopg, PyPgSQL, and PyGreSQL. A
fourth, PoPy, is now defunct, having contributed its project to combine with that of PyGreSQL
back in 2003. Each of the three remaining adapters has its own characteristics, strengths, and
weaknesses, so it would be a good idea to practice due diligence to determine which is right for
you.
The good news is that the interfaces are similar enough that you can create an application that,
say, measures the performance between all three (if that is a metricthat is important to you). Here
we show you the setup code to get a Connection object for each: psycopg
SQLite
For extremely simple applications, using files for persistent storage usually
suffices, but the most complex and data-driven applications demand a full relational
database. SQLite targets the intermediate systems and indeed is a hybrid of the two. It is
extremely lightweight and fast, plus it is serverless and requires little or no administration.
SQLite has seen a rapid growth in popularity, and it is available on many
This script performs some basic operations using a variety of databases (MySQL, SQLite,
Gadfly) and a corresponding Python database adapter.
#!/usr/bin/env python
import os
DB_EXC = None
def setup():
return RDBMSs[raw_input('''
(M)ySQL
(G)adfly
(S)QLite
global DB_EXC
try:
import sqlite3
except ImportError, e:
try:
except ImportError, e:
return None
DB_EXC = sqlite3
if not os.path.isdir(dbDir):
os.mkdir(dbDir)
elifdb == 'mysql':
try:
import MySQLdb
except ImportError, e:
return None
try:
cxn = MySQLdb.connect(db=dbName)
except _mysql_exceptions.OperationalError, e:
cxn = MySQLdb.connect(user='root')
try:
except DB_EXC.OperationalError, e:
pass
cxn.commit()
cxn.close()
cxn = MySQLdb.connect(db=dbName)
elifdb == 'gadfly':
try:
DB_EXC = gadfly
return None
try:
except IOError, e:
cxn = gadfly()
if not os.path.isdir(dbDir):
os.mkdir(dbDir)
cxn.startup(dbName, dbDir)
else:
return None
return cxn
def create(cur):
try
cur.execute('''
login
MySQL supports various types of pattern matching operations to retrieve filtered result-sets from
huge database tables. In previous chapters, we have already learned about the LIKE operator for
pattern matching. In this chapter, we will see another pattern matching operation based on
regular expressions.
Syntax
Following is the table of pattern, which can be used along with the REGEXP operator
^ Beginning of string
$ End of string
[:class:] A character class, i.e. use [:alpha:] to match letters from the alphabet
Examples
The following example demonstrates the usage of some patterns mentioned in the table above,
along with the REGEXP operator. For that, we are first creating a database table to perform the
search on.
Assume we are creating a table called CUSTOMERS using the following query −
Execute the following query to display all the records present in above created table −
Now, we are finding all the records in the CUSTOMERS table whose name starts with 'k' −
The following query retrieves all records in CUSTOMERS table whose name ends with 'sh' −
Here, we are retrieving all the records whose name contain 'sh' −
As we can see the output, there are only two names that contain 'sh'.
It returned an empty set because the CUSTOMERS table do not have any names who starts with
vowel and ends with 'ol'
The following query finds all the names in the CUSTOMERS table whose name starts with a
consonant −
1 NOT REGEXP
Negation of REGEXP
2 REGEXP
Checks whether the string matches regular expression or not
3 REGEXP_INSTR()
Returns the starting index of substring matching regular expression
4 REGEXP_LIKE()
Returns whether the string matches the regular expression
5 REGEXP_REPLACE()
Replaces substrings matching the regular expression
6 REGEXP_SUBSTR()
Returns substrings matching the regular expression
7 RLIKE
Checks whether the string matches regular expression or not
In Python, special symbols and characters are often used for various purposes, such as string
manipulation, regular expressions, and syntax structure. Here is a list of some common special
symbols and characters in Python:
1. Escape Characters
Escape characters are used to insert special characters into strings, or to represent characters that
are difficult or impossible to type directly.
2. String Delimiters
3. Arithmetic Operators
• +: Addition
• -: Subtraction
• *: Multiplication
• /: Division (floating-point)
• //: Integer division
• %: Modulus (remainder of division)
• **: Exponentiation (power)
4. Comparison Operators
• ==: Equal to
• !=: Not equal to
• >: Greater than
• <: Less than
• >=: Greater than or equal to
• <=: Less than or equal to
5. Logical Operators
6. Assignment Operators
• =: Assign value
• +=: Add and assign
• -=: Subtract and assign
• *=: Multiply and assign
• /=: Divide and assign
• //=: Integer divide and assign
• %=: Modulus and assign
• **=: Exponentiate and assign
• is: Tests object identity (whether two references point to the same object)
• is not: Tests if two references do not point to the same object
8. Membership Operators
9. Bitwise Operators
11. Comments
Regular expressions (REs) are powerful tools used for pattern matching and text
manipulation. In Python, regular expressions are handled by the re module, which provides a
wide range of functionality to search, match, replace, and manipulate strings based on specific
patterns.
1. Pattern Matching: Regular expressions use special characters to define patterns that can
be matched against strings. These patterns allow you to check whether a string contains a
certain sequence of characters, extract parts of a string, or even replace specific portions
of a string.
2. Metacharacters: These are special characters that are interpreted differently from
ordinary characters. They form the foundation of regular expressions.
Here are the most common functions provided by the re module in Python for working with
regular expressions:
1. re.match(pattern, string):
o Tries to match the pattern from the start of the string.
o Returns a match object if successful, otherwise returns None.
o Example: re.match(r"^abc", "abcdef") matches because "abc" is at the beginning
of the string.
2. re.search(pattern, string):
7. re.compile(pattern):
o Compiles the pattern into a regular expression object, which can be used multiple
times for matching.
o Example: regex = re.compile(r"\d+") then regex.findall("abc123xyz456") returns
['123', '456'].
Example Code
python
Copy code
import re
5 MARK:
10 MARK:
***************UNIT 5 COMPLETED****************
4+3%5
a) 7 b) 2 c) 4 d) 1
10. Which of the following character is used to give single-line comments in Python?
a) //b) #c) !d) /*
i=1
whileTrue:
if i%3==0:
break
print(i)
i + =1
a)1 2 3
b) error
c) 1 2
d) none of the mentioned
12. Which of the following functions can help us to find the version of python that we are
currently working on?
a) sys.version(1)
b) sys.version(0)
c) sys.version()
d) sys.version
15. What will be the output of the following Python code snippet if x=1?
x<<2
a) 4
b) 2
c) 1
d) 8
2**(3**2)
(2**3)**2
2**3**2
list(filter(bool, l))
def f(x):
print("Sanfoundry")
returnx(*args, **kwargs)
return f1
min(max(False,-3,-4), 2,7)
a) -4
b) -3
c) 2
d) False
25. Which of the following is not a core data type in Python programming?
a) Tuples
b) Lists
c) Class
d) Dictionary
26. What will be the output of the following Python expression if x=56.236?
print("%.2f"%x)
a) 56.236
b) 56.23
c) 56.0000
d) 56.24
27. Which of these is the definition for packages in Python?
a) A set of main modules
b) A folder of python modules
c) A number of files containing Python definitions and statements
d) A set of programs making use of Python modules
28. What will be the output of the following Python function?
len(["hello",2, 4, 6])
a) Error
b) 6
c) 4
d) 3
29. What will be the output of the following Python code?
x = 'abcd'
foriin x:
PYTHON NOTES Page 157
print(i.upper())
30. What is the order of namespaces in which Python looks for an identifier?
a) Python first searches the built-in namespace, then the global namespace and finally the local
namespace
b) Python first searches the built-in namespace, then the local namespace and finally the global
namespace
c) Python first searches the local namespace, then the global namespace and finally the
built-in namespace
d) Python first searches the global namespace, then the local namespace and finally the built-in
namespace
31. What will be the output of the following Python code snippet?
a) 4 3 2 1
b) error
c) 1 2 3 4
d) none of the mentioned
32. What will be the output of the following Python statement?
>>>"a"+"bc"
a) bc
b) abc
c) a
d) bca
33. Which function is called when the following Python program is executed?
f = foo()
format(f)
a) str()
b) format()
c) __str__()
class tester:
self.id = str(id)
id="224"
>>>temp = tester(12)
>>>print(temp.id)
a) 12
b) 224
c) None
d) Error
def foo(x):
x[0] = ['def']
x[1] = ['abc']
return id(x)
q = ['abc', 'def']
print(id(q) == foo(q))
z=set('abc')
z.add('san')
z.update(set(['p', 'q']))
print("abc. DEF".capitalize())
a) Abc. def
b) abc. def
c) Abc. Def
41. Which of the following statements is used to create an empty set in Python?
a) ( )
b) [ ]
c) { }
d) set()
list1 = [1,2,3,4]
list2 = [2,4,5,6]
list3 = [2,6,7,8]
result = list()
a) [1, 3, 5, 7, 8]
b) [1, 7, 8]
c) [1, 2, 4, 7, 8]
d) error
a) * abcde *
b) *abcde *
>>>list1 = [1, 3]
>>>list2 = list1
>>>list1[0] = 4
>>>print(list2)
a) [1, 4]
b) [1, 3, 4]
c) [4, 3]
d) [1, 3]
47. Which of the following Python statements will result in the output: 6?
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
a) A[2][1]
b) A[1][2]
c) A[3][2]
d) A[2][3]
48. What is the maximum possible length of an identifier in Python?
a) 79 characters
b) 31 characters
c) 63 characters
i=0
whilei< 5:
print(i)
i += 1
ifi == 3:
break
else:
print(0)
a) error
b) 0 1 2 0
c) 0 1 2
d) none of the mentioned
x = 'abcd'
foriin range(len(x)):
print(i)
a) error
b) 1 2 3 4
c) a b c d
d) 0 1 2 3
51. What are the two main types of functions in Python?
a) System function
b) Custom function
c) Built-in function & User defined function
d) User function
def addItem(listParam):
listParam += [1]
mylist = [1, 2, 3, 4]
addItem(mylist)
print(len(mylist))
a) 5
b) 8
c) 2
d) 1
53. Which of the following is a Python tuple?
a) {1, 2, 3}
b) {}
c) [1, 2, 3]
d) (1, 2, 3)
54. What will be the output of the following Python code snippet?
z=set('abc$de')
'a' in z
a) Error
b) True
c) False
d) No output
round(4.576)
a) 4
b) 4.6
c) 5
d) 4.5
x = [[0], [1]]
a) 01
b) [0] [1]
c) (’01’)
d) (‘[0] [1]’,)
deffoo():
try:
return 1
finally:
return 2
k = foo()
print(k)
a) error, there is more than one return statement in a single try-finally block
b) 3
c) 2
d) 1