Saturday, 21 April 2018

Python - OOPS--getter,setter -- Day 26

  • this explains setter ,getter and decorator
  • https://www.udemy.com/python-the-complete-python-developer-course/learn/v4/t/lecture/6022196?start=0
  •   
    #getter and setter
    #this program explains about the use of get and set methods and property keyword
    #this class will be imported in the getsetmain.py,there is no need of importing this class
    #but for the clarity and navigation purpose written as 2 programs
    
    #set and get nethods can be used to set as well as check certain conditions
    #the return variables and the assignment variable name s/b different ie..level:_lvel and lives:_lives
    #if not it will result in error due to recursive
    
    #few simple objectives like lives cannot be less than 0
    #and score multiplied by 1000 for each level are achieved
    class Player:
        def __init__(self,name):
            self.name = name
            self._lives=3
            self._level = 1
            self._score=0
    
        def _setlife(self,live):
            if live>=0:
                self._lives = live
            else:
                print('live cannot be negative')
                self._lives=0
    
        def _getlife(self):
            return self._lives
    
        def _setlevel(self,level):
            if level>=1:
                delta = level-self._level
                self._score += delta * 1000
                self._level = level
            else:
                print('level cannot be less than 1 ')
    
        def _getlevel(self):
            return self._level
    
        lives = property(_getlife,_setlife)
        level = property(_getlevel,_setlevel)
    
    ####decorator
    #this is similar to the property but with different syntax
    
    #getter
        @property
        def score(self):
            return self._score
    
    #setter
        @score.setter
        def score(self,score):
            self._score = score
    
    
        def __str__(self):
            return("{0.name};lives:{0.lives};level:{0.level};score:{0.score}".format(self))
     
    
  • main program using the above imported class
  •   
    #we can use getsetplayer.Player, but since it is tedious
    #we have used the from and import like below
    
    
    
    
    from getsetplayer import Player
    
    tim = Player('tim')
    # print(tim.name)
    # print(tim.lives)
    # print(tim.score)
    # print(tim.level)
    
    print(tim)
    tim.lives-=1
    print(tim)
    tim.lives-=1
    print(tim)
    tim.lives-=1
    print(tim)
    tim.lives-=1
    print(tim)
    tim.lives=3
    tim.level+=1
    print('*********')
    print(tim)
    tim.level+=1
    print(tim)
    print('*********')
    tim.score = 500
    print(tim)
     
    

    Python - OOPS Basics-avoid circular reference- Day 26(5 days later)

  • there is circular reference in this example ie the song class has the artist object referred in it , similarly album also has artist object reference,we can remove by using their name alone instead of the whole object
  • this program explains how the class ,fields,methods can be used to store the set of info with the same format(like artist,album,song)
  •   
    
    class Song:
        """Class to represent a song
    
        Attributes:
            title (str): The title of the song
            artist (str): An artist name representing the songs creator.
            duration (int): The duration of the song in seconds.  May be zero
        """
    
        def __init__(self, title, artist, duration=0):
            self.name = title
            self.artist = artist
            self.duration = duration
    
    
    class Album:
        """ Class to represent an Album, using it's track list
    
        Attributes:
            name (str): The name of the album.
            year (int): The year was album was released.
            artist: (str): The name of the artist responsible for the album. If not specified,
            the artist will default to an artist with the name "Various Artists".
            tracks (List[Song]):  A list of the songs on the album.
    
        Methods:
            add_song: Used to add a new song to the album's track list.
        """
    
        def __init__(self, name, year, artist=""):
            self.name = name
            self.year = year
            if artist is None:
                self.artist = "Various Artists"
            else:
                self.artist = artist
    
            self.tracks = []
    
        def add_song(self, songname, position=None):
            """Adds a song to the track list
    
            Args:
                song (Song): A song to add.
                position (Optional[int]): If specified, the song will be added to that position
                    in the track list - inserting it between other songs if necessary.
                    Otherwise, the song will be added to the end of the list.
            """
            song_found = find_object(songname,self.tracks)
            if song_found is None:
                song_found = Song(songname,self.artist)
                if position is None:
                    self.tracks.append(song_found)
                else:
                    self.tracks.insert(position, song_found)
    
    class Artist:
        """Basic class to store artist details.
    
        Attributes:
            name (str): The name of the artist.
            albums (List[Album]): A list of the albums by this artist.
                The list includes only those albums in this collection, it is
                not an exhaustive list of the artist's published albums.
    
        Methods:
            add_album: Use to add a new album to the artist's albums list
        """
    
        def __init__(self, name):
            self.name = name
            self.albums = []
    
        def add_album(self, album):
            """Add a new album to the list.
    
            Args:
                album (Album): Album object to add to the list.
                    If the album is already present, it will not added again (although this is yet to implemented).
            """
            self.albums.append(album)
    
        def add_song(self, album_name, year, song_name):
            """Add a new song to the collection of albums
    
            This method will add the song to an album in the collection.
            A new album will be created in the collection if it doesn't already exist.
    
            Args:
                name (str): The name of the album
                year (int): The year the album was produced
                title (str): The title of the song
            """
            album_found = find_object(album_name, self.albums)
            if album_found is None:
                # print(name + " not found")
                album_found = Album(album_name, year, self.name)
                self.add_album(album_found)
            else:
                print("Found album " + album_name)
    
            album_found.add_song(song_name)
    
    
    def find_object(field, object_list):
        """Check 'object_list' to see if an object with a 'name' attribute equal to 'field' exists, return it if so."""
        for item in object_list:
            if item.name == field:
                return item
        return None
    
    
    def load_data():
    
        artist_list = []
    
        with open("albums.txt", "r") as albums:
            for line in albums:
                # data row should consist of (artist, album, year, song)
                artist_field, album_field, year_field, song_field = tuple(line.strip('\n').split('\t'))
                year_field = int(year_field)
                # print("{}:{}:{}:{}".format(artist_field, album_field, year_field, song_field))
    
                new_artist = find_object(artist_field, artist_list)
                if new_artist is None:
                    new_artist = Artist(artist_field)
                    artist_list.append(new_artist)
    
                new_artist.add_song(album_field, year_field, song_field)
    
        return artist_list
    
    
    def create_checkfile(artist_list):
        """Create a check file from the object data for comparison with the original file"""
        with open("checkfile.txt", 'w') as checkfile:
            for new_artist in artist_list:
                for new_album in new_artist.albums:
                    for new_song in new_album.tracks:
                        print("{0.name}\t{1.name}\t{1.year}\t{2.name}".format(new_artist, new_album, new_song),
                              file=checkfile)
    
    
    if __name__ == '__main__':
        artists = load_data()
        print("There are {} artists".format(len(artists)))
    
        create_checkfile(artists)
    
    
     
    

    Python - OOPS Basics-eg2 - artist,album,song - Day 26(5 days later)

  • this program needs a album file which can be downloaded from udemy and place it in the appropriate working folder
  • this program explains how the class ,fields,methods can be used to store the set of info with the same format(like artist,album,song)
  •   
    class Song:
        """Class to represent a song
    
        Attributes:
            title (str): The title of the song
            artist (Artist): An artist object representing the songs creator.
            duration (int): The duration of the song in seconds.  May be zero
        """
    
        def __init__(self, title, artist, duration=0):
            self.title = title
            self.artist = artist
            self.duration = duration
    
    
    class Album:
        """ Class to represent an Album, using it's track list
    
        Attributes:
            name (str): The name of the album.
            year (int): The year was album was released.
            artist: (Artist): The artist responsible for the album. If not specified,
            the artist will default to an artist with the name "Various Artists".
            tracks (List[Song]):  A list of the songs on the album.
    
        Methods:
            add_song: Used to add a new song to the album's track list.
        """
    
        def __init__(self, name, year, artist=None):
            self.name = name
            self.year = year
            if artist is None:
                self.artist = Artist("Various Artists")
            else:
                self.artist = artist
    
            self.tracks = []
    
        def add_song(self, song, position=None):
            """Adds a song to the track list
    
            Args:
                song (Song): A song to add.
                position (Optional[int]): If specified, the song will be added to that position
                    in the track list - inserting it between other songs if necessary.
                    Otherwise, the song will be added to the end of the list.
            """
            if position is None:
                self.tracks.append(song)
            else:
                self.tracks.insert(position, song)
    
    
    class Artist:
        """Basic class to store artist details.
    
        Attributes:
            name (str): The name of the artist.
            albums (List[Album]): A list of the albums by this artist.
                The list includes only those albums in this collection, it is
                not an exhaustive list of the artist's published albums.
    
        Methods:
            add_album: Use to add a new album to the artist's albums list
        """
    
        def __init__(self, name):
            self.name = name
            self.albums = []
    
        def add_album(self, album):
            """Add a new album to the list.
    
            Args:
                album (Album): Album object to add to the list.
                    If the album is already present, it will not added again (although this is yet to implemented).
            """
            self.albums.append(album)
    
    
    
    def load_data():
        new_artist = None
        new_album = None
        artist_list = []
    
        with open("albums.txt", "r") as albums:
            for line in albums:
                # data row should consist of (artist, album, year, song)
    
                artist_field, album_field, year_field, song_field = tuple(line.strip('\n').split('\t'))
                year_field = int(year_field)
                # print("{}:{}:{}:{}".format(artist_field, album_field, year_field, song_field))
    
                if new_artist is None:
                    new_artist = Artist(artist_field)
                elif new_artist.name != artist_field:
                    # We've just read details for a new artist
                    # store the current album in the currents artists collection then create a new artist object
                    new_artist.add_album(new_album)
                    artist_list.append(new_artist)
                    new_artist = Artist(artist_field)
                    new_album = None
    
                if new_album is None:
                    new_album = Album(album_field, year_field, new_artist)
                elif new_album.name != album_field:
                    # We've just read a new album for the current artist
                    # store the current album in the artist's collection then create a new album object
                    new_artist.add_album(new_album)
                    new_album = Album(album_field, year_field, new_artist)
    
                # create a new song object and add it to the current album's collection
                new_song = Song(song_field, new_artist)
                new_album.add_song(new_song)
    
            # After read the last line of the text file, we will have an artist and album that haven't
            #  been store - process them now
            if new_artist is not None:
                if new_album is not None:
                    new_artist.add_album(new_album)
                artist_list.append(new_artist)
    
        return artist_list
        # print(artist_list)
    
    
    def create_checkfile(artist_list):
        """Create a check file from the object data for comparison with the original file"""
        with open("checkfile.txt", 'w') as checkfile:
            for new_artist in artist_list:
                for new_album in new_artist.albums:
                    for new_song in new_album.tracks:
                        print("{0.name}\t{1.name}\t{1.year}\t{2.title}".format(new_artist, new_album, new_song),
                              file=checkfile)
    
    
    if __name__ == '__main__':
        artists = load_data()
        print("There are {} artists".format(len(artists)))
        #
        # create_checkfile(artists)
    
     
    
  • #In the previous program if the sort order of the artsist and album is ascending it will work properly, but if it is changed ,then it will show the wrong count,this is because the artsist object is created based oh the last inserted artist album..ie if the 2 nd inserted object repeats again at the last line then it will be treated as new artist again which is not the case this problem will be solved if look at the object list ,whether the artist or album list is already created or not ,if it created we can simply get the name and make use of,this is explained in the nex example program
  •   
    class Song:
        """
        class to represent a song
    
        Attributes:
            title():The tile of the song
            artist(Artist):An artist object representing the songs creator
            duration (int):The duration of the song in seconds.May be Zero
        """
        def __init__(self,title,artist,duration=0):
            """song init method
            Args:
                title(str):Initialises the 'title' attribute
                artist(Artist):An artist object representing the songs creator
                duration (optional int):initialise value to 'duration' attribute
                        will be defaulted to zero if not specified.
            """
            self.title = title
            self.artist = artist
            self.duration = duration
    
    
    class Album:
        """ class to represent a album,using its track list
    
        Attributes:
            name (str):The name of the album.
            year (int):The year the album was released.
            artist :(Artist):The artist responsible for the album.If not specified,
            the artist will default to an artist with the name "Various Artists".
            tracks (List[Song]):A List of songs on the album
    
            Methods:
                add_song:used to add a new song to the albums track list
        """
    
        def __init__(self,name,year,artist =None):
            self.name = name
            self.year = year
            if artist is None:
                self.artist = Artist("Various artists")
            else:
                self.artist = artist
    
            self.tracks = []
    
        def add_song(self,song,position = None):
            """Adds a song to the track list
    
            Args:
                song(Song):A song to add.
                position (optional[int]):If specified,the song will be added to that position
                    in the track list  - inserting it between other songs if necessary.
                    Otherwise,the song will be added to the end of tthe list
            """
    
            if position is None:
                self.tracks.append(song)
            else:
                self.tracks.insert(position,song)
    
    
    class Artist:
        """Basic class to store artist details
    
        Attributes:
            name(str):The name of the artist
            albums (List[Album]):A list of albums by this artist.
                    The list includes only those albums in this collection,it is
                    not an exhaustive list of the artist's published albums
    
        Methods:
            add_album:used to add a new album to the artists's album list
    
        """
    
        def __init__(self,name):
            self.name = name
            self.albums = []
    
        def add_album(self,album):
            """
            Add a new album to the list.
    
            Args:
                album(Album):Album object to add to the list.
                    If the album is already present,it will not be added again (although it is yet to be implemented).
            """
            self.albums.append(album)
    
    
    def checkobjectexist (field,object_list):
        for item in object_list:
            if item.name == field:
                return item
        return None
    
    def load_data():
        new_artist = None
        new_album = None
        artist_list = []
    
        with open("albums.txt","r") as albums:
            for line in albums:
                #data row should consist of (artist,album,year,song)
                artist_field,album_field,year_field,song_field = tuple(line.strip('\n').split('\t'))
                year_field = int(year_field)
                if new_artist is None:
                    new_artist = Artist(artist_field)
                    artist_list.append(new_artist)
                elif new_artist.name != artist_field:
                    #we have just read details for new artist
                    #check for the existence of the object
                    new_artist = checkobjectexist(artist_field,artist_list)
                    if new_artist is None:
                        new_artist = Artist(artist_field)
                        artist_list.append(new_artist)
                    new_album = None
    
                if new_album is None:
                    new_album = Album(album_field,year_field,new_artist)
                    new_artist.add_album(new_album)
                elif new_album.name != album_field:
                    #we have just read details for new album for the current artist
                    #check whether the album already exists in the list
                    new_album = checkobjectexist(album_field,new_artist.albums)
                    if new_album is None:
                        new_album = Album(album_field,year_field,new_artist)
                        new_artist.add_album(new_album)
    
            #create a new song object and add it to the current album's collection
                new_song = Song(song_field,new_artist)
                new_album.add_song(new_song)
    
        return artist_list
    
    # def create_checkfile(artist_list):
    #     """Create a check file from the object data for comparison with the original file"""
    #     with open("checkfile.txt", 'w') as checkfile:
    #         for new_artist in artist_list:
    #             for new_album in new_artist.albums:
    #                 for new_song in new_album.tracks:
    #                     print("{0.name}\t{1.name}\t{1.year}\t{2.title}".format(new_artist, new_album, new_song),
    #                           file=checkfile)
    
    
    
    if __name__ == '__main__':
        artists = load_data()
        print(len(artists))
    
        # for new_artist in artists:
        #     for new_album in new_artist.albums:
        #         print(new_album.name,new_album.tracks)
    # create_checkfile(artists)
    
     
    
  • The below program produces the same result,except that the concepts that are used like checking the existence of the artist and album are done inside the class
  •   
    class Song:
        """
        class to represent a song
    
        Attributes:
            title():The tile of the song
            artist(Artist):An artist object representing the songs creator
            duration (int):The duration of the song in seconds.May be Zero
        """
        def __init__(self,title,artist,duration=0):
            """song init method
            Args:
                title(str):Initialises the 'title' attribute
                artist(Artist):An artist object representing the songs creator
                duration (optional int):initialise value to 'duration' attribute
                        will be defaulted to zero if not specified.
            """
            self.name = title
            self.artist = artist
            self.duration = duration
    
    
    class Album:
        """ class to represent a album,using its track list
    
        Attributes:
            name (str):The name of the album.
            year (int):The year the album was released.
            artist :(Artist):The artist responsible for the album.If not specified,
            the artist will default to an artist with the name "Various Artists".
            tracks (List[Song]):A List of songs on the album
    
            Methods:
                add_song:used to add a new song to the albums track list
        """
    
        def __init__(self,name,year,artist =None):
            self.name = name
            self.year = year
            if artist is None:
                self.artist = Artist("Various artists")
            else:
                self.artist = artist
    
            self.tracks = []
    
        def add_song(self,songname,position = None):
            """Adds a song to the track list
    
            Args:
                song(Song):A song to add.
                position (optional[int]):If specified,the song will be added to that position
                    in the track list  - inserting it between other songs if necessary.
                    Otherwise,the song will be added to the end of tthe list
            """
            # print(self.name,self.tracks)
            # print('***')
            song_found = checkobjectexist(songname,self.tracks)
            # print('***')
            if song_found is None:
                song_found = Song(songname,self.artist)
                # print("Song Not Found")
                if position is None:
                    self.tracks.append(song_found)
                else:
                    self.tracks.insert(position,song_found)
    
    
    class Artist:
        """Basic class to store artist details
    
        Attributes:
            name(str):The name of the artist
            albums (List[Album]):A list of albums by this artist.
                    The list includes only those albums in this collection,it is
                    not an exhaustive list of the artist's published albums
    
        Methods:
            add_album:used to add a new album to the artists's album list
    
        """
    
        def __init__(self,name):
            self.name = name
            self.albums = []
    
        def add_album(self,album):
            """
            Add a new album to the list.
    
            Args:
                album(Album):Album object to add to the list.
                    If the album is already present,it will not be added again (although it is yet to be implemented).
            """
            self.albums.append(album)
    
        def add_song(self,album_name,year,song_name):
            album_found = checkobjectexist(album_name,self.albums)
            if album_found is None:
                # print("Album Not Found")
                album_found = Album(album_name,year,self)
                self.add_album(album_found)
            else:
                print("Found Album")
    
            album_found.add_song(song_name)
    
    def checkobjectexist (field,object_list):
        for item in object_list:
            if item.name == field:
                return item
        return None
    
    def load_data():
        artist_list = []
    
        with open("albums.txt","r") as albums:
            for line in albums:
                #data row should consist of (artist,album,year,song)
                artist_field,album_field,year_field,song_field = tuple(line.strip('\n').split('\t'))
                year_field = int(year_field)
    
                new_artist = checkobjectexist(artist_field,artist_list)
                if new_artist is None:
                    new_artist = Artist(artist_field)
                    artist_list.append(new_artist)
    
                new_artist.add_song(album_field,year_field,song_field)
    
        return artist_list
    
    # def create_checkfile(artist_list):
    #     """Create a check file from the object data for comparison with the original file"""
    #     with open("checkfile.txt", 'w') as checkfile:
    #         for new_artist in artist_list:
    #             for new_album in new_artist.albums:
    #                 for new_song in new_album.tracks:
    #                     print("{0.name}\t{1.name}\t{1.year}\t{2.title}".format(new_artist, new_album, new_song),
    #                           file=checkfile)
    
    
    
    if __name__ == '__main__':
        artists = load_data()
        print(len(artists))
    
        # for new_artist in artists:
        #     for new_album in new_artist.albums:
        #         print(new_album.name,new_album.tracks)
    # create_checkfile(artists)
    
     
    

    Sunday, 15 April 2018

    Python - OOPS Basics-eg1 - Day 25(4 days later)

  • simple program on bank account concept,based on oops
  •   
    import datetime
    import pytz
    class Account:
    
        #this will be static method,ie it will be common for all instances(ie the class)
        #so while accessing it no need of using self
        @staticmethod
        def _current_time():
            utc_time = datetime.datetime.utcnow()
            return pytz.utc.localize(utc_time)
    
    
    
        def __init__(self,name,_balance):
            self._name =name
            self._transactiondetails_list = [(Account._current_time(), _balance)]
            self._balance = _balance
            print("Account Created for {}".format(self._name))
            self.showbalance()
    
        def deposit(self,amount):
            self._balance+=amount
            self.showbalance()
            self._transactiondetails_list.append((Account._current_time(), amount))
            # self.transactiondetails_list.append((pytz.utc.localize(datetime.datetime.utcnow()),amount))
            # print(self.transactiondetails_list)
    
        def withdraw(self,amount):
            if(0 < amount<=self._balance):
                self._balance-=amount
                self._transactiondetails_list.append((Account._current_time(), -amount))
            else:
                print("Amount should be greater than 0 and lesser than available balance")
            self.showbalance()
    
        def showbalance(self):
            print('Balance: ', self._balance)
    
        def showtransdetails(self):
            for date, amount in self._transactiondetails_list:
                if amount > 0:
                    tran_type ='Deposited'
                else:
                    tran_type ='Withdrwan'
                    amount*=-1
                print("{:6} {} on {} (local time was {})".format(amount,tran_type,date,date.astimezone()))
    
    udai = Account('udai',1000)
    #udai.withdraw(100)
    # udai.withdraw(200)
    # udai.deposit(200)
    # #we can update the balance variable to whatever we want outside of the class,so we can rename
    # #to _balance,which will also dont restrict to change , but user can know that
    # #it is for internal purpose and shouldn't be modified,similarly for the name and list variables
    # #which should not be modified after the instantiation
    # # udai.balance=0
    # udai.showbalance()
    # udai.showtransdetails()
    
    #its better not to mess with '_' and '__' objects which will produce strange results
    udai.showbalance()
    udai._balance = 10
    udai.showbalance()
    print('*'*40)
    print(udai.__dict__)
    print(Account.__dict__)
    udai.__balance = 49
    udai.showbalance()
    udai.showbalance()
    print(udai.__dict__)
    print(Account.__dict__)
     
    

    Python - OOPS Basics - Day 25(4 days later)

  • Class:template for creating objects.All objects created using the same class will have the same charecteristics Objects:an instance of a class Instantiate:Create a Instance of a class Method:a funtion defined in a class Attribute:a variable bound to a instance of a class
  •   
    #everything is objects in python
    #take away : class and objects
    
    # a = 1
    # b = 3
    # print (a + b)
    # print (a.__add__(b))
    #so + is same as __add__ ,if u ctrl right click it will goto the same definition
    
    class kettle (object):
    
        power_source = 'fuel'
    
        def __init__(self,make,price):
            self.make = make
            self.price = price
            self.on = False
    
        def switch_on(self):
            self.on = True
    
    kenwoodobj = kettle('kenwood',25)
    hamilton = kettle('hamilton',30)
    
    print(kenwoodobj.make)
    print(hamilton.make)
    print(hamilton.price)
    hamilton.make = 'Hamiltoon'
    print(hamilton.make)
    print(kenwoodobj)
    
    print ('{}={},{}={}'.format(kenwoodobj.make,kenwoodobj.price,hamilton.make,hamilton.price))
    kenwoodobj1 = kenwoodobj
    print(id(kenwoodobj1))
    print(id(kenwoodobj))
    print(id(hamilton))
    print(id(hamilton.make))
    
    #we can call the object by
    #classname.objectname(instancename)
    #or
    #instancename.objectname()
    kettle.switch_on(hamilton)
    print(hamilton.make)
    print(hamilton.on)
    hamilton.on = False
    print(hamilton.on)
    hamilton.switch_on()
    print(hamilton.on)
    
    #this is called as instance variable,variable is only for this instance,not for the entire instances of the
    #class
    kenwoodobj.power = 1.5
    print(kenwoodobj.power)
    #if we try accessing the same variable for different instance,it will throw error
    # print(hamilton.power)
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    print ('*' * 80)
    
    # kettle.power_source = 'atomic'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    print ('/' * 80)
    
    #if we assign the value for the calss attribute instance,it becomes instance vriable and remains
    #unaffected for the class and other instances
    kenwoodobj.power_source = 'gas'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    print ('*' * 80)
    hamilton.power_source = 'fossil fuel'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    hamilton.power_source = 'fuel'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    print ('@' * 80)
    
    kettle.power_source = 'fuel'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
     
    
  • this will explain how a basic program document has to be written
  •   
    #this will explain you how to document a program(DocString)
    class song:
        """
        class to represent a song
    
        Attributes:
            title():The tile of the song
            artist(Artist):An artist object representing the songs creator
            duration (int):The duration of the song in seconds.May be Zero
        """
        def __int__(self,title,artist,duration=0):
            """song init method
            Args:
                title(str):Intialises the 'title' attribute
                artist(Artist):An artist object representing the songs creator
                duration (optional int):initialise value to 'duration' attribute
                        will be defaulted to zero if not specified.
    
    
            """
            self.title = title
            self.artist = artist
            self.duration = duration
     
    

    Python - scope and recursive function - Day 25(4 days later)

  • this will explain the variable's scope.
  •   
    #take way:read the document related to local,nonlocal,global
    #know what is LEGB - Local Enclosing Global Builtins
    #below example will illustrate the variable and the scope of it
    
    
    # def spam1():
    #     def spam2():
    #         def spam3():
    #             z = ' even more spam'
    #             print('3 {}'.format(locals()))
    #             return z
    #         y = 'more spam '
    #         y+= spam3()
    #         print('2 {}'.format(locals()))
    #         return y
    #     x = 'spam '
    #     x+= spam2()
    #     print('1 {}'.format(locals()))
    #     print(x)
    
    def spam1():
        def spam2():
            def spam3():
                # y = 'test'
                z = ' even' + y
                print('3 {}'.format(locals()))
                return z
            y = ' more'+x
            y+= spam3()
            print('2 {}'.format(locals()))
            return y
        x = 'spam'
        x+= spam2()
        # we can't write like this x = 'spam' + spam2(),since spam2 function first expects x
        # it will throw unreferenced variable error if we code like that
        print('1 {}'.format(locals()))
        print(x)
    
    print(spam1())
    print(locals())
    print(globals())
     
    
  • this will explain how the recursive funtion can be made use of
  •   
    #recursive function,function that calls itself again and again
    #factorial
    
    def factorial(n):
        result = 1
        if n>1:
            for i in range (1,n+1):
                result = result * i
        return result
    
    def factorialrec(n):
        #n factorial can also be defined as n * (n-1)!
        if n<=1:
            return 1
        else:
            return n * factorialrec(n-1)
    
    def fibonaccirec(n):
        # Fn = Fn-1 + Fn-2
        if n<2:
            return n
        else:
            return fibonaccirec(n-1)+fibonaccirec(n-2)
    
    def fibonacci(n):
        if n == 0:
            return 0
        if n == 1:
            return 1
        elif n==2:
            return 1
        else:
            n_minus1 = 1
            n_minus2 = 0
            for i in range(1,n):
                result = n_minus1+n_minus2
                n_minus2 = n_minus1
                n_minus1 = result
            return result
    
    
    
    
    # for x in range (1,130):
    #     print(x , factorial(x))
    
    # for x in range (1,130):
    #     print(x , factorialrec(x))
    
    # here use of the recursive funtion in calculating the fibonaaci
    #might slow downb the process,so we can go for direct method
    
    # for x in range (1,36):
    #     print(x , fibonaccirec(x))
    
    #below direct method will be fast
    for x in range (1,36):
        print(x , fibonacci(x))
     
    

    Monday, 9 April 2018

    Python - using underscore - Day 24

      
    #there is nothing like private or protected concept in python
    #if we want to treat something as private we can use underscore '_'
    # in front of the name,although it wont have any programming influence,
    # but for the users understanding,also the objects starting with '_' won't be
    # displayed if we use import *,although we can access using the modulename.objectname
    # import blackjacktest1
    # g = sorted(globals())
    # for x in g:
    #     print(x)
    # for x in globals():
    #     print(x)
    # print (__name__)
    # blackjacktest1.play()
    
    #if you rename by prefexing any of the funtion with '_' and check the below loop will not return
    #those funtions or objects
    
    from blackjacktest1 import *
    g = sorted(globals())
    for x in g:
        print(x)
    
    #we can use '_' or '__' as variable name, thoughh it is not the proper way of naming variable
    _ = 'a'
    print(_)
    __ = 'ab'
    print(__)
    
    personaldetails =('udai',23,'welcome')
    name,_,__ = personaldetails
    print(name,_,__)
     
    

    Sunday, 8 April 2018

    Python - import challenge - blackjack game - Day 23


  • if we directly import the module it will execute w/o users control..ie it will execute immediately after the import statement which is not intended..
  • here few changes are made to run the module from other code..ie by importing it and calling the functionality whenever needed
  • we can make use of the __name__ to do this

  •   
    #this is extension of blackjack game to include the new game button and shuffle button
    
    import tkinter as tkinter
    import random
    
    try:
        import tkinter
    except ImportError:  # python 2
        import Tkinter as tkinter
    def load_images(card_images):
        suits=['heart','club','diamond','spade']
        face_cards=['jack','queen','king']
    
        if tkinter.TkVersion >= 8.6:
            extension = 'png'
        else:
            extension = 'ppm'
        #for each suit retrieve the image for the cards
        for suit in suits:
            #first the number cards 1 to 10
            for card in range(1,11):
                name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
                image = tkinter.PhotoImage(file = name)
                card_images.append((card,image))
            #next the Face Cards
            for card in face_cards:
                name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
                image = tkinter.PhotoImage(file = name)
                card_images.append((10,image))
    
    def deal_card(frame):
        #pop the next card of the top of the deck
        next_card= deck.pop(0)
        #if the player keeps on playing new game then all the cards will be used so
        deck.append(next_card)
        #add the image to the label and display the label
        tkinter.Label(frame,image=next_card[1],relief = 'raised').pack(side = 'left')
        #now return the cards face value
        return next_card
    
    
    def score_hand(hand):
        # Calculate the total score of all cards in the list.
        # Only one ace can have the value 11, and this will be reduce to 1 if the hand would bust.
        score = 0
        ace = False
        for next_card in hand:
            card_value = next_card[0]
            if card_value == 1 and not ace:
                ace = True
                card_value = 11
            # score += card_value
            score = score + card_value
            # if we would bust, check if there is an ace and subtract 10
            if score > 21 and ace:
                # score -= 10
                score = score - 10
                ace = False
        return score
    
    def deal_dealer():
        dealer_score= score_hand(dealer_hand)
        while 0 < dealer_score <17:
            dealer_hand.append(deal_card(dealer_card_frame))
            dealer_score= score_hand(dealer_hand)
            dealer_score_label.set(dealer_score)
    
        player_score = score_hand(player_hand)
        if player_score>21:
            resulttext.set('Dealer Wins!')
        elif dealer_score > 21 or dealer_score player_score:
            resulttext.set('Dealer Wins!')
        else:
            resulttext.set('Draw!')
    
        # player_score_label.set(player_score)
        # if player_score>21:
        #     resulttext.set ('Dealer Wins')
    
    
    # def deal_player():
    #     deal_card(player_card_frame)
    
    def deal_player():
        player_hand.append(deal_card(player_card_frame))
        player_score= score_hand(player_hand)
    
        player_score_label.set(player_score)
        if player_score>21:
            resulttext.set ('Dealer Wins')
        # global player_score
        # global player_ace
        # card_value = deal_card(player_card_frame)[0]
        # if card_value ==1 and not player_ace:
        #     player_ace = True
        #     card_value = 11
        # player_score = player_score + card_value
        # # if we would bust,check if there is an ace and subtract
        # if player_score>21 and player_ace:
        #     player_score = player_score - 10
        #     player_ace = False
        # player_score_label.set(player_score)
        # if player_score>21:
        #     resulttext.set("Dealer Wins")
        # print(locals())
    
    def new_game():
        global dealer_card_frame
        global player_card_frame
        global dealer_hand
        global player_hand
        # embedded frame to hold the card images
        dealer_card_frame.destroy()
        dealer_card_frame = tkinter.Frame(card_frame, background='green')
        dealer_card_frame.grid(row=0, column=1, sticky='ew', rowspan=2)
        # embedded frame to hold the card images
        player_card_frame.destroy()
        player_card_frame = tkinter.Frame(card_frame, background="green")
        player_card_frame.grid(row=2, column=1, sticky='ew', rowspan=2)
    
        resulttext.set("")
    
        # Create the list to store the dealer's and player's hands
        dealer_hand = []
        player_hand = []
    
        deal_player()
        dealer_hand.append(deal_card(dealer_card_frame))
        dealer_score_label.set(score_hand(dealer_hand))
        deal_player()
    
    def shuffle():
        random.shuffle(deck)
    
    
    
    def play():
        deal_player()
        dealer_hand.append(deal_card(dealer_card_frame))
        dealer_score_label.set(score_hand(dealer_hand))
        deal_player()
        mainwindow.mainloop()
    
    
    mainwindow = tkinter.Tk()
    #setup the screens and frame for the dealer and the player
    mainwindow.title("blackjack")
    mainwindow.geometry("640x480")
    mainwindow.configure(background = "green")
    
    resulttext = tkinter.StringVar()
    result = tkinter.Label(mainwindow,textvariable = resulttext)
    result.grid(row=0,column=0,columnspan=3)
    
    card_frame= tkinter.Frame(mainwindow,relief = 'sunken',borderwidth = 1,background = 'green')
    card_frame.grid(row=1,column=0,sticky = 'ew',columnspan = 3,rowspan=2)
    
    dealer_score_label = tkinter.IntVar()
    tkinter.Label(card_frame,text = 'Dealer',background ='green',fg='white').grid(row=0,column=0)
    tkinter.Label(card_frame,textvariable = dealer_score_label,background ='green',fg='white').grid(row=1,column=0)
    
    #embedded Frame hold the card images
    dealer_card_frame=tkinter.Frame(card_frame,background = 'green')
    dealer_card_frame.grid(row=0,column=1,sticky='ew',rowspan=2)
    
    
    player_score_label = tkinter.IntVar()
    tkinter.Label(card_frame,text = 'Player',background ='green',fg='white').grid(row=2,column=0)
    tkinter.Label(card_frame,textvariable = player_score_label,background ='green',fg='white').grid(row=3,column=0)
    #embedded Frame hold the card images
    player_card_frame=tkinter.Frame(card_frame,background = 'green')
    player_card_frame.grid(row=2,column=1,sticky='ew',rowspan=2)
    
    button_frame = tkinter.Frame(mainwindow)
    button_frame.grid(row=3,column=0,columnspan = 3,sticky = 'w')
    
    dealer_button=tkinter.Button(button_frame,text = 'Dealer',command = deal_dealer)
    dealer_button.grid(row=0,column=0)
    
    player_button=tkinter.Button(button_frame,text = 'Player',command = deal_player)
    player_button.grid(row=0,column=1)
    
    new_game_button=tkinter.Button(button_frame,text = 'New Game',command = new_game)
    new_game_button.grid(row=0,column=2)
    
    shuffle_button = tkinter.Button(button_frame, text="Shuffle", command=shuffle)
    shuffle_button.grid(row=0, column=3)
    
    #load cards
    cards = []
    load_images(cards)
    # print(cards)
    # print(id(cards))
    #create a new deck of cards and shuffle them
    deck = list(cards) + list(cards) + list(cards)
    shuffle()
    
    # Create the list to store the dealer's and player's hands
    dealer_hand = []
    player_hand = []
    
    if __name__ == '__main__':
        play()
    
    
     
    
  • we can import by using the code like below one
  •   
    import blackjacktest1
    print (__name__)
    blackjacktest1.play()
     
    

    Python - function challenge - blackjack game extension - Day 23


  • #this is extension of blackjack game to include the new game button and shuffle button

  •   
    #this is extension of blackjack game to include the new game button and shuffle button
    
    import tkinter as tkinter
    import random
    
    try:
        import tkinter
    except ImportError:  # python 2
        import Tkinter as tkinter
    def load_images(card_images):
        suits=['heart','club','diamond','spade']
        face_cards=['jack','queen','king']
    
        if tkinter.TkVersion >= 8.6:
            extension = 'png'
        else:
            extension = 'ppm'
        #for each suit retrieve the image for the cards
        for suit in suits:
            #first the number cards 1 to 10
            for card in range(1,11):
                name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
                image = tkinter.PhotoImage(file = name)
                card_images.append((card,image))
            #next the Face Cards
            for card in face_cards:
                name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
                image = tkinter.PhotoImage(file = name)
                card_images.append((10,image))
    
    def deal_card(frame):
        #pop the next card of the top of the deck
        next_card= deck.pop(0)
        #if the player keeps on playing new game then all the cards will be used so
        deck.append(next_card)
        #add the image to the label and display the label
        tkinter.Label(frame,image=next_card[1],relief = 'raised').pack(side = 'left')
        #now return the cards face value
        return next_card
    
    
    def score_hand(hand):
        # Calculate the total score of all cards in the list.
        # Only one ace can have the value 11, and this will be reduce to 1 if the hand would bust.
        score = 0
        ace = False
        for next_card in hand:
            card_value = next_card[0]
            if card_value == 1 and not ace:
                ace = True
                card_value = 11
            # score += card_value
            score = score + card_value
            # if we would bust, check if there is an ace and subtract 10
            if score > 21 and ace:
                # score -= 10
                score = score - 10
                ace = False
        return score
    
    def deal_dealer():
        dealer_score= score_hand(dealer_hand)
        while 0 < dealer_score <17:
            dealer_hand.append(deal_card(dealer_card_frame))
            dealer_score= score_hand(dealer_hand)
            dealer_score_label.set(dealer_score)
    
        player_score = score_hand(player_hand)
        if player_score>21:
            resulttext.set('Dealer Wins!')
        elif dealer_score > 21 or dealer_score player_score:
            resulttext.set('Dealer Wins!')
        else:
            resulttext.set('Draw!')
    
        # player_score_label.set(player_score)
        # if player_score>21:
        #     resulttext.set ('Dealer Wins')
    
    
    # def deal_player():
    #     deal_card(player_card_frame)
    
    def deal_player():
        player_hand.append(deal_card(player_card_frame))
        player_score= score_hand(player_hand)
    
        player_score_label.set(player_score)
        if player_score>21:
            resulttext.set ('Dealer Wins')
        # global player_score
        # global player_ace
        # card_value = deal_card(player_card_frame)[0]
        # if card_value ==1 and not player_ace:
        #     player_ace = True
        #     card_value = 11
        # player_score = player_score + card_value
        # # if we would bust,check if there is an ace and subtract
        # if player_score>21 and player_ace:
        #     player_score = player_score - 10
        #     player_ace = False
        # player_score_label.set(player_score)
        # if player_score>21:
        #     resulttext.set("Dealer Wins")
        # print(locals())
    
    def new_game():
        global dealer_card_frame
        global player_card_frame
        global dealer_hand
        global player_hand
        # embedded frame to hold the card images
        dealer_card_frame.destroy()
        dealer_card_frame = tkinter.Frame(card_frame, background='green')
        dealer_card_frame.grid(row=0, column=1, sticky='ew', rowspan=2)
        # embedded frame to hold the card images
        player_card_frame.destroy()
        player_card_frame = tkinter.Frame(card_frame, background="green")
        player_card_frame.grid(row=2, column=1, sticky='ew', rowspan=2)
    
        resulttext.set("")
    
        # Create the list to store the dealer's and player's hands
        dealer_hand = []
        player_hand = []
    
        deal_player()
        dealer_hand.append(deal_card(dealer_card_frame))
        dealer_score_label.set(score_hand(dealer_hand))
        deal_player()
    
    def shuffle():
        random.shuffle(deck)
    
    mainwindow = tkinter.Tk()
    
    #setup the screens and frame for the dealer and the player
    mainwindow.title("blackjack")
    mainwindow.geometry("640x480")
    mainwindow.configure(background = "green")
    
    resulttext = tkinter.StringVar()
    result = tkinter.Label(mainwindow,textvariable = resulttext)
    result.grid(row=0,column=0,columnspan=3)
    
    card_frame= tkinter.Frame(mainwindow,relief = 'sunken',borderwidth = 1,background = 'green')
    card_frame.grid(row=1,column=0,sticky = 'ew',columnspan = 3,rowspan=2)
    
    dealer_score_label = tkinter.IntVar()
    tkinter.Label(card_frame,text = 'Dealer',background ='green',fg='white').grid(row=0,column=0)
    tkinter.Label(card_frame,textvariable = dealer_score_label,background ='green',fg='white').grid(row=1,column=0)
    
    #embedded Frame hold the card images
    dealer_card_frame=tkinter.Frame(card_frame,background = 'green')
    dealer_card_frame.grid(row=0,column=1,sticky='ew',rowspan=2)
    
    
    player_score_label = tkinter.IntVar()
    tkinter.Label(card_frame,text = 'Player',background ='green',fg='white').grid(row=2,column=0)
    tkinter.Label(card_frame,textvariable = player_score_label,background ='green',fg='white').grid(row=3,column=0)
    #embedded Frame hold the card images
    player_card_frame=tkinter.Frame(card_frame,background = 'green')
    player_card_frame.grid(row=2,column=1,sticky='ew',rowspan=2)
    
    button_frame = tkinter.Frame(mainwindow)
    button_frame.grid(row=3,column=0,columnspan = 3,sticky = 'w')
    
    dealer_button=tkinter.Button(button_frame,text = 'Dealer',command = deal_dealer)
    dealer_button.grid(row=0,column=0)
    
    player_button=tkinter.Button(button_frame,text = 'Player',command = deal_player)
    player_button.grid(row=0,column=1)
    
    new_game_button=tkinter.Button(button_frame,text = 'New Game',command = new_game)
    new_game_button.grid(row=0,column=2)
    
    shuffle_button = tkinter.Button(button_frame, text="Shuffle", command=shuffle)
    shuffle_button.grid(row=0, column=3)
    
    #load cards
    cards = []
    load_images(cards)
    # print(cards)
    # print(id(cards))
    #create a new deck of cards and shuffle them
    deck = list(cards) + list(cards) + list(cards)
    shuffle()
    
    # Create the list to store the dealer's and player's hands
    dealer_hand = []
    player_hand = []
    
    new_game()
    
    mainwindow.mainloop()
    
     
    

    Saturday, 7 April 2018

    Python - function challenge - blackjack game - Day 22(after 1 day)


  • first we will download the cards image from the svg online or search in github
  • then extract and place those file in the project folder

  •   
    #this program explains how to achieve the blackjack game
    #the key points to note here are
    #pop funtion,using the same code of function to avoid repetition
    #load images from file to frame,shuffling of cards,calculating scores
    #then use of the global keyword to avoiding shadowing of the global variable inside the function
    
    import tkinter as tkinter
    import random
    
    def load_images(card_images):
        suits=['heart','club','diamond','spade']
        face_cards=['jack','queen','king']
    
        #for each suit retrieve the image for the cards
        for suit in suits:
            #first the number cards 1 to 10
            for card in range(1,11):
                name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
                image = tkinter.PhotoImage(file = name)
                card_images.append((card,image))
            #next the Face Cards
            for card in face_cards:
                name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
                image = tkinter.PhotoImage(file = name)
                card_images.append((10,image))
    
    def deal_card(frame):
        #pop the next card of the top of the deck
        next_card= deck.pop(0)
        #add the image to the label and display the label
        tkinter.Label(frame,image=next_card[1],relief = 'raised').pack(side = 'left')
        #now return the cards face value
        return next_card
    
    def deal_dealer():
        dealer_score= score_hand(dealer_hand)
        while 0 < dealer_score <17:
            dealer_hand.append(deal_card(dealer_card_frame))
            dealer_score= score_hand(dealer_hand)
            dealer_score_label.set(dealer_score)
    
        player_score = score_hand(player_hand)
        if player_score>21:
            resulttext.set('Dealer Wins!')
        elif dealer_score > 21 or dealer_score player_score:
            resulttext.set('Dealer Wins!')
        else:
            resulttext.set('Draw!')
    
        # player_score_label.set(player_score)
        # if player_score>21:
        #     resulttext.set ('Dealer Wins')
    
    
    # def deal_player():
    #     deal_card(player_card_frame)
    
    def deal_player():
        player_hand.append(deal_card(player_card_frame))
        player_score= score_hand(player_hand)
    
        player_score_label.set(player_score)
        if player_score>21:
            resulttext.set ('Dealer Wins')
        #below code is used for testing the global,local shadowing concept 
        # global player_score
        # global player_ace
        # card_value = deal_card(player_card_frame)[0]
        # if card_value ==1 and not player_ace:
        #     player_ace = True
        #     card_value = 11
        # player_score = player_score + card_value
        # # if we would bust,check if there is an ace and subtract
        # if player_score>21 and player_ace:
        #     player_score = player_score - 10
        #     player_ace = False
        # player_score_label.set(player_score)
        # if player_score>21:
        #     resulttext.set("Dealer Wins")
        # print(locals())
    
    def score_hand(hand):
        #calculate the total score of all cards in the list
        # only one can have the value 11,and this will be reduce to 1 if the hand would bust.
        score = 0
        ace = False
        for next_card in hand:
            card_value = next_card[0]
            if card_value == 1 and not ace:
                ace = True
                card_value = 11
            score = score + card_value
            #if we would bust ,check if there is an ace and subtract 10
            if score > 21 and ace:
                score =score - 10
                ace = False
            return score
    
    
    mainwindow = tkinter.Tk()
    
    #setup the screens and frame for the dealer and the player
    mainwindow.title("blackjack")
    mainwindow.geometry("640x480")
    mainwindow.configure(background = "green")
    
    resulttext = tkinter.StringVar()
    result = tkinter.Label(mainwindow,textvariable = resulttext)
    result.grid(row=0,column=0,columnspan=3)
    
    card_frame= tkinter.Frame(mainwindow,relief = 'sunken',borderwidth = 1,background = 'green')
    card_frame.grid(row=1,column=0,sticky = 'ew',columnspan = 3,rowspan=2)
    
    dealer_score_label = tkinter.IntVar()
    tkinter.Label(card_frame,text = 'Dealer',background ='green',fg='white').grid(row=0,column=0)
    tkinter.Label(card_frame,textvariable = dealer_score_label,background ='green',fg='white').grid(row=1,column=0)
    
    #embedded Frame hold the card images
    dealer_card_frame=tkinter.Frame(card_frame,background = 'green')
    dealer_card_frame.grid(row=0,column=1,sticky='ew',rowspan=2)
    
    
    player_score_label = tkinter.IntVar()
    tkinter.Label(card_frame,text = 'Player',background ='green',fg='white').grid(row=2,column=0)
    tkinter.Label(card_frame,textvariable = player_score_label,background ='green',fg='white').grid(row=3,column=0)
    #embedded Frame hold the card images
    player_card_frame=tkinter.Frame(card_frame,background = 'green')
    player_card_frame.grid(row=2,column=1,sticky='ew',rowspan=2)
    
    button_frame = tkinter.Frame(mainwindow)
    button_frame.grid(row=3,column=0,columnspan = 3,sticky = 'w')
    
    dealer_button=tkinter.Button(button_frame,text = 'Dealer',command = deal_dealer)
    dealer_button.grid(row=0,column=0)
    
    player_button=tkinter.Button(button_frame,text = 'Player',command = deal_player)
    player_button.grid(row=0,column=1)
    
    #load cards
    cards = []
    load_images(cards)
    # print(cards)
    # print(id(cards))
    #create a new deck of cards and shuffle them
    deck = list(cards)
    random.shuffle(deck)
    
    #Create the list to store the dealers and players hands
    dealer_hand = []
    player_hand = []
    
    deal_player()
    dealer_hand.append(deal_card(dealer_card_frame))
    deal_player()
    
    mainwindow.mainloop()
     
    

    Friday, 6 April 2018

    Python function -circle challenge 1 - Day 21(after 1 day)


  • this code will draw circle through function,by passing the center,radius

  •   
    #instead of using the for loop outside we can plot it in the parabol
    #funtion itself
    import math
    import tkinter
    
    def parabola(page,size):
        for x in range(-size,size):
            y = x * x/size
            plot(page,x,y)
    
    #the formula behind this is for circle it is enough to draw one quadrant and
    #then negating it the axis will provide the symmetry and make an circle
    #ie .. we have y = h + (math.sqrt(radius ** 2 -((x-g)**2)))
    #we want y = h - (math.sqrt(radius ** 2 -((x-g)**2)))
    #but minus y is actually -y = h - (math.sqrt(radius ** 2 -((x-g)**2)))
    #so we add 2 * h back onto -y
    def circle(page,radius,g,h):
        for x in range(g,g + radius):
            y = h + (math.sqrt(radius ** 2 -((x-g)**2)))
            plot(page,x,y)
            plot(page,x,2* h - y)
            plot(page,2 * g - x,y)
            plot(page,2 * g - x,2* h - y)
    
    def draw_axes(page):
        page.configure(scrollregion=(-200,-200,200,200))
        page.create_line(-200,0,200,0, fill="blue")
        page.create_line(0,200,0,-200, fill="blue")
    
    def plot(canvas,x,y):
        canvas.create_line(x,-y,x+1,-y+1,fill="red")
    
    mainwindow = tkinter.Tk()
    
    mainwindow.title("Parabola")
    mainwindow.geometry("640x480")
    
    canvas = tkinter.Canvas(mainwindow,width=640,height= 480)
    canvas.grid(row=0,column=0)
    
    
    print(id(canvas))
    
    draw_axes(canvas)
    parabola(canvas,100)
    parabola(canvas,150)
    
    circle(canvas,100,100,100)
    circle(canvas,100,100,-100)
    circle(canvas,100,-100,100)
    circle(canvas,100,-100,-100)
    circle(canvas,30,30,30)
    circle(canvas,30,30,-30)
    circle(canvas,30,-30,30)
    circle(canvas,30,-30,-30)
    
    # for x in range(-100,100):
    #     y = parabola(x)
    #     plot(canvas,x,-y)
    
    mainwindow.mainloop()
     
    

    Python function scope - Day 20(after 20 days)


  • this will explain how the scope of the variable works
  • here we are trying to plot the parabola by calling the function
  • we have used canvas variable one inside and another outside of the function to show how the scope works

  •   
    #this will explain the scope of the variable
    #we can use locals() to know the variable in that scopre,this can be used only inside functions
    
    import tkinter
    
    
    def parabola(x):
        y = x * x/100
        return y
    
    
    def draw_axes(canvas):
        #the canvas variable here is different from the canvas outside
        #of this function
        # canvas.update
        #here the x and y origin are not fetching properly so hardcoded the values
        # x_origin = canvas.winfo_width ()/2
        # y_origin = canvas.winfo_height()/2
        # x_origin = canvas.winfo_width ()
        # y_origin = canvas.winfo_height()
        canvas.configure(scrollregion=(-200,-200,200,200))
        canvas.create_line(-200,0,200,0, fill="blue")
        canvas.create_line(0,200,0,-200, fill="blue")
        #this will give the object location(address),we can differentiate object of same names
        #using this id()
        print(id(canvas))
        print(locals())
    
    def plot(canvas,x,y):
        canvas.create_line(x,y,x+1,y+1,fill="red")
    
    mainwindow = tkinter.Tk()
    
    mainwindow.title("Parabola")
    mainwindow.geometry("640x480")
    
    canvas = tkinter.Canvas(mainwindow,width=320,height= 480)
    canvas.grid(row=0,column=0)
    
    #we have created two canvas to show how the scope works
    canvas2 = tkinter.Canvas(mainwindow,width=320,height= 480)
    canvas2.grid(row=0,column=1)
    
    print(id(canvas))
    print(id(canvas2))
    
    draw_axes(canvas)
    draw_axes(canvas2)
    
    for x in range(-100,100):
        y = parabola(x)
        plot(canvas,x,-y)
    
    
    mainwindow.mainloop()
     
    

    Thursday, 15 March 2018

    Python function eg - Day 20


  • this will explain how to create a funtion in python and call it,if the funtion doesnot returns any value then it will be treated as none
  • to view the definition of the function you can do -- ctrl + left click

  •   
    def python_food():
        print("Spinach is good for health")
    
    python_food()
    print (python_food())
    
    def center_text():
        width = 50
        text = 'Spinach is good for health'
        leftalignment = (width - len(text))//2
        print(' '*leftalignment,text)
    
    center_text()
    print('='*20)
    
    def center_text1(text):
        width = 50
        leftalignment = (width - len(text))//2
        print(' '*leftalignment,text)
    
    
    
    center_text1('Spinach is Good for Health')
    center_text1('Excecise is goood for body')
    center_text1('Life is worth living')
    center_text1('Love yourself')
     
    
  • the below code is the text behind the print function,we can see only the basic info not the code since this is written in C-language
  •  
     
    def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
        """
        print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
        
        Prints the values to a stream, or to sys.stdout by default.
        Optional keyword arguments:
        file:  a file-like object (stream); defaults to the current sys.stdout.
        sep:   string inserted between values, default a space.
        end:   string appended after the last value, default a newline.
        flush: whether to forcibly flush the stream.
        """
        pass
     
    

    Python tkinter - Calculator GUI - Day 20


  • this is the code for the model calculator,it is just a GUI,funtionality will be implemented in later lessons

  •   
    import tkinter
    
    keys = [[('C','1'),('CE','1')],
            [('7','1'),('8','1'),('9','1'),('+','1')],
            [('4','1'),('5','1'),('6','1'),('-','1')],
            [('1','1'),('2','1'),('3','1'),('*','1')],
            [('0','1'),('=','1'),('/','1')]]
    
    mainWindowPadding = 10
    
    mainWindow = tkinter.Tk()
    mainWindow.title("Calculator")
    mainWindow.geometry("800x480-8+200")
    mainWindow["padx"]= mainWindowPadding
    
    result = tkinter.Entry(mainWindow)
    result.grid(row=0,column=0,sticky = 'nsew')
    
    keypad = tkinter.Frame(mainWindow)
    keypad.grid(row=1,column=0,sticky = 'nsew')
    
    row = 0
    for keyrow in keys:
        column = 0
        for key in keyrow:
            tkinter.Button(keypad,text = key[0]).grid(row=row,column=column,
    columnspan = key[1],sticky ='ew')
            column+=1
        row+=1
    
    
    mainWindow.update()
    mainWindow.minsize(keypad.winfo_width()+mainWindowPadding,result.winfo_height()
    +keypad.winfo_height())
    mainWindow.maxsize(keypad.winfo_width()+50 + mainWindowPadding,result.winfo_height()+50 
    + keypad.winfo_height())
    mainWindow.mainloop()
     
    

    Wednesday, 14 March 2018

    Python tkinter advanced gui - Day 19


  • #weight property ,is used so that we can decide which rows and columns should remain less expandable or minimizable when maximizing the window or shrinking it. titles buttons should have less weight where as scroll bar,list should have more weight

  •   
    import tkinter
    import os
    
    mainwindow = tkinter.Tk()
    mainwindow.title("GRID DEMO")
    mainwindow.geometry('600x480-8-200')
    
    label =tkinter.Label(mainwindow,text ='tkinter grid demo label')
    label.grid(row=0,column=0,columnspan = 3)
    
    mainwindow.columnconfigure(0,weight=1)
    mainwindow.columnconfigure(1,weight=1)
    mainwindow.columnconfigure(2,weight=3)
    mainwindow.columnconfigure(3,weight=3)
    mainwindow.columnconfigure(4,weight=3)
    mainwindow.rowconfigure(0,weight=1)
    mainwindow.rowconfigure(1,weight=10)
    mainwindow.rowconfigure(2,weight=1)
    mainwindow.rowconfigure(3,weight=3)
    mainwindow.rowconfigure(4,weight=3)
    
    filelist =tkinter.Listbox(mainwindow)
    filelist.grid(row=1,column=0,sticky = 'nsew',rowspan=2)
    filelist.config(border=2,relief = 'sunken')
    for zone in os.listdir('/Windows/System32/drivers/'):#sample path
        filelist.insert(tkinter.END,zone)
    
    listscroll = tkinter.Scrollbar(mainwindow,orient = tkinter.VERTICAL,command = filelist.yview)
    listscroll.grid(row = 1,column=1,sticky = 'nsw',rowspan=2)
    filelist['yscrollcommand']=listscroll.set
    
    optionframe = tkinter.LabelFrame(mainwindow,text = 'File Details')
    optionframe.grid(row=1,column=2,sticky ='ne')
    
    rbvalue = tkinter.IntVar()
    rbvalue.set(3)#to set the default option for radiobutton
    
    #radio Buttons
    radio1= tkinter.Radiobutton(optionframe,text = 'FileName',value =1,variable =rbvalue)
    radio2= tkinter.Radiobutton(optionframe,text = 'Path',value =2,variable =rbvalue)
    radio3= tkinter.Radiobutton(optionframe,text = 'TimeStamp',value =3,variable =rbvalue)
    radio1.grid(row=0,column=0,sticky ='w')
    radio2.grid(row=1,column=0,sticky ='w')
    radio3.grid(row=2,column=0,sticky ='w')
    
    #widget to display the result
    resultLabel = tkinter.Label(mainwindow,text ="Result")
    resultLabel.grid(row=2,column=2,sticky='nw')
    result = tkinter.Entry(mainwindow)
    result.grid(row=2,column=2,sticky='sw')
    
    #Frame for Time Spinners
    timeFrame = tkinter.LabelFrame(mainwindow,text = 'Time')
    timeFrame.grid(row=3,column=0,sticky = 'new')
    #Time Spinners
    hourSpinner = tkinter.Spinbox(timeFrame,width=2,values = tuple(range(0,24)))
    minuteSpinner = tkinter.Spinbox(timeFrame,width=2,from_=0,to=59)
    secondSpinner = tkinter.Spinbox(timeFrame,width=2,values = tuple(range(0,60)))
    hourSpinner.grid(row=0,column=0)
    tkinter.Label(timeFrame,text=':').grid(row=0,column=1)
    minuteSpinner.grid(row=0,column=2)
    tkinter.Label(timeFrame,text=':').grid(row=0,column=3)
    secondSpinner.grid(row=0,column=4)
    timeFrame['padx']=36
    
    #Frame for Date Spinners
    dateFrame = tkinter.Frame(mainwindow)
    dateFrame.grid(row=4,column=0,sticky = 'new')
    #Date Labels
    dayLabel = tkinter.Label(dateFrame,text='Day')
    monthLabel = tkinter.Label(dateFrame,text='Month')
    yearLabel = tkinter.Label(dateFrame,text='Year')
    dayLabel.grid(row=0,column=0,sticky ='w')
    monthLabel.grid(row=0,column=1,sticky ='w')
    yearLabel.grid(row=0,column=2,sticky ='w')
    #Date Spinners
    daySpin = tkinter.Spinbox(dateFrame,width=5,from_=1,to=31)
    monthSpin = tkinter.Spinbox(dateFrame,width=5,values=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"))
    yearSpin = tkinter.Spinbox(dateFrame,width=5,from_=2000,to=2099)
    daySpin.grid(row=1,column=0)
    monthSpin.grid(row=1,column=1)
    yearSpin.grid(row=1,column=2)
    
    #buttons
    okButton = tkinter.Button(mainwindow,text = 'OK')
    cancelButton = tkinter.Button(mainwindow,text = 'Cancel',command = mainwindow.destroy)
    okButton.grid(row=4,column=3,sticky='e')
    cancelButton.grid(row=4,column=4,sticky='w')
    
    mainwindow.mainloop()
    print (rbvalue.get())#to confirm the selection of correct value in radio button
     
    

    Tuesday, 13 March 2018

    Python tkinter - Day 18(10 days later)



  • Tkinter provides classes which allow the display, positioning and control of widgets. Toplevel widgets are Tk and Toplevel. Other widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton, Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox LabelFrame and PanedWindow.

  •   
    import tkinter
    print(tkinter.TkVersion)
    print(tkinter.TclVersion)
    
    # tkinter._test()
    # or we can use the below piece of code
    
    mainWindowvar = tkinter.Tk()
    
    mainWindowvar.title('test')
    # mainWindow.geometry('2000x2000')
    #below code will specify the screen size and position of the
    #new window
    mainWindowvar.geometry('400x400-5-10')
    
    
    # # help(tkinter)
    #
    # labelvar = tkinter.Label(mainWindowvar,text = "this is label")
    # labelvar.pack(side = "top")
    #
    # canvasvar = tkinter.Canvas(mainWindowvar, relief = 'raised',borderwidth=1)
    # canvasvar.pack(side='left', anchor = 'n')
    # button1 = tkinter.Button(mainWindowvar,text = "button1")
    # button2 = tkinter.Button(mainWindowvar,text = "button2")
    # button3 = tkinter.Button(mainWindowvar,text = "button3")
    # button1.pack(side ='top')
    # button2.pack(side ='top')
    # button3.pack(side ='top')
    #
    # mainWindowvar.mainloop()
    
    
    # help(tkinter)
    
    #the above code will work but to make it proper we
    #can introduce frame
    
    labelvar = tkinter.Label(mainWindowvar,text = "this is label")
    labelvar.pack(side = "top")
    
    leftframevar = tkinter.Frame(mainWindowvar)
    leftframevar.pack(side='left',anchor = 'n',fill=tkinter.Y,expand =False)
    
    canvasvar = tkinter.Canvas(leftframevar, relief = 'raised',borderwidth=1)
    canvasvar.pack(side='left', anchor = 'n')
    
    rightframevar = tkinter.Frame(mainWindowvar)
    rightframevar.pack(side='right',anchor = 'n',fill=tkinter.Y,expand =True)
    
    button1 = tkinter.Button(rightframevar,text = "button1")
    button2 = tkinter.Button(rightframevar,text = "button2")
    button3 = tkinter.Button(rightframevar,text = "button3")
    button1.pack(side ='top')
    button2.pack(side ='top')
    button3.pack(side ='top')
    
    mainWindowvar.mainloop()
    
    
     
    

    Wednesday, 28 February 2018

    Python timezone challenge- Day 17


  • the challenge here is to let the user choose the time zone from list of time zones and accordingly display the time
  •   
    import datetime
    import pytz
    
    available_zones ={"1":"African/Tunis",
     "2":"Asia/Kolkata",
     "3":"Australia/Adelaide",
     "4":"Europe/Brussels",
     "5":"Europe/London",
     "6":"Japan",
     "7":"Pacific/Tahiti"
    }
    print("Please Choose the timezone (or 0 to quit)")
    for place in sorted(available_zones):
        print("\t {} : {}".format(place,available_zones[place]))
    
    while True:
        choice = input()
        if choice == 0:
            break
        if choice in available_zones.keys():
            tz_to_display = pytz.timezone(available_zones[choice])
            world_time = datetime.datetime.now(tz=tz_to_display)
            print ("The time in {} is {} {} ".format(available_zones[choice],
                                 world_time.strftime("%A %x %X %z"),world_time.tzname()))
            print("LocalTime is {}".format(datetime.datetime.now().strftime("%A %x %X %z")))
            print("UTCTime is {}".format(datetime.datetime.utcnow().strftime("%A %x %X %z")))
    
     
    

    Python timezone - Day 16(1 day later)


  • pip command,if it doesn't work ,open the python setup goto modify and check the add python to environment variables option python time zone library package,pip3 install pytz
  •   
    import pytz
    import datetime
    country = "Europe/Moscow" #check for the spelling and case sensitivity
    tz_to_display = pytz.timezone(country)
    # print(tz_to_display)
    # print(country)
    print("The time in {} is {}".format(country,datetime.datetime.now(tz=tz_to_display)))
    print("UTC is {}".format(datetime.datetime.utcnow()))
    print("LocalTime here is {}".format(datetime.datetime.now()))
    tz_to_display = pytz.timezone("Singapore")
    print("The time in {} is {}".format("Singapore",datetime.datetime.now(tz=tz_to_display)))
    
    #list of all timezones
    for x in pytz.all_timezones:
        print(x)
    print("=="*50)
    print(pytz.country_names)
    #list of all countries
    for x in pytz.country_names:
        print(x)
    
    for x in sorted(pytz.country_names):
        print(x + ": " + pytz.country_names[x])
    
    #although the below code will run,there will be error ,since the few countries
    #like (Bouvet Island ) have not defined the timezones
    # for x in sorted(pytz.country_names):
    #     print("{} : {} : {}".format(x,pytz.country_names[x],pytz.country_timezones(x)))
    
    print("=================="*10)
    #we can use the get method to avoid the below issue
    for x in sorted(pytz.country_names):
        print("{} : {} : {}".format(x,pytz.country_names[x],pytz.country_timezones.get(x)))
    print("*************"*10)
    #we can also use the below method
    for x in sorted(pytz.country_names):
        print("{} : {} ".format(x,pytz.country_names[x],end = ' '))
        if x in (pytz.country_timezones):
            print(pytz.country_timezones[x])
        else:
            print("TimeZone Not Defined")
     
    

    Monday, 26 February 2018

    Python date time calendar module - Day 15


  • time module
  •   
    # import time
    # # print(time.gmtime())
    # # ##epoch time
    # # print(time.gmtime(0))
    # # print("="*40)
    # # print(time.localtime())
    # # print("="*40)
    # # ##seconds till now from epoch time
    # # print(time.time())
    #
    # time_here = time.localtime()
    # print(time_here)
    # #time_here is a tuple ,we can make use of the tuple index or name ,so that
    # #we can get the desired part of the date
    # print("year:",time_here[0],time_here.tm_year)
    # print("Month:",time_here[1],time_here.tm_mon)
    # print("Day:",time_here[2],time_here.tm_mday)
    
    #reaction time game
    
    
    # import time
    # from time import time as my_timer
    # import random
    #
    # input("press enter to start")
    # wait_time = random.randint(1,6)
    # time.sleep(wait_time)
    # start_time=my_timer()
    # input("press enter to stop")
    # end_time=my_timer()
    #
    # print(start_time,end_time)
    # print("started at "+ time.strftime("%X",time.localtime(start_time)))
    # print("Ended at "+ time.strftime("%X",time.localtime(end_time)))
    # print("Time taken for response was {}".format(end_time-start_time))
    
    
  • #apart from the time method we also have three other methods that we can make use of #monotonic - this can be used ,so that even if there is daylight saving time,activates #in the mean time or the user changes the clock in system,always the end time #will be higher than the #start time if we use the monotonic #other 1 is perf_counter #and the process_time is the elapsed cpu time for the process #proposal for python - PEP 0418 can read from there
  • import time # # from time import perf_counter as my_timer # # from time import monotonic as my_timer # from time import process_time as my_timer # import random # # # input("press enter to start") # wait_time = random.randint(1,6) # time.sleep(wait_time) # start_time=my_timer() # input("press enter to stop") # end_time=my_timer() # # print(start_time,end_time) # print("started at "+ time.strftime("%X",time.localtime(start_time))) # print("Ended at "+ time.strftime("%X",time.localtime(end_time))) # print("Time taken for response was {}".format(end_time-start_time)) #info about the each clock print("time():\t\t\t",time.get_clock_info("time")) print("monotonic():\t",time.get_clock_info("monotonic")) print("perf_counter():\t",time.get_clock_info("perf_counter")) print("process_time():\t",time.get_clock_info("process_time"))

    Sunday, 25 February 2018

    Python Modules - Day 14(day later)


  • we can import modules using the module name and import keyword we can import the full module or specific functions in that module if there is any reference warning right click on the function and choose ignore unresolved references
  •   
    # import turtle
    #
    #
    # turtle.forward(400)
    # turtle.circle(250)
    # turtle.right(300)
    #
    # #the done function is used to hold the screen to see the result
    # #or else we can use the time module and sleep function
    #
    #
    # for i in range(0,100,10):
    #     turtle.forward(i)
    #     turtle.circle(i)
    #     turtle.right(i)
    #
    #
    # turtle.done()
    
    
    #if we need only the particular functions we can code like below
    # from turtle import circle,done
    #
    # circle(70)
    # done()
    
    #or else we can do use *
    # from turtle import *
    #
    # circle(70)
    # done()
    
    #we will get the error if we run the below piece of code
    #since the done is common here,we declared as string,but the turtle method
    #also has the "done" as function
    done = "done with the drawing"
    
    import turtle
    
    turtle.forward(400)
    turtle.circle(250)
    turtle.right(300)
    
    done()
    print(done)
    
    #here we can check the list of objects inside the
    #inbuilt modules of the python
    #we can also ctrl + click the module name to find the list of objects
    
    print(dir())
    #the above line will print
    
    #['__annotations__', '__builtins__', '__cached__', '__doc__',
    ## '__file__', '__loader__', '__name__', '__package__', '__spec__']
    print("="*40)
    for i in dir():
        print(i)
    print(dir('__builtins__'))
    #the above line will print
    
    #['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
    # '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
    # '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
    # '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
    # '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
    # 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
    # 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier',
    #  'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
    # 'lower',
    #  'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
    #  'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
    # 'translate', 'upper', 'zfill']
    
    print("="*40)
    for i in dir('__builtins__'):
        print(i)
    
    #lets check for the shelve now
    
    import shelve
    
    print(dir())
    # ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', 
    #'__name__',
    #  '__package__', '__spec__', 'i', 'shelve']
    
    print(dir(shelve))
    # ['BsdDbShelf', 'BytesIO', 'DbfilenameShelf', 'Pickler',
    # 'Shelf', 'Unpickler', '_ClosedDict', '__all__', '__builtins__',
    # '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__',
    # 'collections', 'open']
    print(dir(shelve.Shelf))
    print('=='*20)
    for i in dir(shelve.Shelf):
        print(i)
    
    
    
    #we can use the help function to know the functionality
    
    
    
    help(shelve)
    print("*"*20)
    help(shelve.Shelf)
    
    import  random
    help(random)
    print("*"*20)
    help(random.randint)
    
     
    

    Friday, 23 February 2018

    Python Shelve eg2....- Day 13


  • updating shelve
  •   
    import shelve
    # with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveeg3") as fruit:
    fruit = shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveeg3")
    fruit['orange']='citrus fruit'
    fruit['apple']='good for health'
    fruit['lemon']='small fruit'
    fruit['papaya']='good for eye'
    
    print(fruit)
    print(fruit['lemon'])
    
    fruit['lemon']='Can Make Juice'
    
    print(fruit)
    print(fruit['lemon'])
    
    for i in fruit:
        print(i +" - " + fruit[i])
    print("="*40)
    
    # while True:
    #     var1 = input("enter any fruit key - ")
    #     if var1 =='quit':
    #         break
    #     # print(fruit.get(var1,'entered key doent exits'))
    #     if var1 in fruit:
    #         print(fruit[var1])
    #     else:
    #         print('entered key does not exits')
    
    #to get the shelve in sorted order
    shelvesortlist = list(fruit.keys())
    shelvesortlist.sort()
    print(shelvesortlist)
    print(fruit)
    for var2 in shelvesortlist:
        print(var2+" - "+fruit[var2])
    print (fruit.values())
    print (fruit.items())
    print (fruit.keys())
    fruit.close()
    
    
    #the below example is not prefect,but the thing is there is a concept of writeback and sync
    #related to shelve object,which can be used to update the shelve based on memory usage
    #the benefits of these will be know later i guess.
    
    
    import shelve
    
    blt = ["bread","bacon","lettuce"]
    egg = ["boiled egg","Milk"]
    butter = ["cheese","butter"]
    pasta = ["pasta","macroni"]
    
    with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveupdateeg4") as recipes:
        recipes["blt"]=blt
        recipes["egg"]=egg
        recipes["butter"]=butter
        recipes["pasta"]=pasta
        print(recipes)
    
        for var1 in recipes:
            print(var1,recipes[var1])
    
    #in the eg above if we want to update the items against any key in shelve,
    #if we use append method ,it wont update the shelve like check using the below code
        recipes["egg"].append("omlette")
        for var1 in recipes:
            print(var1,recipes[var1])
    #we can update it correcty by changing the list itself and reassigning to the shelve
        templist = ["boiled egg","Milk","omlette"]
        recipes["egg"]=templist
        for var1 in recipes:
            print(var1,recipes[var1])
    
    print("="*40)
    with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveupdateeg4") as recipes:
        for var1 in recipes:
            print(var1,recipes[var1])
    print('*'*40)
    
     
    

    Thursday, 22 February 2018

    Python Shelve- Day 12(1 day later)

  • #shelve are same like dictionary,except that shelve can be used while #dealing with extremely large dictionary,dictionary will be handled in memory, #where as shelve will handle in a separate file #key points to note in shelve is that , the file with extension .db(or dit,bak,dat) ## will be created, #in dictionary since it is in memory,even if there is any mistake like type we can #change it immediately by changing the typo ,where as in shelve we have to #delete that key combination
  •   
    import shelve
    
    # with shelve.open("D:/WORK/2018/February/22-02-2018-Thursday/shelvetest1")as fruit:
    #     fruit = {"orange":"its a fruit which is orange in color",
    #               "apple":"good for health"}
    #     print(fruit)
    #     print(fruit["orange"])
    # print("="*40)
    # print(fruit["orange"])
    # print(fruit)
    
    with shelve.open("D:/WORK/2018/February/22-02-2018-Thursday/shelvetest2")as fruit:
        fruit["orange"]="its a fruit which is orange in color"
        fruit["apple"]="good for health"
    print(fruit)
    print("="*40)
    #the below peice of code will throw an error
    # print(fruit["orange"])
    
    
    with shelve.open("D:/WORK/2018/February/22-02-2018-Thursday/shelvebike1")as bike:
        bike["name"]="tvs"
        bike["engine_cc"]="250 cc"
        #even if removed and executes the below code it will be saved
        #in the first run and remains there,which is not the case if
        #it is normal dictionary
        # bike["engin_cc"]="250 cc"
        bike["model"]="victor"
        print(bike)
        for i in bike:
            print(i)
            print(bike[i])
    ###############################################################################
    import shelve
    
    with shelve.open("D:/WORK/2018/February/22-02-2018-Thursday/shelvebike1")as bike:
        bike["name"]="tvs"
        bike["engine_cc"]="250 cc"
        #even if removed and executes the below code it will be saved
        #in the first run and remains there,which is not the case if
        #it is normal dictionary
        # bike["engin_cc"]="250 cc"
        #we can delete that key using,it has to be run one time only
        # del bike["engin_cc"]
        bike["model"]="victor"
        print(bike)
        for i in bike:
            print(i)
            print(bike[i])
    
     
    

    Python Read Write File,Binary Read Write File - Day 11(2 days later)

  • *Read Write File

  •   
    # #this shows how to open and read contents from the file
    # samplefilevar = open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')
    # for linevar in samplefilevar:
    #     print (linevar)
    # samplefilevar.close()
    #
    # print("===="*20)
    # #print only the lines containing the specific word
    # samplefilevar = open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')
    # for linevar in samplefilevar:
    #     if "file" in linevar.lower():
    #         print (linevar,end = '')
    # samplefilevar.close()
    # print("===="*20)
    # #using with keyword will automatically close the file,we dont need to
    # #use the separate close statement
    #
    # with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')as var2:
    #     for line in var2:
    #         #end = '' is used to avoid using the extra empty line
    #         print(line,end='')
    
    # with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')as var2:
    #     line =var2.readline()
    #     print(line)
    # with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplereadfile.txt",'r')as var2:
    #     #readlines will read all lines and piut it into list,so it is better to use readline,
    #     #since the readlines will read the entire file in memory,where as readline will
    #     #go row by row
    #     lines =var2.readlines()
    #     print(lines)
    #
    # for line1 in lines:
    #     print(line1,end='')
    
    #write contents to a file
    # cities = ["Delhi","Bombay","Chennai"]
    #
    # with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile1.txt",'w')as var2:
    #     for city in cities:
    #         print(city,file=var2)
    #
    # with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile1.txt",'r')as var3:
    #     cities = var3.readlines()
    # print(cities)
    #
    # #strip functions strips the character that is present at the end or beginning 
    #,but not the middle
    # for city in cities:
    #     print(city)
    #     print(city.strip("\n"))
    #
    # cityvar1 = []
    # with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile1.txt",'r')as var3:
    #     cities = var3.readlines()
    #     for city in cities:
    #         cityvar1.append(city)
    #
    # print(cityvar1)
    #
    # cityvar2 = []
    # with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile1.txt",'r')as var3:
    #     cities = var3.readlines()
    #     for city in cities:
    #         cityvar2.append(city.strip("\n"))
    #
    # print(cityvar2)
    #
    # strvar1 = "testing"
    # print(strvar1.strip("s"))
    # print(strvar1.strip("g"))
    # #below will remove t at the beginning not the st at the middle
    # print(strvar1.strip("st"))
    
    
    #tuples to file
    # albumtuplevar2 = "muthu","rahman",2000,(1,"oruvan oruvan"),(2,"kuluvall"),(3,"vidukathaya")
    # print(albumtuplevar2)
    # title,composer,year,track1,track2,track3 =albumtuplevar2
    # print(title)
    # print(composer)
    # print(year)
    # print(track1)
    # print(track2)
    # print(track3)
    #
    # with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile2.txt",'w')as var2:
    #     print(albumtuplevar2,file=var2)
    
    with open("D:/WORK/2018\February/20-02-2018-Tuesday/pythonsamplewritefile2.txt",'r')as var3:
        var4 = var3.readlines()
    print(var4)
    print(var4)
    ######################################################################
    #appending the tables to the existing file
    #if we use the mode 'a',it will append it ,if we use the mode 'w',it will overwrite the file
    #our challenge is to print like
    #1 times 2 is 2
    #2 times 2 is 4
    #....
    #likewise till 13 table
    
    with open("D:/WORK/2018/February/20-02-2018-Tuesday/pythonwritefile3.txt",'w')as tables:
        for i in range(1,1000):
            for j in range(1,1000):
                print("{1} times {0} is {2}".format(i,j,i*j),file=tables)
            print("=="*20,file=tables)
    
    #######################################################################
    #We can use pickle ,instead of converting the binaty manually and reconverting
    #while reading
    
    import pickle
    
    imedla = ('More Mayhem',
              'Imelda May',
              '2011',
              ((1,'Pulling the rug'),
               (2,'Psycho'),
               (3,'Mayhem'),
               (4,'Kentish Town Waltz')))
    
    # with open("D:/WORK/2018/February/22-02-2018-Thursday/pythonwritefilebinary.pickle","wb") 
    as pickle_file:
    #     pickle.dump(imedla,pickle_file)
    
    with open("D:/WORK/2018/February/22-02-2018-Thursday/pythonwritefilebinary.pickle","rb")
    as imelda_pickled:
        imelda2 = pickle.load(imelda_pickled)
    
    print(imelda_pickled)
    print(imelda2)
    album,artist,year,tracklist = imelda2
    print (album)
    print (artist)
    print (year)
    for track in tracklist:
        trackno,tracktile = track
        print("{0} : {1}".format(trackno,tracktile))
    #########################################################################################
    #storing multiple objects in the binary file and retrieving it in the same order
    import pickle
    
    imedla = ('More Mayhem',
              'Imelda May',
              '2011',
              ((1,'Pulling the rug'),
               (2,'Psycho'),
               (3,'Mayhem'),
               (4,'Kentish Town Waltz')))
    
    even = list(range(0,10,2))
    odd = list(range(1,10,2))
    
    with open("D:/WORK/2018/February/22-02-2018-Thursday/pythonwritefilebinary2.pickle","wb") 
    as pickle_file:
        pickle.dump(imedla,pickle_file,protocol=0)
        pickle.dump(even,pickle_file,protocol=0)
        pickle.dump(odd,pickle_file,protocol=0)
        pickle.dump(12345,pickle_file,protocol=0)
    #to read the above objects we need to read it in the same order ie..tuples,list,variable
    
    with open("D:/WORK/2018/February/22-02-2018-Thursday/pythonwritefilebinary2.pickle","rb")
    as imelda_pickled:
        imelda2 = pickle.load(imelda_pickled)
        even_list = pickle.load(imelda_pickled)
        odd_list = pickle.load(imelda_pickled)
        x = pickle.load(imelda_pickled)
    
    print(imelda_pickled)
    print(imelda2)
    album,artist,year,tracklist = imelda2
    print (album)
    print (artist)
    print (year)
    for track in tracklist:
        trackno,tracktile = track
        print("{0} : {1}".format(trackno,tracktile))
    
    print("="*40)
    
    for i in even_list:
        print(i)
    print("="*40)
    for i in odd_list:
        print(i)
    print("="*40)
    print(x)
    ###################################################################################
    
     
    

    Monday, 19 February 2018

    Python Sets - Day 10(day later)

  • *like dictioanry,but don't have keys
  • *immutable objects
  • *no order
  • *2 ways to create a set,one like the dictioanry,other by using the set keyword
  •   
    farm_animals = {"cow","goat"}
    print(farm_animals)
    wild_animals= set(["Lion","Tiger"])
    farm_animals.add("horse")
    print(farm_animals)
    wild_animals.add("horse")
    print(wild_animals)
    
    evennos = set(range(0,50,2))
    print(evennos)
    
    evennos = set(range(0,50,2))
    print(evennos)
    squares = {4,9,16,25,36}
    print(squares)
    print(sorted(squares))
    print (squares.union(evennos))
    #both will produce same result
    print (evennos.union(squares))
    #both will produce same result
    print (squares.intersection(evennos))
    print (evennos.intersection(squares))
    print (evennos & squares)
    print (squares & evennos )
    
    #*empty set can not be created by using the curly braces {},since it will be treated as 
    dictionary when calling the add method
    emptyset1 = {}
    print(emptyset1)
    #the below code will throw error
    # emptyset1.add("1")
    print(emptyset1)
    emptyset2 = set()
    print(emptyset2)
    #but not the below code
    emptyset2.add("1")
    print(emptyset2)
    
    #differences/Minus
    print(evennos)
    print(squares)
    
    
    print("squares minus evenos")
    print(squares.difference((evennos)))
    print(squares - evennos)
    
    print("evenos minus squares ")
    print(evennos.difference((squares)))
    print(evennos - squares)
    
    #update the difference in the set
    
    squaretuple = (4,9,16,25,36)
    squarenos = set(squaretuple)
    evennos = set(range(0,50,2))
    print(sorted(evennos))
    print(sorted(squarenos))
    print("="*40)
    #will update the set after the difference
    evennos.difference_update(squarenos)
    print(evennos)
    
    
    #symmetric difference,it is exact opposite of intersection
    
    squarenos1 = {4,9,16,25,36}
    evennos1 = set(range(0,50,2))
    print(sorted(squarenos1))
    print(sorted(evennos1))
    
    print(evennos1.symmetric_difference(squarenos1))
    #it will return the same result for both the line of the code
    print(squarenos1.symmetric_difference(evennos1))
    
    #discard & Remove,these two will affect the sets directly,
    #disacard wont throw an error ,even if the value is not present there in the set,
    #where as remove will throw if it does not exits
    
    print(sorted(squarenos1))
    print(sorted(evennos1))
    
    squarenos1.discard(4)
    squarenos1.remove(16)
    print(sorted(squarenos1))
    #wont throw error
    squarenos1.discard(5)
    #will throw error
    # squarenos1.remove(5)
    
    evensquarenos2 = {4,16,36}
    evennos2 = set(range(0,50,2))
    print(sorted(evensquarenos2))
    print(sorted(evennos2))
    
    if evennos2.issuperset(evensquarenos2):
        print("evennos is the superset of the evensquarenos")
    
    if evensquarenos2.issubset(evennos2):
        print("evensquarenos is the subset of the evennos")
    
    
    #frozenset,we can add,edit,remove the frozen set,but can do other operations 
    #like union,intersection...
    evenfrozen = frozenset({2,4,6})
    print(evenfrozen)
    #the below line will throw an error,since we are trying 
    #to modify the frozen set which is not allowed
    # evenfrozen.add(8)
    
    
    #challenge ,remove the vowels from the string
    
    stringval1= set("python is trending language")
    stringval2= set("abcdefghijklmnopqrstuvwxyz")
    frozensetstring = frozenset("aeiou")
    print(stringval1.difference(frozensetstring))
    print(sorted(stringval2.difference(frozensetstring)))
    
    
     
    

    Saturday, 17 February 2018

    Python Dictionaries CopyUpdate- Day 9(After 6 days)

  • Dictionary Copy Update Concept
  •   
    # filmsvar1 = {"muthu":"one of the movie in which rajini comes in double role",
    #          "basha":"Don of a don movie,a cult hit",
    #          "enthiran":"rajini's scifi movie",
    #          "murattu kalai":"movie taken in paganeri"}
    #
    # filmsvar2 = {"BLoodStonte":"Rajini's Hollywood Movie",
    #              "enthiran2":"Upcoming Movie"}
    #
    # # print(filmsvar1)
    # # print(filmsvar2)
    # # #this will update the filmsvar1 wont create a separate object
    # # filmsvar1.update(filmsvar2)
    # # print(filmsvar1)
    # # print(filmsvar2)
    #
    # #to make a copy of dictionary
    #
    # filmsvar3 = filmsvar2.copy()
    # print(filmsvar2)
    # print(filmsvar3)
    # filmsvar2.update(filmsvar1)
    # print(filmsvar2)
    # print(filmsvar3)
    #
    # #Use the old challenge and make it work even if the user types valley,road directly
    #
    # location = {0:"You are Sitting in front of comp",
    #             1:"You are in road",
    #             2:"At the top of the hill",
    #             3:"Building",
    #             4:"You are across Valley",
    #             5:"Roaming at forest"}
    # exits = {0:{"Q":0},
    #          1:{"N":5,"5":5,"S":4,"4":4,"E":3,"3":3,"Q":0},
    #          2:{"N":5,"5":5,"Q":0},
    #          3:{"W":1,"1":1,"Q":0},
    #          4:{"W":2,"2":2,"N":1,"1":1,"Q":0},
    #          5:{"S":1,"1":1,"W":2,"2":2,"Q":0}}
    #
    # vocabularyvar = {"NORTH":"N","SOUTH":"S","EAST":"E","WEST":"W","QUIT":"Q",
    #                  "ROAD":"1","HILL":"2","BUILDING":"3","VALLEY":"4","FOREST":"5"}
    #
    # loc=1
    # while True:
    #     availablexits = ""
    #     #we can use join to do the fllowing
    #     # for direction in exits[loc].keys():
    #     #     availablexits +=direction+ ","
    #     availablexits = ','.join(exits[loc].keys())
    #
    #     print(location[loc])
    #
    #     if loc == 0:
    #         break
    #
    #     direction = input("Available Exits are "+ availablexits).upper()
    #     if len(direction)>0:
    #         words = direction.split()
    #         for word in words:
    #             if word in vocabularyvar:
    #                 direction = vocabularyvar[word]
    #                 print(direction)
    #     print()
    #     if direction in exits[loc]:
    #         loc = exits[loc][direction]
    #     else:
    #         print("You cannot go in that direction")
    
    #the above code will work,but it will unnecessarily will show no's 1,2,3,4,5 in the
    # available exits,so we can use the copy and update funtions in dictionary to solve those issues
    
    location = {0:"You are Sitting in front of comp",
                1:"You are in road",
                2:"At the top of the hill",
                3:"Building",
                4:"You are across Valley",
                5:"Roaming at forest"}
    exits = {0:{"Q":0},
             1:{"N":5,"S":4,"E":3,"Q":0},
             2:{"N":5,"Q":0},
             3:{"W":1,"Q":0},
             4:{"W":2,"N":1,"Q":0},
             5:{"S":1,"W":2,"Q":0}}
    
    namedexits  = {1:{"5":5,"4":4,"3":3,"Q":0},
                   2:{"5":5,"Q":0},
                   3:{"1":1,"Q":0},
                   4:{"2":2,"1":1,"Q":0},
                   5:{"1":1,"2":2,"Q":0}}
    
    vocabularyvar = {"NORTH":"N","SOUTH":"S","EAST":"E","WEST":"W","QUIT":"Q",
                     "ROAD":"1","HILL":"2","BUILDING":"3","VALLEY":"4","FOREST":"5"}
    
    loc=1
    while True:
        availablexits = ""
        #we can use join to do the fllowing
        # for direction in exits[loc].keys():
        #     availablexits +=direction+ ","
        availablexits = ','.join(exits[loc].keys())
    
        print(location[loc])
    
        if loc == 0:
            break
        else:
            allexits = exits[loc].copy()
            allexits.update(namedexits[loc])
    
        direction = input("Available Exits are "+ availablexits).upper()
        if len(direction)>0:
            words = direction.split()
            for word in words:
                if word in vocabularyvar:
                    direction = vocabularyvar[word]
                    print(direction)
        print()
        #previously we used index ,since it it dictionary under dictionary
        if direction in allexits:
            loc = allexits[direction]
        else:
            print("You cannot go in that direction")