Python

Python Programming – Class Object

In this Page, We are Providing Python Programming – Class Object. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Class Object

Class object

When a class definition is created, a “class object” is also created. The class object is basically a wrapper around the contents of the namespace created by the class definition. Class object support two kinds of operations: “attribute reference” and “instantiation”.

Attribute reference

Attribute references use the standard syntax used for all attribute references in Python: obj .name. Valid attribute names are all the names that were in the class’s namespace, when the class object was created. So, if the class definition looked like this:

>>> class MyClass: 
. . .            " " "A simple example class " " " 
. . .           i=12345
. . .           def f ( self ) : 
. . .                 return ' hello world ' :
. . . 
>>> MyClass . i 
12345
>>> MyClass.___doc___
' A simple example class '

then MyClass . i and MyClass . f are valid attribute references, returning an integer and a method object, respectively. The value of MyClass.i can also be change by assignment. The attribute ___doc___is also a valid attribute, returning the docstring belonging to the class.

>>> type ( MyClass )
<type ' classobj ' >

From the above expression, it can be noticed that MyClass is a class object.

Instantiation

A class object can be called to yield a class instance. Class instantiation uses function notation. For example (assuming the above class MyClass):

x=MyCiass ( )

creates a new instance of the class MyClass, and assigns this object to the local variable x.

>>> type ( MyClass( ) )
<bype ' instance' > 
>>> type (x) 
<type 'instance'>

Many classes like to create objects with instances customized to a specific initial state. Therefore, a class may define a special method named ___init___( ), like this:

def __init__ ( self ) :
self.data=[ ]

When a class defines an __init__ ( ) method, class instantiation automatically invokes __init__( ) for the newly created class instance. So in this example, a new, initialized instance can be obtained by:

x=MyClass ( )

Of course, the ___init___ ( ) method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to ___init___ ( ). For example,

>>> class Complex:
. . .          def __init___ ( self , realpart , imagpart ) :
. . .              self . r=realpart
. . .              self . i=imagpart
>>> x=Complex ( 3 . 0, -4 . 5 )
>>> x . r , x . i
( 3 . 0 , -4 . 5 )

Python Programming – Method

In this Page, We are Providing Python Programming – Method. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Method

Method

A method is a function that belongs to an object. In Python, the term “method” is not unique to class instance, other object types can have methods as well. For example, list objects have methods, namely, append, insert, remove, sort, and so on.

Usually in a class, the method is defined inside its body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). Self is merely a conventional name for the first argument of a method. For example, a method defined as meth (self, a, b, c) should be called as x.meth (a, b, c) for an instance x of the class in which the definition occurs; the called method will think it is called as meth (x, a, b, c). The idea of self was borrowed from “Modula-3” programming language.

It is not necessary that the function definition is textually enclosed in the class definition; assigning a function object to a local variable in the class is also fine. For example:

>>> def f 1 ( self , x , y ) :
. . .            return min ( x , x+y )
. . . 
>>> class test_class :
. . .        aa=f1
. . .        def bb ( self ) : 
. . .              return ' hello world '
. . .       cc=bb
. . . 
>>>

Here aa, bb and cc are all attributes of class test_class that refer to function objects, and consequently, they are all methods of instances of class test_class; cc being exactly equivalent to bb. Note that this practice usually confuses the reader of the program.

Usually, Python use methods for some functionality (e.g. list. index ()), but functions for other (e.g. len (list)). The major reason is history; functions were used for those operations that were generic for a group of types and which were intended to work even for objects that did not have methods at all (e.g. tuples). In fact, implementing len ( ), max ( ), min ( ) etc.

as built-in functions has actually less code than implementing them as methods for each type. One can quibble about individual cases, but it is part of Python, and it is too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage.

Python Programming – Class

In this Page, We are Providing Python Programming – Class. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Class

Class

A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embodies the attributes: the “data attributes” and “methods”, specific to a data type. A class definition is given below:

classdef        : := " class " classname [ inheritance ] " : " suite
inheritance   : := " ( " [ expression_list ] " ) " 
classname    : := identifier

The above class definition might seem alien, it will become more clear with the progress of this Chapter. The simplest form of class definition looks like:

class ClassName: 
        <statement-1>
         .
 
        .

       .
      <statement-N>

The following example gives a glimpse of how a class is defined.

>>> class Output :
. . .      def Display ( self ) :
. . .            print ' This is a class example . '
. . . 
>>> x=Output ( ) 
>>> x . Display ( )
This is a class example.

Like function definition (def statements), the class definition (Output in the above example) must be executed before they have any effect. In practice, the statements inside a class definition will usually be function (or more specifically “method”) definitions (Display ( ) in the above example), but other statements are allowed. The function definitions inside a class normally have a peculiar form of the argument list, dictated by the calling conventions for methods (discussed later).

The creation of a class definition also creates a new namespace, and used as the local scope, thus all assignments to local variables go into this new namespace.

Python Programming – Constants

In this Page, We are Providing Python Programming – Constants. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Constants

Constants

math.pi
The mathematical constant π.

math. e
The mathematical constant e.

>>> math.e
2.718281828459045

Number-theoretic and representation functions

math . ceil ( x )
Return the ceiling of x as a float, the smallest integer value greater than or equal to x.

>>> import math 
>>> math . ceil ( -3 . 2 )
-3 . 0
>>> math . ceil ( 3 . 2 )
4 . 0

math . copysign ( x , y )
Return x with the sign of y.

>>> math . copysign ( 5 . 1 , -2 . 8 )
-5 . 1
>>> math . copysign ( -5 . 1 , 2 . 8 )
5 . 1

math . tabs ( x )
Return the absolute value of x.

>>> math . fabs ( - 4 . 2 )
4 . 2

math . factorial ( x )
Return x factorial. Raises ValueError, if x is not integral or is negative.

>>> math . factorial ( 5 ) 
120 
>>> math . factorial ( -5 ) 
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
ValueError: factorial ( ) not defined for negative values

math . floor ( x )
Return the largest integer value less than or equal to x as a float.

>>> math . floor ( -3 . 2 )
-4 . 0
>>> math . floor ( 3 . 2 )
3 . 0

math . fmod ( x , y )
Return remainder of a division expression. Note that the Python expression x%y may not return the same result. The result of fmod (x, y) has same sign as x, while x%y returns a result with the sign of y instead.

>>> math . fmod ( 5 . 0 , -2 . 0 )
1 . 0
>>> 5 . 0% -2 . 0 
-1 . 0
>>> math . fmod ( -5 . 0 , 2 . 0 )
-1 . 0
>>> -5 . 0 % 2 . 0
1 . 0

Consider the following interesting scenario.

>>> math . fmod ( -1e-100 , 1e100)
-1e-100 
>>> -1e-100 % 1e100
1e +100

It can be observed that fmod (-1e-100 , 1e100) returns -1e-100, but the result of Python’s – 1e-100%1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod ( ) is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

math . frexp ( x )
Return the mantissa and exponent of x as the pair (m, e). The m is a float and e is an integer such that x = m x 2e exactly. If x is zero, returns ( 0 . 0 , 0 ) , otherwise 0 . 5<=abs ( m ) <1.

>>> math . frexp ( 4 . 0 )
( 0 . 5 , 3 )
>>> 0 . 5*2**3
4 . 0
>>> math . frexp ( 0 . 1 )
( 0 . 8 , -3 )
>>> 0 . 8* 2**-3
0 . 1
>>> math . frexp ( -4 . 0 )
( -0 . 5 , 3 )
>>> -0 . 5*2**3
- 4 . 0

math.fsum(iterable)
Return an accurate floating point sum of values in the iterable.

>>> math . fsum ( [ . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 ] )
1 . 0

math . isinf ( x )
Check if the float x is positive or negative infinity.

>>> a=1e+300
>>> a
1e+300
>>> math . isinf ( 1e+300 )
False
>>> a=1e+310
>>> a
inf
>>> math . isinf ( 1e+310 )
True

Calculating an exponent with floating point values, in particular, raises Overf lowError instead of preserving the inf result.

>>> a=10 . 0**310

Traceback ( most recent call last ) :
File "<pyshell#l>", line 1, in <module>
    a=10 . 0**310
OverflowError: (34 , ' Result too large ' )

math . isnan ( x )
Check if the float x is a nan (not a number), nan does not compare as equal to any value, even itself, so nan should be checked using isnan () function.

>>> a=1e+310
>>> a
inf
>>> b=a/a
>>> b
nan
>>> math . isnan ( a )
False
>>> math . isnan ( b )
True

math . ldexp ( x , i )
Return x* (2**i). This function is reverse of function frexp ( ).

>>> math . 1dexp ( -0 . 5 , 3 )
-4 . 0
>>> -0 . 5*2**3
-4 . 0
>>> math . ldexp ( 0 . 8 , -3 )
0 . 1
>>> 0 . 8*2**-3
0 . 1

math . modf ( x )
Return the fractional and integer parts of x. Both results carry the sign of x and are floats.

>>> math . modf ( 1 . 5 )
( 0 . 5 , 1 . 0 )

>>> math . modf ( -1 . 5 )
( -0 . 5 , -1 . 0 )

math . trunc ( x )
Return the real value x truncated to an integer.

>>> math . trunc ( 93 . 2508 )
93
>>> math . trunc ( -93 . 2508 )
-93

Power and logarithmic functions

math . exp ( x )
Return ex.

>>> math . e**-3 . 2
0 . 04076220397836622
>>> math . pow ( math . e , -3 . 2 )
0 . 04076220397836622
>>> math . exp ( -3 . 2 )
0 . 04076220397836621

math . expm1 ( x )
Return ex-1. For small floats x, the subtraction in exp(x)-1 can result in a significant loss of precision; the expml ( ) function provides a way to compute this quantity to full precision:

>>> x=0 . 0000000000000000000000001
>>> math . exp ( x ) , -1
0 . 0
>>> math . expm1 ( x )
1e - 25

math . log ( x [ , base ] )
With one argument, return the natural logarithm of x (to base e). With two arguments, return the logarithm of x to the given base, calculated as log (x) / log (base).

>>> math . log ( 9 )
2 . 1972245773362196
>>> math . log ( 9 , 2 )
3 . 1699250014423126

math . loglp ( x )
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

>>>x=0.0000000000000000000000001
>>> X
1e-25
>>> 1+x
1 . 0
>>> math . 1og ( 1 +x )
0 . 0
>>> math . 1og1p ( x )
1e-25

math . 1og10 ( x )
Return the base-10 logarithm of x. This is usually more accurate than log (x, 10).

>>> math . 1og10 ( 100 )
2 . 0
>>> math . 1og10 ( 10000 )
4 . 0

math . pow ( x , y )
Return x raised to the power y. In particular, pow ( 1 . 0 , x ) and pow ( x , 0 . 0 ) always return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow (x, y) is undefined, and raises ValueError.

>>> math.pow ( 9 . 0 , 0 . 5 )
3 . 0
>>> math . pow ( -9 . 0 , 0 . 5 )
Traceback ( most recent call last ) :
File "<stdin>" , line 1 , in <module>
ValueError: math domain error

Unlike the built-in * * operator, math. pow ( ) converts both its arguments to type float.

math . sqrt( x )
Return the square root of x. Computing the square roots of negative numbers requires complex numbers, which are not handled by math module. Any attempt to calculate a square root of a negative value results in ValueError.

>>> math . sqrt ( 9 . 0 )
3 . 0
>>> math . sqrt ( -9 , 0 )

Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
math . sqrt ( -9 . 0 )
ValueError: math domain error

Trigonometric functions

math . acos ( x )
Return the arc cosine of x, in radians.

>>> math . acos ( 0 . 5 )
1 . 0471975511965979

math . asin ( x )
Return the arc sine of x, in radians.

>>> math . asin ( 0 . 5 )
0 . 5235987755982989

math . atan ( x )
Return the arc tangent of x, in radians.

>>> math . atan ( 0 . 5 )
0 . 4636476090008061

math . atan2 ( y , x )
Return atan(y/x), in radians. The resuit is between -TI and TI. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2 () is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan (1) and atan2 (1,1) are both n /4, but atan2 (-1,-1) is -3#/4.

>>> math . atan ( 1 . 0 )
0 . 7853981633974483
>>> math . pi / 4
0 . 7853981633974483

math . cos ( x )
Return the cosine of x radians.

>>> math . cos ( 0 . 7853981633974483 )
0 . 7071067811865476

math . hypot ( x , y )
Return the Euclidean distance, \(\sqrt{x^{2}+y^{2}}\) . This is the length of the vector from the origin to point (x,y).

>>> math . hypot ( 3 . 0 , 4 . 0 )
5 . 0

math . sin ( x )
Return the sine of x radians.

>>> math . sin ( 0 . 7853981633974483 )
0 . 7071067811865475

math . tan ( x )
Return the tangent of x radians.

>>> math.tan ( 0 . 7853981633974483 )
0.9999999999999999

Angular conversion

math . degrees ( x )
Converts angle x from radians to degrees.

>>> math . degrees ( 1 . 5707963267948966 )
90 . 0
>>> 1 . 5707963267948966*180 / math . pi
90 . 0

math . radians ( x )
Converts angle x from degrees to radians.

>>> math . radians ( 90 )
1 . 5707963267948966
>>> ( 90*math . pi ) / 180
1 . 5707963267948966

Hyperbolic functions

math . acosh ( x )
Return the inverse hyperbolic cosine of x.

>>> math . cosh ( 1 . 0 )
1 . 5430806348152437

math . asinh ( x )
Return the inverse hyperbolic sine of x.

>>> math . asinh ( 1 . 0 )
0 . 8813735870195429

math . atanh ( x )
Return the inverse hyperbolic tangent of x.

>>> math . atanh ( 0 . 8 )
1 . 0986122886681098

math . cosh ( x )
Return the hyperbolic cosine of x.

>>> math . cosh ( 0 . 7853981633974483 )
1 . 3246090892520057

math . sinh ( x )
Return the hyperbolic sine of x.

>>> math . sinh ( 0 . 7853981633974483)
0 . 8686709614860095

math . tanh ( x )
Return the hyperbolic tangent of x.

>>> math . tanh ( 0 . 7853981633974483 )
0 . 6557942026326724

Special functions

math . erf ( x )
Return the error function at x.

>>> math . erf ( 0 . 25 )
0 . 2763263901682369

math . erfc ( x )
Return the complementary error function at x i.e. 1-erf (x).

>>> math . erf c ( 0 . 25 )
0 . 7236736098317631

math . gamma ( x )
Return the gamma function at x.

>>> math . gamma ( 5 . 5 )
52 . 34277778455352

math . lgamma ( x )
Return the natural logarithm of the absolute value of the gamma function at x.

>>> math . 1 gamma ( 5 . 5 )
3 . 9578139676187165

5 Different ways to read a file line by line in Python

Python gives us functions for writing ,creating and reading files.Ok llike we have some file in our directory so in python we can read that file and also make some modification on it. Normal text files and binary files there are two types of files that can be handled in python.There are different ways to read a file line by line in Python.

We have one  file intro1.txt in our directory and we want to read it line by line.Lets see how will we do that.

Using readlines()

readlines() we can use for small file. It reads all files details from memory, then  separate into lines and returns all in a list.  All the List returned by readlines or readline will store the newline character at the end.

Lets take an example,

fileHandler = open ('c:\\new folder\intro1.txt', "r")
# Get list of all lines in file
listOfLines = fileHandler.readlines()
for line in listOfLines:
    print(line.strip()) 
fileHandler.close()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse.

So in above example we have seen that listOfLines = fileHandler.readlines() this will return a list of lines in file. We can iterate over that list and strip() the new line character then print the line .

Above case is only use for small file for large file we have to look up some other methods because it use lots of memory.

Using readline()

For working with large file we have readline().It will read file line by line instead of storing all at one time.Also, if the end of the file is reached, it will return an empty string.

fileHandler = open ("c:\\new folder\intro1.txt", "r")
while True:
    
    line = fileHandler.readline()
    # If line is empty then end of file reached
    if not line :
        break;
    print(line.strip())
   
fileHandler.close()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. 
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
 Python supports modules and packages, which encourages program modularity and code reuse.

Using context manager (with block)

If we open any file it is very important to close that file,if we did not close then it will automatically close but sometime when there is  large function which not going to end soon.In that case we take help of context manager to cleanup and closeup.

fileHandler = open("c:\\new folder\intro1.txt", "r")
line = fileHandler.readline()
for line in fileHandler:
    print("Line{}: {}".format(count, line.strip()))
   
fileHandler.close()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py 
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse.

After termination of loop file will automatically close,even if there is any exception it will also terminates.

 Using context manager (with block)get List of lines in file

listOfLines = list()        
with open("c:\\new folder\intro1.txt", "r") as file:
    for line in file:
        listOfLines.append(line.strip()) 
    print(listOfLines)

Output:

['Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.', 
"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.", 
'Python supports modules and packages, which encourages program modularity and code reuse.']

So in above example we have iterate all the lines in file and create a list.

Using context manager and while loop read contents of file line by line

So in this method we are going to use while loop and context manager for reading of any file.So in while loop we can give any condition according to this it iterate over lines in file.

with open("c:\\new folder\intro1.txt", "r") as fileHandler:  
    # Read next line
    line = fileHandler.readline()
    # check line is not empty
    while line:
        print(line.strip())
        line = fileHandler.readline()

Output:

RESTART: C:/Users/HP/Desktop/filehandling.py
 Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. 
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. 
Python supports modules and packages, which encourages program modularity and code reuse.

Conclusion:

So in this article we have shown you different methods to read any file.Hope you enjoyed the session.

Python : How to Sort a Dictionary by Key or Value ?

Dictionaries are the implementation by Python of a data structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.

The list of key value pairs in curly braces that is separated by comma defines a dictionary. Column ‘:’ separates the value of each key.

A dictionary cannot be sorted only to get a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you need an ordered data type, which is a list—probably a list of tuples.

In this post, we will look at how to sort a dictionary by key or value

Examples:

By keys

Input:

dictionary = {'this': 200, 'is':100, 'BTechGeeks':300}

Output:

BTechGeeks : 300
is : 100
this :200

Input:

dictionary = {'this': 100, 'is':200, 'BTechGeeks':300}

Output:

is : 100
this : 200
BTechGeeks : 300

Sort a Dictionary by Key/Value

There are several ways to sort a dictionary by key or value some of them are:

Sort Dictionary by keys:

Method #1: Using items() function

A view object is returned by the items() method. The object view contains the dictionary’s key-value pairs as tuples in a list.

The object displays any modifications made in the dictionary.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list
for i in sorted(dictitems):
    # print key and value
    print(i[0], ":", i[1])

Output:

BTechGeeks : 300
is : 100
this :200

Method #2:Using dict.keys() method

  • Convert the keys of the dictionary to list .
  • Sort the list .
  • Print the corresponding keys and values as you traverse the list.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using dict.keys
dictlist = list(dictionary.keys())
# sort the list
dictlist.sort()
# Print the corresponding key and value by traversing this list
for key in dictlist:
    # print key and value
    print(key, ":", dictionary[key])

Output:

BTechGeeks : 300
is : 100
this :200

Method #3: Sorting the dictionary keys in reverse order

Both of the previous solutions sorted the dictionary ascending order by key. What if we were to sort the contents by the keys in decreasing order? This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in descending order
for i in sorted(dictitems, reverse=True):
    # print key and value
    print(i[0], ":", i[1])

Output:

this : 200
is : 100
BTechGeeks : 300

Sort Dictionary by Values:

Using sorted() and items() functions to sort dictionary by value

We’ll use the same sorted() function and transfer a key function that returns the first index element of the tuple, i.e. the value field from the key/value pair, to sort dictionary elements by value.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1]):
    # print key and value
    print(i[0], ":", i[1])

Output:

is : 100
this : 200
BTechGeeks : 300

Using sorted() + items() +reverse() functions to sort dictionary by value in reverse order

This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1], reverse=True):
    # print key and value
    print(i[0], ":", i[1])

Output:

BTechGeeks : 300
this : 200
is : 100

Related Programs:

Python: Check if String is Empty or Contain Spaces only

Python strings are byte arrays representing characters of Unicode.. However, because Python lacks a character data type, a single character is simply a one-length string. Square brackets can be used to access string elements.

Given a string, the task is to check whether the string is empty or not.

Example:

Input:

string=""

Output:

Given String is empty

Check if String is Empty

There are several ways to check whether the string is empty some of them are:

Method #1:Using len() function

The most general method for checking for zero-length strings is to use len(). Despite the fact that it ignores the fact that a string with only spaces should be considered an empty string even if it is not zero.

In Python, the len() function takes a sequence as an argument and returns the number of elements in that sequence. So, if we pass a string to the len() function as an argument, it returns the total number of characters in that string.

So, we can use the len() function to determine whether a string is empty or not by determining whether the number of characters in the string is zero or not.

Below is the implementation:

# given string
string = ""
# determining whether or not the given string is empty using len()
if len(string) == 0:
    print("Givem String is empty")
else:
    print("Given String is not empty")

Output:

Given String is empty

Method #2:Using not

The not operator can do the same thing as len() and search for 0 length strings, but it also considers strings with only spaces to be non-empty, which isn’t realistic.

In Python, an empty string is equivalent to False. So, to see if a string is empty or not, we can use the “not” operator, .

Below is the implementation:

# given string
string = ""
#  determining whether or not the given string is empty
if not string:
    print("Given String is empty")
else:
    print("Given String is not empty")

Output:

Given String is empty

Check whether string is empty/contain spaces

Using strip()

To get a copy of a string without leading and trailing white spaces, we can use the string’s strip() function. So, let’s use this to see if the string is empty or only contains white spaces.

Below is the implementation:

# given string
string = " "
#  determining whether or not the given string is empty
if string and string.strip():
print("Given String is not empty")
else:
print("Given String is empty")

Output:

Given String is empty

Using isspace()

The string class’s isspace() function returns True if the string only contains white spaces. So we can use this to see if a string is empty or only contains white spaces.

To get a copy of a string without leading and trailing white spaces, we can use the string’s strip() function. So, let’s use this to see if the string is empty or only contains white spaces.

Below is the implementation:

# given string
string = "      "
#  determining whether or not the given string is empty
if string and not string.isspace():
    print("Given String is not empty")
else:
    print("Given String is  empty")

Output:

Given String is empty

Related Programs:

Python Programming – Looping Techniques

In this Page, We are Providing Python Programming – Looping Techniques. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Looping Techniques

Looping techniques

The list can also be used in iteration operation, for example:

>>> for a in [ 4 , 6 , 9 , 2 ] : print a
4
6
9
2
>>> for a in [ 4 , 6 , 9 , 2 ] : print a ,
. . .
4 6 9 2

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate ( ) function.

>>> for i ,v in enumerate ( [ ' tic ' , ' tac ' , ' toe ' ] ) :
. . . print i, v
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip () function.

>>> questions= [ ' namer , ' quest ' , ' favorite color ' ]
>>> answers= [ ' lancelot ' , ' the holy grailblue ' ] 
>>> for q,a in zip ( questions , answers ) :
. . .   print 'What is your { 0 } ? It is { 1 }.'. format ( q , a) 
What is your name ? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.

While iterating a mutable sequence, if there is a need to change the sequence (for example to duplicate certain items), it is recommended to make a copy of the sequence before starting iteration. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient.

>>> words= [ ' cat ' , ' window ' , ' defenestrate ' ]
>>> for w in words [ : ] :
. . . if len ( w )>6:
. . . words. insert ( 0 , w )
>>> words
[ ' defenestrate ' , ' cat ' , ' window ' , ' defenestrate ' ]

Nested list

It is possible to nest lists (create list containing other lists), for example:

>>> q= [ 2 , 3 ]
>>> p= [ 1 , q , 4 ]
>>> len ( p )
3
>>> p [ 1 ]
[ 2 , 3 ]
>>> p [ 1 ] [ 0 ]
2
>>> p [ 1 ] . append ( ' xtra ' )
>>> p
[ 1 , [ 2 , 3 , ' xtra ' ] , 4 ]
>>> q
[ 2 , 3 , ' xtra ' ]

Note that in the last example, p [ 1 ] and q refer to the same object, which can be cross-checked using the id ( ) built-in function.

>>> id ( q )
104386192
>>> id (p [1] )
104386192

Python Programming – Deleting List Elements

In this Page, We are Providing Python Programming – Deleting List Elements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Deleting List Elements

Deleting list elements

To remove a list element, one can use either the del statement (if you know the element index to delete) or remove () method (if you do not know the element index, but the element itself, discussed in section 4.1.9). The following example depicts the deletion of an element using the del statement.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> del a [ 1 ]
>>> a
[ ' spam ' , 100 , 1234 ]

The del statement can also be used to explicitly remove the entire list.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> del a 
>>> a
Traceback ( most recent call last ) :
File " <stdin> " , line 1 , in <module>
NameError: name ' a ' is not defined

The following is an interesting case of the del statement:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> del a [ 1 ] , a [ 1 ]
>>> a
[ ' spam ' , 1234 ]

It should be noted that the same index is deleted twice. As soon as an element is deleted, the indices of succeeding elements are changed. So deleting an index element n times, would actually delete n elements.

It is also possible to delete multiple items from a list.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 1 : 3 ] = [ ]
>>> a
[ ' spam ' , 1234 ]

Swapping lists

There might be a scenario in which multiple lists need to be swapped among themselves. This is can done easily using multiple assignments expression.

>>> a= [ 10 , 20 , 30 ] 
>>> b= [ 40 , 50 , 60 ] 
>>> c= [ 70 , 80 , 90 ]
>>> a , b , c=c , a , b 
>>> a
[ 70 , 80 , 90 ] 
>>> b
[ 10 , 20 , 30 ]
>>> c
[ 40 , 50 , 60 ]

Python Programming – Updating List Elements

In this Page, We are Providing Python Programming – Updating List Elements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Updating List Elements

Updating list elements

It is possible to change individual or multiple elements of a list:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 0 ]= ' filter '
>>> a
[ ' filter ' , ' eggs ' , 100 , 1234 ]
>>> a [ 2 : 4 ]= 455 , 56858 
>>> a
[ ' filter ' , ' eggs ' , 455 , 56858 ]

The items of list can be updated by the elements of another iterable (list, tuple).

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b=[ ' hi ' , ' bye ' ]
>>> a [ 2 : 4 ] =b 
>>> a
[ 66 . 25 , 333 , ' hi ' , ' bye ' , 1234 . 5 ]
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b= ( ' hi ' , ' bye ' )
>>> a [ 2 : 4 ]=b 
>>> a
[ 66 . 25 , 333 , ' hi ' , ' bye ' , 1234 . 5 ]
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b= [ ' hi ' , ' bye ' ] 
>>> a [ 1: 4 : 2 ] =b 
>>> a
[ 66 . 25 , ' hi ' , 333 , ' bye ' , 1234 . 5 ]

It is also possible to insert elements in a list.

>>> a=[ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 1 : 1 ]=[ ' chair ' ]
>>> a
[ ' spam ' , ' chair ' , ' eggs ' , 100 , 1234 ]
>>> a [ 1 : 1 ] = [ ' hello ', ' bye ' ]
>>> a
[ ' spam ' , ' hello ' , ' bye ' , ' chair ' , ' eggs ' , 100 , 1234 ]

To insert a copy of the list at the beginning of itself:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ : 0 ]=a 
>>> a
[ ' spam ' , ' eggs ' , 100 , 1234 , ' spam ' , ' eggs ' , 100 , 1234 ]

There are various methods of list objects for updating the list, which is discussed in section 4.1.9.