<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nitish Srivastava on Medium]]></title>
        <description><![CDATA[Stories by Nitish Srivastava on Medium]]></description>
        <link>https://medium.com/@ntsh-vicky?source=rss-daed194b94b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uQti0F5_xIYOkB_S</url>
            <title>Stories by Nitish Srivastava on Medium</title>
            <link>https://medium.com/@ntsh-vicky?source=rss-daed194b94b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:36:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ntsh-vicky/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Basic Of Python: Data Structure (Part 1)]]></title>
            <link>https://ntsh-vicky.medium.com/basic-of-python-data-structure-part-1-ea79260362cb?source=rss-daed194b94b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea79260362cb</guid>
            <category><![CDATA[python-dictionaries]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-data-structures]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-list]]></category>
            <dc:creator><![CDATA[Nitish Srivastava]]></dc:creator>
            <pubDate>Tue, 28 May 2024 01:44:12 GMT</pubDate>
            <atom:updated>2024-05-28T01:44:12.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nFBfdj1l_XiHUmth92HEw.png" /></figure><p>Data structure refers to the way data is organized, stored, and manipulated in a computer so that it can be efficiently accessed and used. Think of it as the framework or blueprint for managing data effectively. It involves techniques for organizing and managing data in a manner that allows for efficient operations like insertion, deletion, searching, and sorting.</p><p>In simpler terms, imagine you have a bunch of books. How you arrange them on your shelf, how you label them, and how you access them when needed, all constitute a kind of data structure. Similarly, in computer science, data structures are the mechanisms that enable efficient storage and retrieval of data in various applications.</p><p>In Python, you have access to a wide range of built-in data structures that you can use to organize and manipulate data efficiently. Some of the most commonly used data structures in Python include:</p><p><strong>1. Lists:</strong></p><ul><li>Lists are ordered collections of items, which can be of mixed types (integers, strings, etc.).</li><li>They are mutable, meaning you can change their content after creation.</li><li>Lists are indexed, meaning you can access elements by their position.</li><li>Lists are denoted by square brackets [ ].</li></ul><p><strong>2. Tuples:</strong></p><ul><li>Tuples are similar to lists, but they are immutable, meaning their content cannot be changed after creation.</li><li>They are often used to represent fixed collections of items, such as coordinates or settings.</li><li>Tuples are denoted by parentheses ( ).</li></ul><p><strong>3. Dictionaries:</strong></p><ul><li>Dictionaries are collections of key-value pairs, where each key is associated with a value.</li><li>They are unordered, meaning the order of items is not guaranteed.</li><li>Dictionaries are useful for storing and retrieving data based on a unique key.</li><li>They are denoted by curly braces { }.</li></ul><p><strong>4. Sets:</strong></p><ul><li>Sets are unordered collections of unique elements.</li><li>They are useful for tasks such as removing duplicates from a list or testing membership of an element.</li><li>Sets do not allow duplicate elements, so adding the same element multiple times has no effect.</li><li>Sets are denoted by curly braces { } or by using the set() function.</li></ul><p><strong>5. Arrays:</strong></p><ul><li>Arrays are collections of items of the same type.</li><li>They are provided by the array module in Python and offer efficient storage of homogeneous data types.</li><li>Arrays are useful for numerical computations and when memory efficiency is important.</li></ul><blockquote>import array<br>my_array = array.array(‘i’, [1, 2, 3, 4, 5])</blockquote><p><strong>6. Deque:</strong></p><ul><li>Deques (double-ended queues) are optimized for inserting and removing items from both ends of a collection.</li><li>They provide fast operations for adding and removing elements from either end.</li><li>Deques are provided by the collections module.</li></ul><blockquote>from collections import deque<br>my_deque = deque([1, 2, 3, 4, 5])</blockquote><p><strong>7. String:</strong></p><ul><li>Ordered collection of characters.</li><li>Immutable: Characters cannot be modified after creation.</li><li>Accessed by index.</li></ul><blockquote>my_string = ‘Hello, World!’</blockquote><p><strong>8. Bytes &amp; Byte Arrays:</strong></p><ul><li>Immutable and mutable sequences of bytes, respectively.</li><li>Used for storing binary data.</li></ul><blockquote>my_bytes = b’hello’<br>my_bytearray = bytearray(b’hello’)</blockquote><p><strong>7. Stack and Queue:</strong></p><ul><li>While Python does not have built-in classes for stacks and queues, you can easily implement them using lists.</li><li>Stacks follow the Last In, First Out (LIFO) principle, where the last element added is the first one to be removed.</li><li>Queues follow the First In, First Out (FIFO) principle, where the first element added is the first one to be removed.</li></ul><p>These data structures serve different purposes and have different characteristics, so choosing the right one depends on the specific requirements of your problem.</p><h4>Lists:</h4><p>Example:</p><blockquote>my_list = [1, 2, 3, 4, 5]</blockquote><p>Commonly used functions/methods:</p><ul><li>append(): Adds an element to the end of the list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2a5tsEgkL1T8T3lABNW4w.png" /><figcaption>Example of adding a new element and list in existing list</figcaption></figure><p>Check the line number 8, where i have appeneded a new List, it has added a new list inside existing list. here its, <em>[7,8,9]</em>, in the last index. Understand this, how <em>append()</em> works with list and check next another list based function <em>extend()</em> and understand difference.</p><ul><li>extend(): Extends the list by appending elements from another list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fM3OMFTEv6HXPwxVUkGkWQ.png" /><figcaption>Example of adding new elements from a list in existing list</figcaption></figure><p>Here, i am using same statement to add new list, but using <em>extend()</em> function. You can see, it has added 3 new values in 3 new index, where last time in append function it was one index contains a whole list value.</p><p>Check this, what happend if we will extend a list with an element (with primitive type data):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5OFRHPe4WBZeuEiU9NtqA.png" /><figcaption>Example of adding new element in existing list and getting error</figcaption></figure><p>In above code, i tried to extend one integer in existing list and it throws an error. Because, <em>extend()</em> function allow only to add another iterator function not primitive type.</p><ul><li>pop(): Removed and returns the last element of the list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkAwsmPercZPzYvR-Nh-Cg.png" /><figcaption>Example of pop()</figcaption></figure><ul><li>insert(): Inserts an element at a specified position.</li></ul><p>Syntex: insert(index where you have to add new element, the new value to insert)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Unp7GxyePesgUBUhotONA.png" /><figcaption>Example of how to insert an element in any index of the existing list</figcaption></figure><ul><li>remove(): Removes the first occurrence of a specified value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*FkfFt40EeO_Juw9-23gP1w.png" /><figcaption>Removed 20 from first occurrence (index 1) but not from index 4</figcaption></figure><p>If you want to remove all occurrance of 20 from list, need to use below defined different way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWavWF1pXbHHPvtqJCv7kw.png" /><figcaption>Example for how to remove an element from multiple occurrance</figcaption></figure><ul><li>index(): Returns the index of the first occurrence of a specified value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*l2B3CMh99Yyx7QwnXHg0aQ.png" /><figcaption>Example of index()</figcaption></figure><p>You can see on above example index() function returned only first occurrence of value 20, though value 20 is also exists on index 4.</p><p>You can use loop to read indexs of multiple occurrance of specified elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOXvln3eIUMD68IuEsO9lA.png" /><figcaption>Example to read all index of soecified value</figcaption></figure><ul><li>count(): Returns the number of occurrences of a specified value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*bZPltfsMpvFvCU6ZagDeOQ.png" /><figcaption>Example of count nos of occurrence of an element in list</figcaption></figure><ul><li>Other calculations in list, like add two list, multiply a list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*h50F7I0qmLs9FISAVBnkhg.png" /><figcaption>Calculations in List</figcaption></figure><p>What you can’t do with list?</p><ol><li>You can’t add a list with primitive datatypes, like <em>my_list + 4.</em></li><li>You can’t multiply two list directly, like my_list1 * my_list2.</li><li>You can’t directly devide and subtract a list with any other list or any primitive datatype.</li></ol><h4>Tuples:</h4><p>Example:</p><blockquote>my_tuple = (1, 2, 3, 4, 5)</blockquote><p>Tuples’s approx all functions are same as List, but because <strong>Tuples are immutable (unchangable)</strong>, it doesn’t have functions to update an existing Tuples, like <em>append()</em>, <em>extend()</em> or <em>remove()</em>. But <em>count()</em> and <em>index()</em> has same logic.</p><ul><li>Concatination and repetition are allowed in tuples.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*hjZMAg2BOZmHSzpcABpLbg.png" /><figcaption>Example of concatination and repetition of tuples</figcaption></figure><ul><li>Packing and Unpacking a List and Tuples</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*-9CW7SFYB2ScuCLqRc6cdg.png" /><figcaption>Example of packing &amp; uncpacking a List or Tuples</figcaption></figure><h4><strong>Dictionaries</strong>:</h4><p>Example:</p><blockquote>my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}</blockquote><p>How to add new items in an existing dictionary?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*90bs8wOeTVj6sTdyjY-5Fg.png" /><figcaption>Example of how to add item on an dictionary</figcaption></figure><p>Commonly used functions/methods:</p><ul><li>get(): Returns the value associated with the specified key. If the key is not found, it returns a default value (None by default).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypTxJEBvriMfvk7tO2yLTg.png" /></figure><p>From above example you can see how to retrieve the value from a specified key in different way and how to return a default value if key does not exists.</p><ul><li>keys(): Returns a view object (dict_keys class) that displays a list of all the keys in the dictionary.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*uEk9F1NSVXdP-j2XZaf8MQ.png" /><figcaption>Reading list of keys from dictionary</figcaption></figure><ul><li>values(): Returns a view object (dict_values class) that displays a list of all the values in the dictionary.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*pQV9XMHFYkFAXgbhjBT0Og.png" /><figcaption>Reading list of values from dictionary</figcaption></figure><ul><li>items(): Returns a view object that displays a list of all key-value pairs in the dictionary as tuples.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*I0Th-MNOhgLjJSdqYyes4Q.png" /><figcaption>Example of items()</figcaption></figure><p>Mostly when you program and need to read all key and value for any logical requirements, you can iterate items and read key and value both, like below eaxmple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adkLCmXf77nIloU18jcJxw.png" /><figcaption>Example of iterate dictionary using for loop</figcaption></figure><ul><li>pop(): Removes the item with the specified key from the dictionary and returns its value. Raises a KeyError if the key is not found.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5I-F-3VQj1RSuj-8XrGZsA.png" /><figcaption>Example of pop a key and return value</figcaption></figure><p>In above example, ypu can see, in line number 3, i have asked to pop key ‘a’ from my_dict. The returned value ret is 1, which is value of key ‘a’. And after pop when i printed my_dict its showing updated value, mean after pop you can’t use key ‘a’ from my_dict. And another example, what happens when trying to delete some key doesnot exists.</p><ul><li>popitem(): Removes and returns the last key-value pair inserted into the dictionary as a tuple. Raises a KeyError if the dictionary is empty.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*caAQxDAqvQKBYzjlXvVZAg.png" /><figcaption>popitem() returns the key and value of the removed item and remove the last key-value pair item</figcaption></figure><ul><li>update(): Updates the dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAI6ztKxGQ4xHpwvymUUjA.png" /><figcaption>Updated my_dict with new key-value pair and added another dictionary my_dict2 on it.</figcaption></figure><ul><li>clear(): Removes all items from the dictionary.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmJLjh2wa50zdWRlXSaqgA.png" /><figcaption>Example of clear all items from dictionary</figcaption></figure><h4>Set:</h4><p>Example:</p><blockquote>my_set = {1,2,3} or set([1,2,3])</blockquote><p>Sets in Python are unordered collections of unique elements. Here are some of the most commonly used basic functions and methods for working with sets:</p><ul><li>add(): Adds an element to the set.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*lV0kSvxS-PtU4MwW2T2hQQ.png" /></figure><ul><li>remove(): Removes a specified element from the set. Raises a KeyError if the element is not present.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*augZfXy0MNjDzOsTvSm9QQ.png" /></figure><ul><li>discard(): Removes a specified element from the set if it is present, but does not raise an error if the element is not present.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0N4pHcqPEY--uooa_OmPw.png" /></figure><ul><li>clear(): Removes all elements from the set.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTUqP2XLBJwsMdNjDe9zFw.png" /></figure><ul><li>copy(): Returns a shallow copy of the set.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*wEnyYLxqjmdvO3ZfE8jVyw.png" /></figure><p>What is difference bewteen new_set = my_set.copy() and new_set = my_set?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QI6_YNc2FHHq4iesKC2-vQ.png" /><figcaption>Example of difference between shallow copy and reference copy</figcaption></figure><p>Some Set related operations:</p><ul><li>union(): Returns a new set containing all unique elements from both sets.</li><li>intersection(): Returns a new set containing elements that are common to both sets.</li><li>difference(): Returns a new set containing elements that are present in the first set but not in the second set.</li><li>symmetric_difference(): Returns a new set containing elements that are present in either set, but not in both.</li></ul><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1W-byTSz6V6sKooag9nXsA.png" /><figcaption>Some Set related operations</figcaption></figure><h3>Slicing List &amp; Tuples</h3><p>Slicing is a technique used to extract a portion of a sequence (like lists, tuples, and strings) in Python. Lists and tuples support slicing using the <strong><em>list[start:stop:step]</em></strong> syntax, where <em>start</em>, <em>stop</em> and <em>step</em> are optional parameters.</p><p>Sets and dictionaries do not support slicing directly, but you can achieve similar functionality using other techniques like iteration or comprehension.</p><p>Example of slicing on list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBHNoMmu_VqC03zmtVO2lw.png" /></figure><p>You can use same for the tuples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJrqnpfNvswYI6fmyC0Sbg.png" /></figure><p>Here, need to understand. When using positive value in slicing, its start from index 0. As line number 5, 1:4 mean - read data from index number 1 to index number 3, exclude index 4. You do not have to read the stop index part. If there is no number mean start index is 0. Like line number 13, ie. [:3] — it is saying, get element from starting (index 0) to index 2, exclude 3. If it is [3:] — Mean, get element from index 3 to end, mean all. It will not exclude the last one.</p><p>Now, What is negative slicing. Negative slicing start from -1, is in reverse order started from last index. Where last index is -1. So if it is [-3:-1], mean get element from third last index to second last index, exclude last index. Based on above example line number 9, -3 index of my_list array has value ‘3’ and second last index which is -2 has 4, by excluding given -1. So it will return [3,4].</p><p>If you have to reverse a list, tuples or string, just put -1 in step portion.</p><blockquote>Example-: my_list[::-1]</blockquote><p>What will not return any data?</p><ol><li>If slicing with same index — my_list[1:1] or my_list[-2:-2]</li><li>if slicing with reverse positive index — my_list[2:1]</li><li>if slicing negative as forward indexing — my_list[-1:-2]</li></ol><p>To understand more slicing, practice more.</p><h3><strong>Its not end</strong></h3><p>List, Tuples, Dict and Set are the basic data structure of Python. I have shared all basic operation here with you.</p><p>But there is more.</p><p><strong>Advance Data Structure</strong>, what i will share with you in next article (Part 2). It is already very long article so that.</p><p>You wanna learn more ? Check the references.</p><ul><li><a href="https://realpython.com/python-data-structures/">Common Python Data Structures (Guide) - Real Python</a></li><li><a href="https://ioflood.com/blog/python-data-structures/">Python Data Structures | Reference Guide</a></li><li><a href="https://www.geeksforgeeks.org/python-data-structures/">Python Data Structures - GeeksforGeeks</a></li><li><a href="https://docs.python.org/3/tutorial/datastructures.html">5. Data Structures</a></li></ul><p>Happy coding! 🚀👩‍💻 &amp; Sorry for any Grammarly mistakes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea79260362cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Of Python — Date & Time]]></title>
            <link>https://medium.com/analytics-vidhya/basic-of-python-date-time-91349829971b?source=rss-daed194b94b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/91349829971b</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-datetime]]></category>
            <dc:creator><![CDATA[Nitish Srivastava]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 17:53:45 GMT</pubDate>
            <atom:updated>2023-11-15T17:57:16.829Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basic of Python — Date &amp; Time</h3><p>As a software engineer, for me date and time is one of basic requirements I am dealing with in my regular projects. You can’t believe, many time I had faced issue on timezone based calculation, what I wrote on my system was different output on server. Okay, at least after experience and while facing many issues I learned how to solve it. So, today I am gonna write about “datetime” module and related problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2zcPuuiGw499YdG4s2SQw.png" /><figcaption>Generated from Midjourney</figcaption></figure><p>Python’s datetime module is a lifesaver in such scenarios. It offers classes for manipulating dates and times in both simple and complex ways. We will check Date &amp; Time opertaions with some cases.</p><p>Like other libraries you need to import datetime into your project using “import datetime”.</p><blockquote>If you are importing datetime library as <strong>“import datetime”,</strong> then you need to write <strong>“datetime.datetime.now()”</strong> to get current datetime.</blockquote><blockquote>If you are importing datetime like <strong>“from datetime import datetime”</strong>, then you need to write <strong>“datetime.now()”</strong> only to get current datetime.</blockquote><h3><strong>There is some basic classes of datetime:</strong></h3><p><strong>date:</strong> Represents a date (year, month, day).</p><p><strong>time:</strong> Time independent of the day (hour, minute, second, microsecond).</p><p><strong>datetime:</strong> Combination of date and time.</p><p><strong>timedelta:</strong> Represents a duration of time.</p><h3><strong>Let’s check some datetime opertaions:</strong></h3><p><strong><em>1. Get current datetime:</em></strong></p><p>To get the current datetime from datetime package you need to use <strong><em>now()</em></strong> function, like “<strong><em>datetime.now()”.</em></strong></p><p><strong><em>2. Datetime formats:</em></strong></p><p>First some keys you need to understand. Some basic format of datetime is –</p><p>a) %Y — It defines full 4 digit year like 2023</p><p>b) %y — Small y, It defines 2 digit of year format like 23</p><p>c) %m — it defines Month in single zero padded decimal like for January-01, same December — 12</p><p>d) %b — Abbreviated month name. Like Jan, Feb, Mar etc.</p><p>e) %B — Full month name like January, February, March etc.</p><p>f) %-m — Month number without zero padding</p><p>g) %d — Day of the month as zero-padding like 01, 02 … 29, 30 etc.</p><p>h) %-d — Day of month without zero-padding like 1, 2 … 29, 30 etc.</p><p>i) %j — Define day of the year , 001 to 365 (366 in leap year)</p><p>j) %a — Abbreviated week days like Mon, Tue, Wed etc.</p><p>k) %A — Full weekdays like Monday, Tuesday, Wednesday etc..</p><p>l) %H — 24 Hour clock’s Hour format like 00 to 23</p><p>m) %I — 12 Hour clock’s Hour format like 01 to 12</p><p>n) %M — capital M, define zero-padded minutes like 00, 01 .. 59</p><p>o) %S — Second as zero-padded decimal number like 00, 01 .. 59</p><p>p) %p — Locale’s equivalent of either AM or PM</p><p>3. <strong><em>Convert Datetime to String Format:</em></strong></p><p>You can use “strftime()” function to convert datetime into string format as above discuss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sUhZvn1ozUO0gGuK2HbqQ.png" /><figcaption>Converting datetime object into string format</figcaption></figure><p>This is usually helpful, when you have to show datetime into UI, so you will need to convert date into your input required format.</p><p><strong><em>4. Convert String Date &amp; Time value into datetime type:</em></strong></p><p>You can use “strptime” to convert string datetime value to datetime object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*IUF103vEdFnRRSi3Qam03Q.png" /><figcaption>Convert String Date into datetime object</figcaption></figure><p>This is usually used, when you have to use string date and time value as datetime object, like for calculation .</p><p>Now think, you have date and time in separate input and you want to save combination of this datetime into datetime object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*8RoRWsi4NWxZCuZLQHI4_w.png" /><figcaption>Convert string format of date &amp; time into datetime object</figcaption></figure><p>So, there is another way to combine date and time and convert into datetime object using combine function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*q9Tf51HiY5wl2tbNQLu0zw.png" /><figcaption>Convert string format of date &amp; time into datetime object using combine function</figcaption></figure><p><strong><em>5. Datetime Arithmetic Operations:</em></strong></p><p>When you must add or minus on datetime. Like you want to know what the day is after 10 days from now, or what is the date after 260 minutes from now etc. You can use <strong>“timedelta”</strong> for arithmetic operations for datetime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*etDAuAaULpQ5Ci6ZJ-cm_g.png" /><figcaption>Example of add, subtract on datetime object</figcaption></figure><p><strong><em>6. Comparision on 2 different datetime objects:</em></strong></p><p>You can use comparison operators like (&lt;, &gt;, ==, !=, &lt;=, &gt;=) to compare two days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*QW_UKssojbkX8k4RQgotZg.png" /><figcaption>Example of comparision between 2 days</figcaption></figure><p><strong><em>7. Split Date &amp; Time from datetime object:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*QvFOF910x5gd_9p0nlgrkA.png" /><figcaption>Example of extract date &amp; time from a datetime object</figcaption></figure><p><strong><em>8. Extract day, month, year, hour, minute, second from datetime object:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*tpjpxbodvTq4XVHfp9qUdw.png" /><figcaption>Example of extract year, month, day, hour, minute &amp; second from datetime object</figcaption></figure><p><strong><em>9. Get epoch time from datetime object:</em></strong></p><p>You can use the timestamp() method. The Unix timestamp represents the number of seconds that have elapsed since January 1, 1970 (UTC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*IusHbFoB60dY62RarMEPeQ.png" /><figcaption>Example of getting epoch time value from datetime object</figcaption></figure><p>This code will convert the specified datetime object into the corresponding Unix timestamp. Note that the <strong><em>timestamp()</em></strong> method returns the timestamp as a floating-point number. If you need an integer value (which is common for Unix timestamps), you can convert it using <strong><em>“int(epoch_time)”</em></strong>.</p><p><strong><em>10. Convert epoch time into datetime:</em></strong></p><p><em>epoch_time</em> is the Unix timestamp which represents the number of seconds since <strong>January 1, 1970 (UTC)</strong>. The <strong><em>fromtimestamp()</em></strong> method is used to convert this timestamp into a datetime object, which you can then use in your program as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*gzD_VNlxqEmpXLxjiHbSaA.png" /><figcaption>Converting epoch time into datetime object</figcaption></figure><p><strong><em>11. Get First and Last date of this week:</em></strong></p><p>To find the first (Monday) and last (Sunday) dates of the current week in Python, you can use the datetime module. The process involves:</p><p>1. Finding today’s date.</p><p>2. Determining the weekday of today’s date.</p><p>3. Calculating the difference to get to Monday (the start of the week).</p><p>4. Adding the necessary days to get to Sunday (the end of the week).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*J9i9CSvzwF9ZnErgm0c5qw.png" /><figcaption>Example of getting First &amp; Last day of the week</figcaption></figure><p><strong><em>12. Get Last day of the month using calendar library:</em></strong></p><p>To find the last day of a given month in Python, you can use the <em>calendar</em> module along with the datetime module. The <strong><em>calendar.monthrange()</em></strong> function provides an easy way to determine the number of days in a specific month of a specific year. The last day of the month is essentially the number of days in that month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*HQHknPw6DpQhiN_HvhDG1A.png" /><figcaption>find the last day of a specific month and year</figcaption></figure><p>This code will output the last day of July 2023. You can change the year and month variables to find the last day of any other month.</p><p><strong><em>13. Check if given year is Leap or not:</em></strong></p><p>To get if year is leap or not you can use calendar module, which provides a function named <strong><em>“isleap()”</em></strong> to get if given year is leap year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*DGry1ndzoEeraVYk4g9w8w.png" /><figcaption>Example of getting if given year is leap year</figcaption></figure><p>If you have datetime object value and you want to get year from it, you can use <strong><em>datetime_obj.year</em></strong>.</p><p><strong><em>14. Get all date from a given month &amp; year:</em></strong></p><p>Better I will suggest to use a generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Xac2riQjtJz0Zm4rhSZJ7Q.png" /><figcaption>generating all days in given month of an year using generators.</figcaption></figure><p><strong><em>15. Get the dates between given two date using generator:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*0yBdzKi30rbgEv2Z8PWyYw.png" /><figcaption><em>Get the dates between given two date using generator</em></figcaption></figure><h3>Working with Time Zones</h3><p>You might need to handle time zones in your applications, like Event based application, where you have to show timing based on different places on different country and timezone or social media website where you want to show users post and comment update based on user timezone availability.</p><p>For this, use the <strong>pytz</strong> library, which works well with datetime.</p><p>You need to install <strong>pytz</strong> library using —<strong><em> “pip install pytz”</em></strong></p><blockquote>You need to be careful when handling timezone. Now think, you have a server, which timezone is UTC and you have to show your social media post timing for Dubai users based on Dubai timezone and Kolkata user based on Kolkata, India timezone, first step will be make your UTC timezone as aware time. Check below examples.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*KfFMEqC0BnTfXYO_iGYxNA.png" /><figcaption>Getting same time of Kolkata &amp; Dubai</figcaption></figure><p><strong>pytz</strong> takes care of <strong>daylight-saving time (DST)</strong> automatically. However, neither India nor the UAE observe DST, so you don’t have to worry about it in this specific case.</p><ol><li><strong><em>UTC Offset on different timezone:</em></strong></li></ol><p>A UTC offset is the difference in hours and minutes from UTC (Coordinated Universal Time). Negative offsets are west of the Prime Meridian (like in the Americas), and positive offsets are east (like in Asia and Europe).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*1ziT6TwWj5j7-xKze5xnpQ.png" /><figcaption>Example of converting UTC timezone into different timezone</figcaption></figure><p><strong><em>2. Get epoch time for a specific timezone</em></strong></p><p>To get the epoch time (Unix timestamp) based on the time in a specific timezone, you’ll first convert the local time to a UTC datetime, and then calculate the epoch time from that. The pytz library is very useful for handling time zones in Python. Here’s how you can do it:</p><p>Let’s say you want to get the epoch time for a specific date and time in the <em>‘Asia/Kolkata’</em> timezone. You need the below step:</p><p>1. <strong>Create a timezone-aware datetime object</strong> in the desired timezone.</p><p>2. <strong>Convert it to UTC</strong>, as epoch time is based on UTC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*GrGgstO9FxoBGGw6Wh_nDw.png" /><figcaption>Get the epoch time from the UTC datetime</figcaption></figure><p>This code snippet will give you the Unix timestamp corresponding to November 15, 2023, 9:00 AM in Kolkata time. You can change the timezone, date, and time as per your requirement.</p><h3><strong>Aware &amp; Naïve</strong></h3><p>In Python’s <strong>datetime</strong> module, the terms <strong><em>“aware”</em></strong> and <strong><em>“naive”</em></strong> refer to whether a datetime object includes timezone information or not.</p><p><strong>a)</strong> <strong>Naive Datetime Objects</strong></p><p>· <strong>Naive datetime objects</strong> do not contain information about the time zone and daylight saving time (DST).</p><p>· They are easy to understand and work with but are less suited for real-world applications where time zone context is important.</p><p>· For example, <strong>datetime.datetime(2023, 11, 15, 9, 0)</strong> is a naive datetime object; it represents a local time but doesn’t specify the time zone it belongs to.</p><p><strong>b)</strong> <strong>Aware Datetime Objects</strong></p><p>· <strong>Aware datetime objects</strong> have information about the time zone and daylight saving time.</p><p>· They are essential for time zone conversions and accurately representing time in a globally understood format.</p><p>· For instance, <strong>datetime.datetime(2023, 11, 15, 9, 0, tzinfo=pytz.timezone(‘Asia/Kolkata’))</strong> is an aware datetime object; it not only represents the local time but also specifies that it is in the ‘Asia/Kolkata’ time zone.</p><p><strong>Why Does This Matter?</strong></p><p>· <strong>Comparisons and Operations</strong>: You can only compare or perform operations on datetime objects that are both naive or both aware. Mixing the two types will result in a <strong>TypeError</strong>.</p><p>· <strong>Real-World Applications</strong>: When building applications that handle events across different time zones (like scheduling meetings or flights), you must use aware datetime objects to avoid errors and confusion.</p><p>· <strong>Storing and Displaying Time</strong>: It’s a good practice to store datetime information in UTC and convert to local time zones for display. This conversion requires aware datetime objects.</p><p>In summary, understanding the distinction between naive and aware datetime objects is crucial for dealing with time accurately in software development, especially in applications that span multiple time zones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*shzp75HsxHnWJ7Jmi9KQMg.png" /><figcaption>Example to understand error occured from naive &amp; aware datetime</figcaption></figure><p><strong>How to solve “Error: can’t compare offset-naive and offset-aware datetimes”?</strong></p><p>To resolve this error, you need to make sure that both datetime objects are either naive or aware. Here’s how you can handle this:</p><ol><li><strong>Converting an Aware Datetime to Naive</strong></li></ol><p>If you want to ignore timezones and just compare the dates and times, you can convert an aware datetime to a naive one by removing its timezone information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*fy_K9ySEEggFySzILf0V7Q.png" /><figcaption>Converting an Aware Datetime to Naive</figcaption></figure><p><strong>2. Converting a Naive Datetime to Aware</strong></p><p>Alternatively, if you need to compare the datetimes with time zone awareness, you can convert a naive datetime to an aware one by adding a timezone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*5hTtb6O0_Z4vyRd_btzvxA.png" /><figcaption>Converting a Naive Datetime to Aware datetime</figcaption></figure><p><strong>Standardizing on One Type</strong></p><p>To compare or perform operations on two datetime objects, ensure both are either naive or aware. If you’re working across time zones, it’s often best to work with aware datetime objects.</p><p>Here’s an example where we ensure both datetimes are aware before comparing them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*49tckPyIufrMevUlq4LNbA.png" /><figcaption>Comparing Two Datetimes</figcaption></figure><h3><strong>Basic datetime related error users faces</strong></h3><p>Working with dates and times in Python, particularly using the datetime module, can sometimes be challenging, and developers often encounter certain common errors or issues. Here are some of the most common ones:</p><p><strong>1. Time Zone Confusion (Naive vs. Aware Datetimes)</strong></p><p>A frequent source of bugs is the confusion between naive (no time zone information) and aware (includes time zone information) datetime objects. When you mix these two types, you can encounter errors like “can’t compare offset-naive and offset-aware datetimes.”</p><p><strong>Solution</strong>: Always be clear about whether a datetime object is naive or aware. Convert naive datetime objects to aware ones when time zone information is relevant. Use libraries like <strong>pytz</strong> or the newer <strong>zoneinfo</strong> module (Python 3.9+) for handling time zones.</p><p><strong>2. Incorrect Format Strings</strong></p><p>When converting datetime objects to strings or vice versa (especially using strftime and strptime), using the wrong format codes can cause errors or unexpected results. It’s crucial to correctly use format codes like %Y, %m, %d, %H, %M, %S, etc.</p><p><strong>Solution</strong>: Familiarize yourself with Python’s datetime formatting directives. Test your <strong>strftime</strong> and <strong>strptime</strong> functions thoroughly to ensure they behave as expected.</p><p><strong>3. Daylight Saving Time (DST) Errors</strong></p><p>Handling daylight saving time transitions can be tricky. Errors often occur when converting times across DST boundaries, which can lead to incorrect times or even errors if a specific time does not exist (or exists twice) due to a DST shift.</p><p><strong>Solution</strong>: Utilize timezone-aware datetime objects. Libraries like <strong>pytz</strong> and <strong>zoneinfo</strong> handle DST transitions properly. Be cautious with manual calculations around DST transitions.</p><p><strong>4. Leap Year Errors</strong></p><p>Another common issue is failing to account for leap years when performing date calculations manually. This can lead to incorrect date calculations, especially in February.</p><p><strong>Solution</strong>: Rely on Python’s <strong>datetime</strong> and <strong>calendar</strong> modules for date calculations, as they correctly handle leap years. Avoid manual date calculations when possible.</p><p><strong>5. Time Zone Offset Errors</strong></p><p>When working with time zone offsets, particularly with custom calculations, errors can arise from not correctly handling positive and negative offsets, or failing to account for time zones that do not align with the standard one-hour offset increments (e.g., Indian Standard Time is UTC+5:30).</p><p><strong>Solution</strong>: Use established libraries (<strong>pytz</strong>, <strong>zoneinfo</strong>) to handle timezone conversions. These libraries take care of odd time zone offsets and daylight saving time adjustments.</p><p><strong>6. Deprecation of <em>pytz</em> Module</strong></p><p>While pytz has been a popular choice for handling time zones, Python 3.9 introduced significant improvements in the built-in zoneinfo module for time zone support. Relying on outdated or deprecated methods can lead to compatibility issues.</p><p><strong>Solution</strong>: For Python 3.9 and later, prefer the built-in <strong>zoneinfo</strong> module for time zone handling. If you’re using an older version of Python, <strong>pytz</strong> is still a valid choice.</p><p><strong>7. Misunderstanding UTC Conversions</strong></p><p>Mistakes often occur when converting to and from UTC, especially if the developer assumes that the local system time is in UTC or incorrectly handles the conversion, leading to off-by-several-hours errors.</p><p><strong>Solution</strong>: Standardize on storing and manipulating dates in UTC, especially in a server or database context. Only convert to local time zones for display purposes.</p><p><strong>8. Ambiguity in Date Formatting</strong></p><p>Using ambiguous date formats (like MM/DD/YYYY vs DD/MM/YYYY) without clear context can lead to misunderstandings and errors in date interpretation.</p><p><strong>Solution</strong>: Use ISO 8601 format (<strong>YYYY-MM-DD</strong>) for unambiguous date representation, especially in internationalized applications and data interchange. Clearly document the date format if a non-standard format is used.</p><blockquote>To avoid these errors, it’s important to have a clear understanding of how datetime works, especially in terms of time zones, and to rigorously test date and time handling code, particularly around edge cases like DST changes and leap years.</blockquote><h3><strong>Best Practices</strong></h3><p>· Always store datetime in UTC, especially in server-side applications.</p><p>· Convert to the local time zone only when presenting dates and times to the user.</p><p>· Be mindful of daylight saving time changes if you’re dealing with time zones that observe DST.</p><p>· Always handle time zones and daylight saving times properly, especially in web applications.</p><p>· Use isoformat for a standard date-time representation when storing or transferring data.</p><p>· Be aware of the datetime limitations, like handling very large dates or very precise time measurements.</p><p>· Unit Testing: Write unit tests for your date and time handling code, especially testing edge cases like leap years, DST transitions, and time zone conversions.</p><p>· Code Review: Have your datetime handling code reviewed by peers, as they might catch issues you’ve missed.</p><p>· Continuous Learning: Keep up to date with best practices and changes in Python’s datetime handling, as the language and its libraries evolve.</p><h3><strong>Conclusion</strong></h3><p><strong>datetime</strong> in Python is a robust module, crucial for handling dates and times in your software projects. With its rich set of functionalities, it makes date and time manipulations a breeze. Always keep exploring its documentation for more in-depth details and updates.</p><p>Remember, date and time handling can get tricky, especially with time zones and daylight saving times. But with <strong>datetime</strong> and a bit of practice, you’ll be able to handle these challenges with ease.</p><h3>Some References:</h3><p>Its better, search more &amp; read more to learn more….</p><ul><li><a href="https://docs.python.org/3/library/datetime.html">datetime - Basic date and time types</a></li><li><a href="https://www.programiz.com/python-programming/datetime">Python datetime</a></li><li><a href="https://www.geeksforgeeks.org/python-datetime-module/?ref=lbp">Python datetime module - GeeksforGeeks</a></li><li><a href="https://realpython.com/python-datetime/">Using Python datetime to Work With Dates and Times - Real Python</a></li></ul><p>Happy coding! 🚀👩‍💻 &amp; Sorry for any Grammarly mistakes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91349829971b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/basic-of-python-date-time-91349829971b">Basic Of Python — Date &amp; Time</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic of Python — Thread]]></title>
            <link>https://medium.com/analytics-vidhya/basic-of-python-thread-fff0ed0ef1fe?source=rss-daed194b94b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fff0ed0ef1fe</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-thread]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[threading]]></category>
            <dc:creator><![CDATA[Nitish Srivastava]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 00:24:39 GMT</pubDate>
            <atom:updated>2023-11-15T15:12:30.880Z</atom:updated>
            <content:encoded><![CDATA[<p>Before starting this topic, You need to understand what is Thread and what is process. I am not much theoretical brain person. So, understand like this, A program like Microsoft word is a process and inside this word program, running subtask like <em>searching a text, using find and replace, spelling mistake, grammar mistake</em> is thread. A process you can understand as an independent &amp; active program and a thread is a lightweight process and a part of main process which share memory with other thread and use same resources of process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*0f6xZQEoyYkkQ6e_WhMy6A.png" /><figcaption>Image from Window Task Manager</figcaption></figure><p>If you are a window user, you can check in Task Manager, as highlighted in above image, there is process 259 and Threads is 3475 (It will be different on you). Now you open a program like Ms Word or photoshop then search, user find and replace, open other dialogue box and then you can see there is some changes in this panel’s process and thread value. Same close that program and check the value.</p><p>There is another word Handle with value 115228, is total active handle inside process. A Handle is an integer value (in window its represent as HWND for window and HMODULE for modules) that identifies a process in window. It can be thread called thread handle, files and other resources. Sometimes you might be trying to delete some file in window and it is showing an error message that file is in use, even you are seeing as its closed, just because you do not have released it yet.</p><p>Now, come to thread again. If a program can run more than one thread simultaneously, that called <strong>multithreaded program</strong>. There is a bad news; Due to <strong>Global Interpreter Lock (GIL)</strong> in python, only one thread can execute once. So for multiprocessing work, you can use <strong>multiprocessing or PoolExecutor module.</strong> See, it also run only one code at once, but python thread modules make it running very fast and in between very small timing, so you will feel like code is running simultaneously.</p><h3>So, where you can use thread?</h3><ol><li>When you have to execute multiple code at same time, like You have list of URL to scrap and download images from there, you can use ThreadPoolExecutor.</li><li>If you have to upload multiple files</li><li>If you are working on image processing to process thousand of images on your machine learning project. Instead of one by one, you can use ThreadPoolExecutor. It will save your time.</li><li>Thread you can also use to execute some program in background without affecting next step or waiting for long time. Think like you have to process a video on your AI/ML project, which can have 100th of frame to process. If you don’t want to wait, just run this image processing code on background using Threading and to make it fast use ThreadPoolExecutor and same time return message with your api like <em>we will notify you when process done.</em></li><li>You can use in a project, like voice assitance based program with face recognition and other object recognition, NLP at same time. Like, JARVIS.</li><li>In Window Toolkit kind project, its normal.</li></ol><h3>Lets start some basic thread life cycle and implementation:</h3><p>1. How to start a thread</p><p>2. What is Daemon thread</p><p>3. What is join() function, and what happened in thread when we use it and when we donot use it.</p><p>4. How to pass different parameters in thread</p><p>5. ThreadPoolExecutor</p><p>6. mutiprocessing</p><p>7. Thread Class</p><p>8. What is Race Condition &amp; Lock</p><p>9. Deadlock</p><p>10. Producer-Consumer</p><h4><strong>How to start a thread:</strong></h4><p>To start a separate thread, you need to call <strong><em>start()</em></strong> function from <strong><em>Thread</em></strong> module. This <strong><em>Thread</em></strong> module you can find in the python’s standard library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*JkwYrnisILHArz6y8vUqUw.png" /><figcaption>An example of Python object initialization</figcaption></figure><p>In the above example you can see, I have created two function, <strong>func1() </strong>and <strong>func2()</strong>.</p><p>In line number 1, I have imported threading library, and then in line number 15 and 16 I have initialize two thread with object name th1 and th2. To initialize thread, I am using Thread class from <strong>threading</strong>, and passing</p><p>here, passing <strong>func1 and func2</strong> function in each thread through target parameter. This is how you can initialize a thread and call thread function.</p><p>Now in line number 19 and 21 I am starting both thread. <strong>.start()</strong> function execute thread. <em>Mostly you can see same function name in every programming language.</em> I have worked on .Net, Java, Python, c++; all are same. Some other functions, like join , run , sleep are same in every programming language, same meaning and use, just different way of writing.</p><h4><strong>What is Daemon thread</strong></h4><p>A <strong>daemon thread</strong> in Python (Or any programming language) is a type of thread that <strong><em>runs in the background and does not prevent the program (or main thread) from exiting</em></strong>. In other words, daemon thread does not block main thread to exiting and continue run in the background.</p><p><strong>Below is an example of Non-Daemon thread:-</strong></p><p>You can see I have sleep main thread for 5 second but still background thread is running and after completion of main thread , still background thread is running till completion and it’s preventing application to exit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*GsoG9lGsa4mNoYP1GQw32Q.png" /><figcaption>Example of Non-daemon Thread</figcaption></figure><p><strong>Lets try with Daemon thread:-</strong></p><p>You can make any thread daemon after passing <strong>“daemon”</strong> parameter as <strong>True</strong> or with thread <strong>obj .daemon = True</strong>. I have written both in below example but one is commented (In line 13).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*iGOFqUm4UYVt-jIH44m1iw.png" /><figcaption>An example to explain Daemon Thread</figcaption></figure><p>You can see in above example, running background thread has not prevented main thread to exit.</p><p>When it Is useful. Think you are running a background subprogram/ thread , example Garbage collector. You can run a thread to clear unwanted memory in background till your application is opened. When you close the application, this running background program should not affect this main thread to exit and still it will be running till clean the existing memories.</p><p>Other Example like ,</p><p>You can see in above example, running background thread has not prevented main thread to exit.</p><p>When it Is useful. Think you are running a background subprogram/ thread , example Garbage collector. You can run a thread to clear unwanted memory in background till your application is opened. When you close the application, this running background program should not affect this main thread to exit and still it will be running till clean the existing memories.</p><p>Other Example like ,</p><p>1. Log file monitoring: If you need to monitor a log file and perform some action whenever a certain pattern is detected in the log, you can create a daemon thread to continuously monitor the log file in the background while the main thread of the program performs other tasks. This way, the program can exit cleanly even if the log monitoring thread is still running.</p><p>2. Periodic task execution: If you have a task that needs to be executed periodically, you can create a daemon thread to perform the task on a schedule. This way, the task will continue to run even if the main thread of the program has completed.</p><p>3. You can also use when you have to run big process, like in api, if you have to execute image processing on so many files which can take more time. You can use daemon thread to handle that process and return temporary response to user and later after image processing will complete you can send another result based response in user callback URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*tWt179u_tkIOWXEZLfXO9w.png" /><figcaption>Example of daemon thread to explain how to run any code in background</figcaption></figure><p>Above I have created an api, where when you call root url, it will execute <strong>background_task()</strong> function in background without affecting user response and later returns the actual result to user callback URL. <em>It just an example.</em></p><p>It’s important to note that any non-daemon threads must complete their work before the program can exit. So, if you have any threads that are not daemon threads, you should make sure they are joined before the program exits.</p><h4><strong>What is join() function, and what happened in thread when we use it and when we donot use it.</strong></h4><p>The join() function is a method of a Thread object in Python, that blocks the calling of thread until the thread on which <strong>join()</strong> is called has completed its execution.</p><p>When a thread is started, the parent thread (the thread that started the new thread) continues executing independently of the child thread. If the parent thread finishes before the child thread, the child thread will continue running until it completes its work. In this case, the program may exit before the child thread has finished running, which can cause unexpected behavior.</p><p>The <strong>join()</strong> function ensures that the parent thread waits for the child thread to complete before it continues execution. This is useful for ensuring that all threads have completed their work before the program exits.</p><p>When you call <strong>join()</strong> on a thread, the calling thread blocks until the thread on which <strong>join()</strong> was called has completed its work. If the thread has already completed its work, the <strong>join()</strong> function returns immediately.</p><p>Here’s an example of <strong><em>thread without using join()</em></strong> function in Python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*wARzZLFxj_Bfk3UuIDmlbw.png" /><figcaption>Example of without join() function</figcaption></figure><p>In above example, Parent thread has completed even child thread not.</p><p>Here is <strong><em>same example with using join()</em></strong>:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*scSGHAYmV-l667YhHDy3QQ.png" /><figcaption>Example with join() function</figcaption></figure><p>In above example, first child thread completed then only parent thread complete.</p><h4><strong>How to pass different parameters in thread</strong></h4><p>You can also pass the parameter to thread function. Below is an example of download and save NFT data using thread. For example I am using Opensea API to download Azuki — Goerli NFTs and store locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLA4MywzN_pEZSuwXrPQyw.png" /><figcaption>Example of download Azuki — Goerli NFTs using Opensea. V1 API</figcaption></figure><p>You can see, I am saving Azuki data in a file same name as contract address. And I am using thread. So why thread? Downloading an image can take more time so, image downalod I can do in background and same time I can store data in database. Which can save my most of the downloding time. You can use daemon thread and concurrent future to save data in thread loop when you have to download all of the 10000 NFTs. We will check in later example.</p><p>But here I was going to show you how to pass parameter in thread function. You can see in line no. 25, I am passing two paremeter, image_url and token_no to downalodNft function. You can use args parameter to pass argument to any thread function.</p><p><strong><em>Result of the above program is below.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Mly3-RcNTjta_G-QPN1e3w.png" /><figcaption>Example output for above program</figcaption></figure><h4><strong>ThreadPoolExecutor</strong></h4><p>In python, <strong><em>asynchronous execution can be performed with threads, using ThreadPoolExecutor. </em></strong>You can use this class while importing concurrent.futures.</p><p>Lets take same as above example using <strong>ThreadPoolExecutor</strong>. We will download all NFTs (Opensea return by default maximum 200 rows in one call) of Azuki.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eh1KHVXBmao7Dj561neHKg.png" /><figcaption>Example of ThreadPoolExecutor</figcaption></figure><p>From above example you can see, In line 25, to 30 is implementation example of <strong>ThreadPoolExecutor</strong>. By this example I am able to download 5 images at a time, as <strong><em>per max_workers is 5</em></strong> in line no. 25. Asynchronously this program is executing 5 threads of <strong>downloadAndSaveNft()</strong> function at a time. And in line no. 30 I am also returning result returned at line no. 11 and storing on <strong>string_result</strong> variable. You can save using list also.</p><h4>Multiprocessing or ProcessPoolExecutor</h4><p>Same as <strong>ThreadPoolExecutor</strong>, we can use <strong>ProcessPoolExecutor</strong> to download file on multiple process. Which is an example of multprocess program. ThreadPoolExecutor is Multithread Program.</p><p><strong>Example with executor.map():</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkFqf-LHsHjNDVUdYky2BQ.png" /><figcaption>Example with executor.map()</figcaption></figure><p>If you are using <strong>executor.map()</strong> instead of <strong>future</strong>, you have to pass array as parameter as line no. 27 and you will get result in <strong>result</strong> as line no. 27.</p><p>If you will write like , <strong><em>result = executor.map(functionname, parameter)</em></strong>. Here type of result will be not string but generator. Because <strong><em>map executor.map() returns generator.</em></strong></p><p><strong>Example with executor.submit() — as same as ThreadPoolExecutor:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rxMVoo4llq7NBO2DFd4SQ.png" /><figcaption>Example with executor.submit()</figcaption></figure><p>Same example as <strong>ThreadPoolExecutor</strong>, but liitle changes. You can see instead of <strong>ThreadPoolExexcutor</strong> I am using <strong>ProcessPoolExecutor</strong>.</p><p><strong><em>One main and important thing need to know</em></strong>. As you can see as example of <strong>ThreadPoolExecutor</strong> I am not directly using statement, but inside <strong>main()</strong> function. And that <strong>main()</strong> function I am calling as line no. 39 to 40. Its because, I need to start <strong><em>main process first and then child process</em></strong>. If I will call <strong>main()</strong> method without <em>__name__=’__main__’</em> , it will start child process before properly starting <strong>main</strong> method.</p><p>Try to remove line 39 and call directly main(), you will get error something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CClS1FcZmEPvtAPgNzC7dw.png" /><figcaption>Freeze_support() error when execute ProcessPoolExecutor without <em>__name__=’__main__’</em></figcaption></figure><p>You can also use multiprocessing, using process class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*zWAqByRPwGsNWb_wqbh7Lw.png" /><figcaption>Example of Process class</figcaption></figure><blockquote>Remember, a process is an instance of a computer program which is executed, but thread is part of process, kind unit of process or lightweight process which share its resources.</blockquote><h4>Thread Class</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*QCKAFMYZaT8b5OaagV8Zzg.png" /><figcaption>Example of Thread Class</figcaption></figure><p>In this example, we define a custom <strong>MyThread</strong> class that inherits from the built-in threading.Thread class. We define a constructor that takes a <strong>thread_id</strong> and a name argument, which are used to identify the thread. We also define a <strong>run()</strong> method, which is the method that will be executed when the thread starts.</p><p>In the <strong>run()</strong> method, we print a message indicating that the thread is starting, sleep for 2 seconds to simulate some work being done, and then print another message indicating that the thread is ending.</p><p>We then create two instances of the <strong>MyThread</strong> class, passing in unique <strong>thread_id</strong> and name values for each thread. We start the two threads by calling the <strong>start()</strong> method on each thread object.</p><p>Finally, we use the <strong>join()</strong> method <em>to wait for the two threads to finish their work before exiting the main thread</em>.</p><p>You can see above, two output line <em>“Starting Thread 1”</em> and <em>“Starting Thread 2”</em> message. After this , when you will execute, you can see it sleeps for 2 second and then executed <em>“Ending Thread 1”</em> and <em>“Ending Thread 2”</em> and then <em>“Exiting main thread”.</em></p><h4>Race Condition and Lock</h4><p>A race condition in Python occurs when the behavior of a program depends on the relative timing of two or more threads of execution. This can lead to unpredictable and incorrect results.</p><p>Here’s an example of a race condition in Python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhN9U9fro_SMTAHz0MBGXg.png" /><figcaption>Example of race condition in Python</figcaption></figure><p>This program creates ten threads, each of which increments a global count variable 100,000 times. The main thread then waits for all the threads to complete before printing the final value of count.</p><p>However, because the threads are executing concurrently, there is a race condition on the count variable. If two threads try to increment count at the same time, their updates may interfere with each other, leading to a final value of count that is less than the expected 1,000,000.</p><p>Check the different output below in output panel.</p><p><strong>To fix this race condition,</strong> you can use a <strong>lock</strong> to ensure that only one thread can access count at a time as below example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*b_uVbRgT9PPpgVHmLJuDOw.png" /><figcaption>Example to resolve Race Condition issue</figcaption></figure><p>You can initialize lock using <strong>threading.Lock()</strong></p><h4>Deadlock</h4><p>In Python threads, a deadlock can occur when two or more threads are blocked, waiting for each other to release a resource. Here’s an example of how a deadlock can occur in Python threads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*N4gCLb6A2Be_eeQkFg1O9w.png" /><figcaption>An example of Deadlock. I have stopped this program by ctrl+z</figcaption></figure><p>In this example, <strong>function1()</strong> acquires <strong>lock1</strong> and <strong>then</strong> <strong>lock2</strong>, while <strong>function2()</strong> acquires <strong>lock2</strong> and <strong>then</strong> <strong>lock1</strong>. When both threads start running, <strong>function1()</strong> acquires <strong>lock1</strong>, and then <strong>function2()</strong> acquires <strong>lock2</strong>. At this point, both threads are blocked, waiting for the other thread to release the lock it needs.</p><p>As a result, the program will never complete and will remain stuck in a deadlock.</p><p>To avoid deadlocks in Python threads, it’s important to ensure that locks are always acquired in a consistent order. In this example, <strong><em>both functions should acquire lock1 before lock2 to avoid a deadlock.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*JSE2Y8nV9mfsQ-XtArUJjw.png" /><figcaption>Example, How to avoid Deadlock</figcaption></figure><p>In this example, both <strong>function1()</strong> and <strong>function2()</strong> acquire <strong>lock1</strong> first before acquiring <strong>lock2</strong>. This ensures that both threads acquire the locks in a consistent order, preventing a potential deadlock.</p><p>Note that each function first acquires <strong>lock1</strong> before attempting to acquire <strong>lock2</strong>, and then releases the locks in the reverse order. This guarantees that the locks will always be acquired in the same order, preventing the possibility of a deadlock.</p><h4>Producer and Consumer</h4><p><strong><em>Producer and Consumer</em></strong> are often used to describe a pattern <strong><em>where one or more threads produce data and one or more threads consume that data</em></strong>. Here’s an example of how the Producer and Consumer pattern can be implemented using Python threads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*4X8h5VLeP30tA9wp4PgVug.png" /><figcaption>Example of Producer &amp; Consumer in Python thread</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Ubo6WyYeUKiV0trq2AHIAA.png" /><figcaption>Output of the above program.</figcaption></figure><p>In Python, you can use the threading module to create and manage threads. The <strong>threading.Condition class provides a way to wait for a specific condition to occur and to notify other threads when that condition has been met.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*-srfQjO7OM9_vaJ005Xmsg.png" /><figcaption>Example of threading condition and notify</figcaption></figure><blockquote>Remember Threading is a big topic, so I can’t cover everything here. You can read it from different articles.</blockquote><p>Some reference link to learn more about Python Threads:</p><ul><li><a href="https://realpython.com/intro-to-python-threading/">An Intro to Threading in Python - Real Python</a></li><li><a href="https://www.toptal.com/python/beginners-guide-to-concurrency-and-parallelism-in-python">Python Multithreading and Multiprocessing Tutorial | Toptal®</a></li><li><a href="https://docs.python.org/3/library/threading.html#rlock-objects">threading - Thread-based parallelism</a></li><li><a href="https://www.geeksforgeeks.org/multithreading-python-set-1/">Multithreading in Python | Set 1 - GeeksforGeeks</a></li></ul><p><a href="https://www.pythontutorial.net/python-concurrency/python-threading/">https://www.pythontutorial.net/python-concurrency/python-threading</a>/</p><p><a href="https://superfastpython.com/threading-in-python/#Thread_Condition">Python Threading: The Complete Guide</a></p><p>In one of my project —</p><p><a href="https://github.com/ntshvicky/live-camera-streaming-attendance-management-system/blob/master/app.py">live-camera-streaming-attendance-management-system/app.py at master · ntshvicky/live-camera-streaming-attendance-management-system</a></p><p><em>(Sorry for grammatical mistakes. I am from Hindi medium.)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fff0ed0ef1fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/basic-of-python-thread-fff0ed0ef1fe">Basic of Python — Thread</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic of Python — Generators]]></title>
            <link>https://medium.com/analytics-vidhya/basic-of-python-generators-895990675d15?source=rss-daed194b94b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/895990675d15</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-generators]]></category>
            <category><![CDATA[python-flask]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nitish Srivastava]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 23:41:57 GMT</pubDate>
            <atom:updated>2023-11-15T15:12:59.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2J5RAakqDLb_ZY1zsfj-Xg.png" /><figcaption>Image from Midjourney</figcaption></figure><p>Think if you need to write a function to read large dataset, function which can maintain internal state, stream some program parallelly; that time you can use <strong>Python Generators</strong>.</p><p><strong>Generators</strong> functions are a special kind of function that return a lazy iterator. An object that you can loop like a list. But like list iterator, generators do not store content in memory. Mean it does not return single value at once but returns iterator object, which you can read one by one while maintaining internal state. A generator uses<strong> yield</strong> statement instead of <strong>return</strong> statement.</p><p>Let’s take an example, as <strong>return</strong> and <strong>yield</strong> statement.</p><p>First check how <strong>returns</strong> work</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*hm_g2CsZcpmNypSuRHiQcg.png" /><figcaption>Image 1 — Example with return</figcaption></figure><p>In above example, function <strong><em>example_return()</em></strong>, returned same output when two time execute. <strong>Line no. 4 and 5</strong> is unreachable statement.</p><p>Now lets see, same example, but using <strong>yield</strong> statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*e6oEGD2E0YLnFkDr8VxmTw.png" /><figcaption>Image 2 — Example with yield</figcaption></figure><p>See above example, instead of return I am using <strong>yield</strong> keyword. Now the <strong>line no. 4 and 5</strong> is reachable. And below, in <strong>line no. 9 and 10</strong>, when I am printing <strong><em>multi_obj</em></strong>, it returns both outputs.</p><p>This is how generators works. A normal iterator uses <strong><em>__iter__</em></strong>, but a generator uses <strong><em>__next__</em></strong> to iterate.</p><h3><strong>Use of For Loop in generator</strong></h3><p>In your above example, you can also execute both statement using <strong>for loop</strong>. Normally I want to say, there is another way of executing generator, using <strong>For Loop</strong> instead of <strong><em>next()</em></strong>.</p><p>Same code, little changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*mFUnruXlRq2U7hbND6Rk-g.png" /><figcaption>Image 3 — Example in Loop</figcaption></figure><p>Lets, find square of some elements in list using generators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*myY7_dXIhCbsTNwfRiHoYQ.png" /><figcaption>Image 4</figcaption></figure><p>In above example, I am passing a list in generator function <strong>square_number()</strong>. Which is returning square value of each elements passed.</p><p>Now see this example and understand use of <strong>yield </strong>keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*a-i8oZ3T17B1-MsIzAHOWQ.png" /><figcaption>Image 5</figcaption></figure><p>Here you can see, statement is returning <strong><em>traceback runtime error of StopIteration</em></strong>, on line number 11. Because <strong>yield </strong>keyword has executed only two times. When generator iterator is trying to read it third time, its being fail.</p><p>A primary job of <strong>yield </strong>statement is to control the flow of a generator function, on the call of <strong><em>next()</em></strong>.</p><h3>Lets check the use of memory when using <strong>return </strong>keyword and same with <strong>yield </strong>keyword.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNazVtvJGIGIvsD2DrdOJw.png" /><figcaption>Image 6 — Example to check how much memory normal iteration is taking</figcaption></figure><p>In above example, you can see while iterating on normal list, it is using 288 Mb memory.</p><p>But same example, but using generators</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xH2YEsUVzVg-7AwQs1OX0Q.png" /><figcaption>Image 7 — Example to check how much memory generator is taking</figcaption></figure><p>In above example, you can when I am using yield, instead of return, its is not taking extra internal memory. Before and after approx. same memory 19 and 19.</p><p><em>Now, I don’t think I need to explain why generators is useful.</em></p><h3><strong>send() and Parallel Programming using Generators</strong></h3><p>Now Lets check, how we can use Generators to execute program parallelly, using <strong><em>send()</em></strong> function. Using<strong><em> send(</em></strong>) function, you can pass a value back to generator. See below example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1IELrxL_tIAAJ6UlapteHg.png" /><figcaption>Image 8</figcaption></figure><p>Here, we can see, I have passed None in line no. 8, on first send statement. Because, <strong><em>we can not send non-None value on just started generator</em></strong>. After that in line number 10, I am passing a value (1000) to the generator, which is printing on line no. 4, with variable val attached with <strong>yield</strong> keyword. And same next 2000, 3000, 4000 is executing.</p><p>What happen, if I will pass some value in first send statement?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0-ripUICcMDeAx3xDskcQ.png" /><figcaption>Image 9 — to show error if using non-None value in first send statement</figcaption></figure><p>You will get error like above example. See in line no. 8, I am getting a runtime error and error message you can see below in terminal screen.</p><p>Lets an another example with loop statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYs2_E2Q2noLPnvwfjCTvg.png" /><figcaption>Image 10 — parallel execution of function</figcaption></figure><p>In above code, you can see I am running two function at same time, also passing a value to another function. Like I am passing value 1000, from <strong><em>mainRoutine()</em></strong> to <strong><em>subroutine()</em></strong> function. Instead of just output, <strong><em>yield val,</em></strong> you can pass passed value on a variable.</p><p>Like <strong>M = yield val</strong>, and then you can write your own statement after this statement to handle passed value in <strong>M</strong>. Like below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNkHz5pMQDHbdXcX9qLRtw.png" /><figcaption>Image 11</figcaption></figure><p>In above example, you can see, both program is running parallely and also calculating value passed by <strong><em>mainRoutine()</em></strong> (line no. 15) on <strong><em>subroutine()</em></strong> (line no. 6).</p><h3>Generator as Expression</h3><p>You can write generator also in one line of code. Below is an example of writing generator with example of list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*HReS2jlyLm7ghT-M9BELdQ.png" /><figcaption>Image 12 — Example on expression</figcaption></figure><p>Just see, same code using [] is list and () is generator.</p><h3>So, where you can use generator?</h3><p>Try these flask code example by yourself</p><p><strong>Example 1: For streaming images –</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACrUSvC02-eigckju4RDRQ.png" /><figcaption>Image 13 — A flask app to stream iamges as video</figcaption></figure><p>For this example, you need a folder in code area with name <strong>assets</strong> and images on it. And one <strong>index.html</strong> file in flask templates folder. After running this application, if you will open <strong><em>localhost:5000</em></strong> link in browser, you can see your images from <strong>assets</strong> folder, is showing one by one.<em> You can stream any images, videos from frame using this code.</em></p><p><strong>Index.html</strong> file for above example is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*MckBWq5Y9zXnKaEFNXeZ_A.png" /><figcaption>Image 14 — .html file to render video from above (image — 13) example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Vw6zstYSF9oMTMhPsC3dpA.gif" /><figcaption>Preview output</figcaption></figure><p><strong>Example 2: Read data from database and print on html one by one using generators</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHRo4CMwjC_kDkzV0JuM2A.png" /><figcaption>Image 15 — A flask app to read data from mongo database and render output in html using genenrators</figcaption></figure><p>Above example is reading data from mongo database and streaming result one by one on html. Here as for example, I am reading follower data stored in my database <em>db_twitter</em>, and printing that data on html. Below is html example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*nfYC43TLQJEz9hK5SsGj2Q.gif" /><figcaption>Preview output</figcaption></figure><blockquote><strong><em>Update_template_context</em></strong><em>, injects request, session, config and g into the template context as well as everything template context processors want to inject.</em></blockquote><p>If you need to pass generator’s <strong><em>next()</em></strong> function into jinja template. You need to make an custom filter on flask app like below.</p><blockquote>@app.template_filter()</blockquote><blockquote>def next_id(gen):</blockquote><blockquote>return next(gen)</blockquote><p>in html , you can read this with data as</p><blockquote>{{ data | next_id }}</blockquote><p>Now , I think you have understand many basic thing on generators. Try more and more yourself. If you are using thread for any parallel program, try to convert that into generators.</p><p><em>(Sorry for grammatical mistakes)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=895990675d15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/basic-of-python-generators-895990675d15">Basic of Python — Generators</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic of Python — Numpy]]></title>
            <link>https://ntsh-vicky.medium.com/lets-see-some-basic-of-numpy-8ce231e7a89e?source=rss-daed194b94b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ce231e7a89e</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[numpy-array]]></category>
            <category><![CDATA[numpy-tutorial]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nitish Srivastava]]></dc:creator>
            <pubDate>Wed, 11 May 2022 15:49:25 GMT</pubDate>
            <atom:updated>2023-11-15T15:13:30.481Z</atom:updated>
            <content:encoded><![CDATA[<p>NumPy (<strong>Numerical Python</strong>) is an open source Python library that’s used to solve different kind of scientific and numerical problems. The NumPy library contains multidimensional array and matrix data structures. It provides homogeneous n-dimensional array (ndarray) object, with methods to efficiently operate on it. It can used to solve variety of mathematical and statistical operations on arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*QPp7NZVG4RJoCWFHz8GJHQ.png" /></figure><p><strong>How to install Numpy?</strong></p><p>1. In anaconda environment — <em>conda install numpy</em></p><p>2. In pip environment — <em>pip install numpy</em></p><p><strong>How to import Numpy in your project modules?</strong></p><p><em>Import numpy as np</em></p><p>To access numpy function we can use above statement in our modules and we can also provide a short name to access it, like here I have used <strong>np.</strong></p><p><strong>What is alias or Short naming for library?</strong></p><p>This is the way you can give an short alias for existing library, like import pandas as pd, for panda, or import mycustomlibrarylongnameexample as mylb, and call just mylb.and_your_function_or_object_name.</p><p><strong>Let’s an example of numpy array and understand difference between numpy array and normal python list.</strong></p><p><em># ====== create range array ==================</em></p><p><em>//Example of Range</em></p><p><em>ar = range(6)</em></p><p><em># Output — range(0,6)</em></p><p><em>list(ar)</em></p><p><em># Output — [0,1,2,3,4,5]</em></p><p><em>// Example of Numpy</em></p><p><em>ar = np.arange(6) # Output — array[0,1,2,3,4,5]</em></p><p>Just execute above code in terminal and see output. Try more, different variables, different array size and different values.</p><p><strong>Why Numpy based maniplulation is better than normal python list?</strong></p><p>Let’s see an example to add values in the list/array. Write below given code on your python terminal and test.</p><p><em>import time</em></p><p><em>import numpy as np</em></p><p><em>print(==== Example for range =====”)</em></p><p><em>start = time.time()</em></p><p><em>total_sum = sum(range(100000000))</em></p><p><em>print(“Result — Duration: {total_sum} — {time.time() — start} seconds”)</em></p><p><em>print(“===== Example for numpy =====”)</em></p><p><em>start = time.time()</em></p><p><em>total_sum = np.sum(np.arange(100000000))</em></p><p><em>print(“Result — Duration: {total_sum} — {time.time() — start} seconds”)</em></p><p><em>You can see output like this,</em></p><p><em>==== Example for range =====</em></p><p><em>Result — Duration: 4999999950000000–1.1205904483795166 seconds</em></p><p><em>===== Example for numpy =====</em></p><p><em>Result — Duration: 4999999950000000–0.7411048412322998 seconds</em> // it may be different, but yes, duration value will be less than range one.</p><p>In above output, you can see numpy tooks less time than range to sum array of 0 to 100000000. It’s a small example. You can try more.</p><p><strong>Few another examples :-</strong></p><p>Convert one dimensional array into multidimensional</p><p>So, first question maybe you are thinking, what is an array? I think everyone has already studied about it on their school, while studying, C or C++. An array is a grid of values. It can be one dimensional, two dimensional or N-dimensional. Basically, in array all elements are same type, called <strong>dtype.</strong></p><p><strong>Example — </strong>A<em>= [1,2,3,4,5,6]</em> //An array with length 6</p><p>Every element in an array is exists on an index started from 0. like above example 1 is on 0 index of array a. So last index = length of array -1</p><p>A[0] = 1</p><p>A[1] = 2</p><p>A[2] = 3</p><p>A[3] = 4</p><p>A[4] = 5</p><p>A[5] = 6</p><p>In python, a list is an array. Here <strong>A </strong>is list. You can convert a list into NumPy array by np.array(A) (np is alias for NumPy).</p><p><strong>Convert a one-dimensional array into multidimensional</strong></p><p>To convert a one-dimensional array to multidimensional, you can use reshape function.</p><p>Like,</p><p><em>A = np.array([1,2,3,4,5,6])</em></p><p>Here, A contains 6 elements. You can only convert an array into multidimensional based on its size. Like,</p><p><em>A = [1,2,3,4,5,6]</em></p><p><em>A.reashape(1,6) //output:- array([[1, 2, 3, 4, 5, 6]]) — two dimensional</em></p><p><em>A.reshape(1,6,10) //output:- array([[[1],[2],[3],[4],[5],[6]]]) — three dimensional</em></p><p><em>A.reshape(1,6,1,1) //output:- array([[[[1],[2],[3],[4],[5],[6]]]])</em></p><p>Inside reshape, whatever nos of parameter you are passing, will create that size of array.</p><p><strong>Another example,</strong></p><p><em>A.reshape(2,3) //output array([[1, 2, 3], [4, 5, 6]])</em></p><p>In above example, you are creating one two-dimensional array, where second array size will be 2 and each array will contain 3 elements.</p><p><em>A.reshape(2,3,1) //output array([[1], [2], [3], [4,] [5], [6]])</em></p><p>n above example, you are saying that A is a three-dimensional array, where main array contains 2 another array, and inside array contains another 3 array and each array contains 1 element.</p><p>Mean, last one is always elements. And other first value is saying, main array contains, inner some array and same for next.</p><p><strong>Some basic other manipulations in numpy.</strong></p><p><em>A = np.array([1,2,5,6,4,3])</em></p><p><em>B = np.array([1,2,3,4,5,6])</em></p><p>Sort array in ascending order :- <em>np.sort(A)</em></p><p>Sort array in descending order :- -<em>np.sort(-A),</em> or <em>np.sort(A)[::-1]</em></p><p>Sum array’s elements :- <em>np.sum(A) </em>//return 21 integer value</p><p>Sum two array :- <em>np.add(A,B)</em></p><p>Concatinate two arrays :- <em>np.concatenate((A,B), axis=0) </em><strong>// join two array in one</strong></p><p>Know shape of array :- <em>A.shape </em>— Output :- (6,)</p><p>Dimension of array :- <em>A.ndim </em>— Output :- 1</p><p>Size of array :- <em>A.size</em> — Output :- 6</p><p>Lets Try these three on another dimension :-</p><p><em>A = np.array([[1, 2, 3], [4, 5, 6]])</em></p><p>Know shape of array :- <em>A.shape</em> — Output :- (2, 3)</p><p>Dimension of array :- <em>A.ndim</em> — Output :- 2</p><p>Size of array :- <em>A.size</em> — Output :- 6</p><p>Convert multidimensional to one dimensional -</p><p><em>A.flatten()</em> //Output :- array([1, 2, 3, 4, 5, 6])</p><p><em>A.ravel()</em> //Output :- array([1, 2, 3, 4, 5, 6])</p><p><strong>Save NumPy object in a disk file as .<em>npy extension, </em>so you can transfer your NumPy object one place to another and read again.</strong></p><p><em>np.save(“filename”, A)</em></p><p>It will save file on your disk. You can read this object using load function.</p><p><strong>Example:-</strong></p><p><em>A = np.array([1,2,3,4,5,6])</em></p><p><em>np.save(“test”, A)</em></p><p><em>B = np.load(“test.npy”)</em></p><p>So, output of B is array([1,2,3,4,5,6]). Do like this, save your file in your computer and open this file in your friend computer. <strong>Writing object to file called serialization and converting file to object called deserialization.</strong></p><p><strong>Let’s an another example to convert an image into NumPy array and then NumPy array to image:</strong></p><p><em># Image to numpy array</em></p><p><em>from PIL import Image</em></p><p><em>image = Image.open(“image.png”)</em></p><p><em>image_array = np.array(image)</em></p><p><em>#numpy array to image</em></p><p><em>Image.fromarray(image_array).save(“image.png”)</em></p><p>If you will be master on it, you can create your own image using numpy array.</p><p>Check, what is np.ones, np.zeros, np.empty, np.tan, np.sin, np.cos, np.add, np.subtract, np.multiply, np.divide, np.percentile, np.copy etc.</p><p>Also try, dir and help function with different numPy functions. Like help(np.sort), dir(np) etc.</p><p><strong>There is so many things, NumPy contains. Not possible to teach in one article. Its just for your idea. Give your time to study about NumPy from different websites like, tutorials point, numpy.org, search articles based on NumPy.</strong></p><p><em>(Sorry for grammatical mistakes)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ce231e7a89e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic of Python Decorators]]></title>
            <link>https://medium.com/analytics-vidhya/basic-of-python-decorators-65ffe8cd7adf?source=rss-daed194b94b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/65ffe8cd7adf</guid>
            <category><![CDATA[python-decorators]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Nitish Srivastava]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 16:22:27 GMT</pubDate>
            <atom:updated>2023-11-15T15:13:55.181Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basic of Python — Decorators</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05kxIGqUK3aIucSEji-dMg.png" /><figcaption>Image from Midjourney</figcaption></figure><p><strong>Decorators</strong> are a powerful and useful tool in Python since it allows programmers to modify the behaviors of function or class. Decorators allow us to wrap another function to extend the behaviors of the wrapped function, without permanently modifying it.</p><p><strong>A Basic Example of Decorator:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*J9N0bVYzMyRyhQuQ5EGrfw.png" /><figcaption>Example 1 — Basic example of decorator</figcaption></figure><p>In the above example, <strong>decorator_function(func) </strong>is the decorator and <strong>showMessage()</strong> is the normal function. You can see inside <strong>decorator_function</strong>, there is an internal function <strong>wrapper</strong>, which is indicating to <strong>showMessage </strong>function and that <strong>showMessage</strong> function is executing on line number 4, between two <strong>print </strong>statement. Remember, you must return wrapper itself to integrate decorator.</p><p>Let see another way of writing decorator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*4J9Mt3YvXAuz-iDZ5Hcylw.png" /><figcaption>Example 2 — Decorator as annotation</figcaption></figure><p>Above you can see, This code is same as previous code, except way of integration of decorator, just integrate with @ annotation just above the function you want to integrate that decorator.</p><p>Let see another example while calling your function multiple times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*mkhhqx2E_d6VYf6ivsPp-g.png" /><figcaption>Example 3 — Execute showMessage two times through decorator</figcaption></figure><p>Let see another example and call your function before first print statement and then between print statement. And see what happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*LQ7XpbPdConsVuLs7xWRqw.png" /><figcaption>Example 4 — Calling function two times before print message and after print message and showing output</figcaption></figure><p>Using the above two examples, you can see inside wrapper, whenever I am calling <strong>func()</strong>, it is executing the <strong>showMessage</strong> function.</p><p>Check what happens if I will write another variable name instead of <strong><em>func</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*ZNACyUs-GgRfboCmWUmqiQ.png" /><figcaption>Example 5 — Example with argument variable’s name changed</figcaption></figure><p>You can see in above example, I have changed <strong>decorator_function</strong> argument name from <strong>func</strong> to <strong>f</strong>, and still same output as previous. Line number 1, 3 and 5. There us no specific requirements to give name here. You can set anything.</p><p>Let another example with condition. In this example we can see, caller function will only execute when condition is true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*gglicMzjFqGSxRpfS7NXag.png" /><figcaption>Example 6 — Example with condition.</figcaption></figure><p>Above example, you can see in line number 1, I have declared a variable named <strong>age </strong>with default value 33 and inside wrapper, in line number 5, I have added a condition, that if age &gt; 33 then execute caller function, either not. Now you can see output. It has not executed “<em>Hello World!</em>” message, because condition is false.</p><p>What happened when above condition was true?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*0LhHpikB_dpqO_lDbMHkDA.png" /><figcaption>Example 7— Example with condition. As same as previous but this time it is showing output.</figcaption></figure><p>See in output terminal, when condition is true (because age = 34 and age &gt; 33), its executed message “<strong>Hello World!</strong>”.</p><p><strong>Decorators with parameter:</strong></p><p>You can also pass parameter to decorators. Which is very helpful, when you have to write some condition for specific function but you want to write one decorator. Like input validation, log creation etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*HdOp8hx8PlJI07zSXzMHjw.png" /><figcaption>Example 8— Example with custom argument</figcaption></figure><p>In above image, you can see, in line number 11, I have passed one parameter with decorator <strong>age = 34 </strong>and a minor change in <strong>decorator_function</strong>. Now parameter “f” Instead of directly with decorator function, I have passed inside decorator while creating another inner function named as <strong>inner_decorator</strong> (you can put any name).</p><p>You will get error, if you will try to pass “f” directly in <strong>decorator_function</strong>, like below example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*VWyfrJFsJEke0ZqgrxcUHg.png" /><figcaption>Example 9— Example of error, if writing argumented decorator wrong way</figcaption></figure><p>Or even like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*WNea-0jf8VSbfKomUkwU3A.png" /><figcaption>Example 10— Example of error, if writing argumented decorator wrong way</figcaption></figure><p>You can see, how i am getting directly a compile time error. So better way use as previous correct way as Example 8.</p><p><strong>So, where do you think you can use decorator:</strong></p><p>Its on your requirement, but just for idea, you can use decorator on below given point. Because this all are basically used on any software application.</p><ol><li><strong>To validate user session: </strong>— You can use decorator to check if user is logged in or not and only then let them use caller function. Like If session is null, or not valid user session, then prevent user to access internal dashboard.</li><li><strong>To validate API’s access token: </strong>— In your application/ API, if you want only user with valid access token can access this function, you can validate that function with decorator. Write once for validation and use with every function you want. Example below.</li><li><strong>In case of Input Validation: — </strong>You can validate if coming request is valid or not and only then let user to execute a function.</li><li><strong>To save log after every execution: — </strong>You can write a simple code to save every request header and log for every request after execution of that function based on your need.</li><li><strong>To handle Exceptions and Errors: — </strong>You can also write code to handle different kind of errors.</li><li><strong>To manage user/session role:-</strong> You can write decorator to check valid user or role is only able to access your api.</li></ol><p><strong>Let see an example using Flask:</strong></p><p>Step 1 :- import important libraries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*Ha8EBEA_KSJJpdW58KbC9w.png" /><figcaption>Example 11 — Code to import required libraries in Python</figcaption></figure><p>Step 2 :- Setup Flask</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*Qry6UyIs3vleQoNkKoYufA.png" /><figcaption>Example 12 — Setup flask</figcaption></figure><p>Step 3 :- Write decorators for as per your need</p><p>Below decorator is used to validate x-access-token generated on login.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*W5-1z1j2lax-NIdX0oXNFw.png" /><figcaption>Example 13 — Decorator to check access token on every api call</figcaption></figure><p>Write another decorator to validate data coming from request. You can modify your code as per your need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvSvhaqw5ha2FYbEbOtutA.png" /><figcaption>Example 14 — Decorator to check required input exists on request or not</figcaption></figure><p>Write another decorator to create log after every request. Here I am saving data in text file. You can save data in database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfoC6FoyYAq6rM3ETxtbaw.png" /><figcaption>Example 15 — Decorator to create log after every api executed</figcaption></figure><p>Step 4 :- Now, lets use these decorators.</p><p>Here in my first example on login API. I am using <strong>validate_request</strong> decorator to validate input coming with api call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qzi5euO4WQRbdMi9gm71Ow.png" /><figcaption>Example 16 — A login example to generate JWT token</figcaption></figure><p>Here, you can see I am passing required parameter to <strong>validate_request</strong> decorator to check keys username and password available with request or not??? Here Example 14, <strong>validate_request</strong>, from line number 38 to 44, I am checking input is available or not…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*zRn65yE-PjZKNsHIf-81Mg.png" /><figcaption>Example 17— Code to validate access token, and only user can access dashboard</figcaption></figure><p>And in dashboard API, using <strong>token_required</strong> decorator, In Example 13, I am first checking if user is passing valid x-access-token then user can access dashboard. This x-access-token is generated at login in previous example (Example 16). Example you can find here — <a href="https://github.com/ntshvicky/Decorator-Test">https://github.com/ntshvicky/Decorator-Test</a></p><p>So, i think, now you can understand use of decorator. Next time we will check some example of decorators with Classes. Way is same just how to write decorator class.</p><p>Write your own code, different condition, different problems and solve using decorator. Thanks….</p><p><em>(Sorry for grammatical mistakes)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65ffe8cd7adf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/basic-of-python-decorators-65ffe8cd7adf">Basic of Python Decorators</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic of Python — 2 : Classes]]></title>
            <link>https://medium.com/analytics-vidhya/basic-of-python-2-classes-a1ce5ddb529c?source=rss-daed194b94b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ce5ddb529c</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[basic-python]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nitish Srivastava]]></dc:creator>
            <pubDate>Sun, 18 Jul 2021 19:17:55 GMT</pubDate>
            <atom:updated>2023-11-15T15:14:26.153Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basic of Python — Classes</h3><p>Today, Python has most demand in IT industry. And everybody want to learn and make career in Python.</p><p>In previous article we have seen some basic of Python, so you can start learning it by yourself. Today, we will learn about Classes and its members, like constructor, class variable, local variable and class functions. We will also check some built in attributes available with classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6JBzRbrZskRCiVqh9vA4A.png" /></figure><p>My previous article in Python: <a href="https://ntsh-vicky.medium.com/basic-of-python-edd5ec6845e5">https://ntsh-vicky.medium.com/basic-of-python-edd5ec6845e5</a></p><p><strong>Object Oriented Programming Concept (OOPs)</strong></p><p>Before learning classes and objects, you should know about OOP’s Concept. There is a lots of articles you can find in OOP’s concept, just you need to search in Google.</p><p>An Object Oriented programming aims to implement logic of real world entities in programming, like classes, objects, inheritance, hiding, polymorphism etc.</p><ol><li><strong>Classes </strong>: A class is a blueprint or prototype. This is not a physical things. In real life example, Human is a class, vehicle is a class, car is a class. Here, human, vehicle and car does not represent a specific thing but a whole community. If you think about human, then here boy, girls, women, man, your father, your mother, you, me; every body is human. No specific one. Vehicle, whatever you are looking at road, car, truck, bike etc.</li></ol><p>It represents the set of properties or methods that are common to all objects.</p><p>In Python we declare a class using class keyword, following with the name of class.</p><p><em>Syntax : class &lt;class name here&gt;</em></p><p><em>Example: class Vehicle</em></p><p><strong>2. Object </strong>: An object is a basic unit of object oriented programming and specified a specific class. As class human, you are an object, i am an object. A bike you have is an object. Whatever you are looking is an object. So an object always has a state, behavior and an identity.</p><p>Like me, state: ethnicity, color, body; behavior: angry, happy, eating etc; identity: my name e.i. Nitish Srivastava.</p><p>Like your bike, state: running, stand, might be flying also if you are a stuntman; behavior: horn, break etc. Identity: its vehicle number…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*bPtXsk2JQqkudnYNUr_Sow.png" /><figcaption>An Example of a class named Vehicle</figcaption></figure><p>Above image contains a class named, Vehicle. Here you can see, Vehicle class is declared by keyword <em>class</em> and contains some member inside it. In line number 4, <em>msg</em> is a class variable, which initialized with a default string message “This is vehicle class”.</p><p>Below in line number 6 and 9, class <em>Vehicle</em> contains two member function <em>showMsg</em> and <em>listenHorn </em>respectively. <em>showMsg</em> has a statement, which printing whatever <em>msg</em> conatins (line number7) and listenHorn, first initializing a local variable horn (in line number 10) and then printing it (in line number 11). And you can see, both function has one parameter <em>self</em>.</p><p>By default in Python, every member function has first parameter self. So while creating these functions, you need to write at least one argument in functions. Here i have created this argument as named self. You can name anything, but self is meaningful.</p><p>The first parameter of a function of a class, referenced object of its class. Its same as <em>this</em> keyword in Java. You can named it anything. If you have to call any class member, you need to call with this parameter’s given name. As below image, i have changed name of the function parameter <em>self</em> to <em>hhh.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*xK0lbu_DKvigpenOR4CmBg.png" /></figure><p>You can see, in line number 7, i am calling <em>msg</em> variable with parameter (hhh.msg), but not <em>horn</em>, in line number 11. Always remember, a class member you need to call with first parameter of function, or outside class with the name of the object of the class (like line number 16). But, because <em>horn</em> is not a class member but local member of function <em>listenHorn</em>, you no need to write <em>hhh</em> (or <em>self</em>) with it. Also you can’t call variable<em> horn</em> (or any local variable) with object as given in line number 18.</p><p>Now come to see what happening from line number 13.</p><p>v = Vehicle(), this is the way to initialized object in Python (in Java or C++, same you are doing with new keyword). here name of the object is v, which is an object of class Vehicle. So if you want to use member of the class, like its class variable or functions, you need to call it through object.</p><p>You can see, in line number 16, i have reinitialized variable <em>msg</em>. and in output of line number 17, it has changed. But i have also tried to reinitialized variable <em>horn</em> in line number 18, but it has not changed in the output of line number 19. It is still Peep Peep.</p><p>Lets an another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*3YUyT8ChXkVGQ-F3pF5knw.png" /><figcaption>program after some changes</figcaption></figure><p>In the above image, i have created a new function showName with two parameter. Same first parameter referenced object of the class and second parameter what you have to pass. So in line number 14 and 19, you can see i am passing a string value in function showName. In line 14, <strong>Bullet 400</strong> with object name <em>v</em>, and in line 19, <strong>Classic 350</strong> with new object <em>v1</em>. Wherever, there is two parameter showName contains, so why i am passing only one string parameter, and line number 10 statement is showing second parameter’s variable. Because as we already talked, first parameter is referenced to object of the class, so you have to work with second or next parameter if you have.</p><p>Also you can see, two different object is not affecting each other. As line 23, has not changed because of line 20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*LymElAAjaaE3V27Y3g8NuQ.png" /><figcaption>An example of self parameter and how you can use it. Also it has an example of constructor.</figcaption></figure><p>In above image, check line number 22,23,25,26, how actually self works.</p><p><strong>3. Constructor: </strong>In the above image, line number 7, is an example of constructor. In another programming language, like C++ or Java, you have learnt about constructor is the class member function, has same name as class name, without any return type defined and called when an object of this class is created.</p><p>In Python, we declare constructor using <em>__init__(self)</em> function. It is a predefined name. Use is same, it called when you are creating object of its class. Like in line number 17 and 19 in above image, constructor directly called when initializing an object. In above example, i have also passed a string parameter with class, which is passing through <em>name</em> variable in constructor. You can pass any number of arguments inside function, but first one is default referenced to object of the class.</p><p>How to use function and its argument you can learn in my previous article <a href="https://ntsh-vicky.medium.com/basic-of-python-edd5ec6845e5">https://ntsh-vicky.medium.com/basic-of-python-edd5ec6845e5</a>#66be . You can use *args or *kargs for number of argument.</p><p><strong>4. Inheritance: </strong>Inheritance is an another features of Object Oriented Programming. Its provide re-usability of the code.</p><p>In real life example, Human, it can walk, run, talk, eat etc. If there is sub class of human like Boy and Girl, both have same attribute or behavior, but there is some sub class has its own attribute. Like Boys can stunt (these days normal for girls too). Girls can birth, but not boys. So walk, run, talk, eat is basic attribute of a super class human, but some specific attribute a sub class may have like birth for class Girl. Same if super class is Vehicle and sub class is FourWheeler and TwoWheeler, then both contains all the features of super class but with their own specific feature.</p><p>Inheritance is the process of building a new class based on the features of another existing class. Check the below example on vehicle and its output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*D3w-INxveDjTI6FKIDwXug.png" /><figcaption>In this example, you can see, both class FourWheeler and TwoWheeler is initializing constructor of Vehicle class, with their own constructor while initializing.</figcaption></figure><p>You can use inheritance while calling database configuration file on another file, If database configuration will be same for all.</p><p><strong>5. Polymorphism:</strong> The word polymorphism means having many forms. In some programming language, polymorphism is also described as same function name but different signature of arguments, that is called overloading. Also some times base class has same function name as super class with same signature, is called overriding.</p><p>You can’t use same function name and different parameter logic in Python. As below given image, you will see error like that….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*vWuIYkSCEDzZZQvloG0iag.png" /><figcaption>Like other programming language it is not printing showMsg function without parameter and with parameter separately as it called.</figcaption></figure><p>But, you can use polymorphism with inheritance while overriding function in base class, as in image given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*7Kz_RO6YMUeAEXqVewteCw.png" /><figcaption>An example of Polymorphism</figcaption></figure><p>You can see in the above image example, there is two sub class extending one super class <em>Vehicle</em>. Both sub class has one function <em>showMsg</em>, same name as defined in super class <em>Vehicle</em>. While printing, both are printing constructor (self.__class__.__name__ returns name of the class of the object) of class <em>Vehicle</em>, but with their own function <em>showMsg</em>. Because here they are overriding <em>showMsg </em>of class vehicle with their own function.</p><p>If you want to print <em>showMsg</em> of class Vehicle, you have to create its own object, <strong><em>v3 = Vehicle()</em></strong>, and then call <em>showMsg</em> like <strong><em>v3.showMsg()</em></strong>.</p><p><strong>6. Access Modifier:</strong> It is used to restrict access to the variables and methods of the class.</p><p>There is three types of access modifier:</p><ol><li>Public Access Modifier</li><li>Protected Access Modifier</li><li>Private Access Modifier</li><li>Public Access Modifier : The members of a class that are declared public are easily accessible from any part of the program. All data members and member functions of a class are public by default.</li><li>Protected Access Modifier : The members of a class that are declared protected are only accessible to a class derived from it. Data members of a class are declared protected by adding a single underscore ‘_’ symbol before the data member of that class.</li><li>Private Access Modifier : The members of a class that are declared private are accessible within the class only, private access modifier is the most secure access modifier. Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class.</li></ol><p>Example of Public Access Modifier : msg = “Hello World”</p><p>Example of Protected Access Modifier : _msg = “Hello World”</p><p>Example of Private Access Modifier : __msg = “Hello World”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*DkLZCpXZ0fmT5sc8_nQpIQ.png" /><figcaption>In this example, all the variable works, because they are member of class Vehicle</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*DztqdTmgmubTmAs24II42A.png" /><figcaption>In this example, all the variable works, except private variable __msg3, because it is member of class Vehicle only and _msg a protected variable called in sub class because it is part of its super class.</figcaption></figure><p>In python protected member can also used by the object of the class in another class, as example below in line number 19….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QsmCnyEOQjAiGAYZjq7Ybw.png" /><figcaption>Example of protected variable used by another class</figcaption></figure><p>Some basic command on Python you can try to learn about any classes or object or keyword in Python</p><ol><li>Know the name of class :- &lt;objectname&gt;.__class__.__name__ , like above examples self.__class__.__name__ or v.__class__.__name__</li><li>Know built in attributes to use with objects:- dir(objectname) or dir(keywords). like dir(list) will return name of all built in functions or attributes of list.</li><li>See the details and help documentation of any keywords :- help(keywordname), like help(list)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3hUh6T_C0h9VfoCPrBIdA.png" /><figcaption>some examples of dir command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*ohXBnQjPUxZSxZw4dCXIPQ.png" /><figcaption>An output of help(dict) command</figcaption></figure><p>Thanks. Always try to write your code with OOPs functionality, because of Encapsulation and Re-usability.</p><p><em>(Sorry for grammatical mistakes)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ce5ddb529c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/basic-of-python-2-classes-a1ce5ddb529c">Basic of Python — 2 : Classes</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Of Python]]></title>
            <link>https://medium.com/analytics-vidhya/basic-of-python-edd5ec6845e5?source=rss-daed194b94b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/edd5ec6845e5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[basics-of-python]]></category>
            <category><![CDATA[learn-python]]></category>
            <dc:creator><![CDATA[Nitish Srivastava]]></dc:creator>
            <pubDate>Sun, 27 Jun 2021 13:00:47 GMT</pubDate>
            <atom:updated>2021-08-23T10:59:37.319Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, Python has most demand in IT industry. And everybody want to learn and make career in Python.</p><p>If you have started learning python, then this is for you. In this article i will tell you some basics things of Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3KPNc09euMSFTwCvWOU0_w.png" /></figure><p>Python Official Website: <a href="https://www.python.org/">https://www.python.org/</a></p><p><strong>Basic usable IDE for Python</strong></p><ol><li>Anaconda — <a href="https://www.anaconda.com/products/individual">https://www.anaconda.com/products/individual</a></li><li>Jupyter Notebook — <a href="https://jupyter.org/">https://jupyter.org/</a></li><li>Spyder — <a href="https://www.spyder-ide.org/?__cf_chl_managed_tk__=dc7f6d76645d7b40423442cdbf82208693551e82-1624780739-0-AUlemzI1dioDM8EUGWaM7voV51ftdeFf6osr63Qo5A0egrBhQgx9Rf0wNUCsmVKm1RamTpxL62iMAsCtXqfzEzMBekimjiHuZzp4l_ggG5HoQnhV21ERA9yOpWPloSv-7uyKQxwhF6vTBHRziBaRrO7W7wYPXBw2ZQX5NSyqPZmzGZLBgdkfFWC-8XAs3S47fF9CT6UDHeR6igXbXUHKTLXdDV7qqYw4sFt3k5W0sgRbPkFTJaG7REdEp9keFU0pAFzW2g50QPkP0rJcCPwUD3cRRrxu6oRpiOUrdL3fSvW8n4rFy98Gu0f4acOf0jP4KDkvOiidKThWPChoykA441YLvLLIeIz584krQWmMTxYJjQ_NjDW6uJzYLtNI4wDjZXbkEn_KUJ0wayNP1vwe2nxFuWtoGM8Ub43lJhIJ21kniVCon73VkstsOovli4Da1PAuEcBukDyexxpOFhW73Dk4Mn1xL_COiwNMgrQvJqGa4u5AJruvK7LSI76JIWh9s8jF-rHar0x-C9FkcNLkoZRMPtZBkUQowu1HaHfjKxsykOoiUIMHDd9580P1_Wan3zeGz0tRFRW5dEOszUvTNmL6Z4Piajdk10VpnRBEBSn7">https://www.spyder-ide.org</a></li><li>IDLE — <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></li><li>Pycharm — <a href="https://www.jetbrains.com/pycharm/">https://www.jetbrains.com/pycharm/</a></li><li>Visual Studio Code — <a href="https://visualstudio.microsoft.com/">https://visualstudio.microsoft.com/</a></li><li>Atom — <a href="https://atom.io/">https://atom.io/</a></li></ol><p>If you have started learning Python, i will suggest you to go with Visual Studio Code. But if you are a machine learning developer and need to research using Python, go with Jupyter Notebook or Spyder. You can also install Jupyter Notebook, Spyder and Visual Studio Code from Anaconda IDE.</p><p><strong>How to Start</strong></p><p>Like every programming language (C or Java), there is few things, you need to learn in Python also.</p><ol><li>How to install</li><li>Check if Python is installed and working</li><li>Set Environment variable to access Python</li><li>Basic Python Command and How you can execute your code</li><li>Hello World</li><li>Understand some basic statement for coding</li><li>Variables</li><li>Operators</li><li>Functions</li><li>Conditional Statements</li><li>Loop</li><li>Class</li></ol><p><strong>How To Install</strong></p><p>Like every software you have to download an IDE (I will recommend to use Visual Studio Code, if you are starting). Go with above given URL and Download your IDE. Some IDE need to install Python Separately, that you can download from <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a>.</p><p>While downloading, If you see an option to add Python to Environment Variable, Choose it, so you no need to setup Environment Variable separatly for your Python and You can access Python from anywhere in your system using console.</p><p><strong>Check if Python is installed and working</strong></p><p>To check, If your Python is installed, You need to Open Command Prompt (In Windows) or Terminal (In Linux or Mac) and Type <strong><em>python — version</em></strong> (version with double dash). If you have installed Python third version then you need to type <strong><em>python3 — version</em></strong>, to check python version. So try both comamnd if getting error at any of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uJGyqXu46r6ewtzRCAfyQ.png" /><figcaption>Here in this image, By default my system has installed Python 3, so python command is working. If i had multiple version of Python installed, i need to type python3 — version to know python3 version and python for python2 version. I don’t need Python3 command here. My system has already installed Python 3.9.5 as default Python.</figcaption></figure><p><strong>Set Environment variable to access Python</strong></p><p>If you have already installed Python, but above given command returns blank, you need to set Environment variable for Python in your PC.</p><p>For that in windows, right click on <strong><em>THE PC or MY COMPUTER</em></strong>, then go to <strong><em>Advance System Settings</em></strong>. It will open a <strong><em>System Properties window</em></strong>. Here select <strong><em>Advance</em></strong> Tab (if not selected already), and click on <strong><em>Environment Variables</em></strong> button. IT will open an another window, where in <strong><em>System variable</em></strong> section, search and select Path and click on Edit. It will open another window with name Edit environment variable. Click on New button and <strong><em>add Python and Python Script folder in list</em></strong>.</p><p>As per my PC, this is my Python path:</p><p>C:\Users\ntshv\AppData\Local\Programs\Python\Python39</p><p>C:\Users\ntshv\AppData\Local\Programs\Python\Python39\Scripts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_h9iRMYSOIR5UCXrotLgA.png" /><figcaption>Environmental variable in windows 10</figcaption></figure><p>Same you can do for setup JDK environment variable, if learning Java. Just you need to add JDK’s bin path here.</p><p><strong>Basic Python Command and How you can execute your code</strong></p><p>Start with basic, no need to make Iron Man Suit now.</p><p>Console is right tool to start. Open Command Prompt (Terminal). enter python and press Enter key. In next second, you will be in python environment. It will look like below image,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ug5Ep7mVlJyvhTEN_RS3Yw.png" /><figcaption>Python Console</figcaption></figure><p>now try to write basic command, like add two numbers. Don’t think about programming. Just go with basic.</p><p>&gt;&gt;&gt; 2+2</p><p>4</p><p>To print something in console, you can use <strong><em>print()</em></strong> function and To enter input from keyboard, you can use <strong><em>input()</em></strong> function. See in below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDiO4ebljTD9YC4ktGSvOA.png" /><figcaption>Try these commands in your console</figcaption></figure><p><strong>Hello World</strong></p><p>Now, console is not a good way for write program, if you are a developer. So we will learn our next step using any IDE. In my case, i will use Visual Studio Code. It is most used IDE today.</p><p>Now, you know what is Hello World. everyones first program. So,good way to start learning code is to save file somewhere with meaningful name. Create a folder in your drive, and open Visual studio code on that folder. In current Windows OS, you can find Visual studio Code at right click on blank space. Or enter <strong><em>cmd</em></strong> in address bar of the folder and when Command Prompt will open on that folder, enter <strong><em>code .</em></strong> (dot) to open Visual Studio Code.</p><p>In linux terminal, You can normally open Visual Studio Code, by entering <strong><em>code .</em></strong> or<strong><em> sudo code . — user-data-dir</em></strong>.</p><p>Next, when editor will open, create a file with extension <strong><em>.py</em></strong>. In my case, i have created <strong><em>helloworld.py</em></strong>. You can name anything you want. And write a normal statement in that file. As here, i have written print(“Hello World”). Save the file and open terminal from main menu (or you can also use your console).</p><p>In terminal, write command python, then space and then name of the file with .py extension. Here, <strong><em>python helloworld.py.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nVvVbN-hyoHbVSzscIsAA.png" /><figcaption>Here, you can see, how i have printed Hello World</figcaption></figure><p>Now, try to write code with the right way using function, check the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*IwOwZJhKN7pKjmycVvrzvA.png" /><figcaption>You can see below output is for this statement</figcaption></figure><p>Now, try with __name__.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*uzLnNj5HfFdtPGju3_jGHw.png" /><figcaption>Check output for this code, below in terminal</figcaption></figure><p><strong>Understand some basic statement for coding</strong></p><p>When you are writting code, you need to understand basic of coding, like how to print output, what to print in output, how to get input from keyboard, how to store and print input data, what is fuction and how to use functions. We will touch fucntions later, so now talk about Input, Output.</p><p>In python, you can use <strong><em>print()</em></strong> function to print any text in console. In real project, print() is just use for print debugging messages in console. Now, just go with console programming, but not real project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3aeDPTaRgqnregMYhL9brQ.png" /></figure><p>In above image. I have printed Hello World in many ways. print(“Hello World”) or print(“Hello”, “World”) or print(“Hello”, “World”, 3). Print statement can contains multiple arguments, with different data types. Like in statement, print(“Nice to meet you”, name) or print(name), you can also print whatever variable contains. But in below two statement is not printing console but just saying what i have entered. It will only work on console, not in file. If you will not write print() in python file, It can’t print message, as given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*bH2ygEdYSKO825EyTVALLw.png" /><figcaption>name “Nitish” is not showing in terminal</figcaption></figure><p>Now, same code is printing message after using print() in below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*cv-Tep0sK0K5oodKPfmIYA.png" /><figcaption>message Nitish stored in name variable is showing on terminal</figcaption></figure><p>You can also print output in multiple line, using three single quotes as below given example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*jgAveC37pNVHdD7mt2kaEg.png" /></figure><p>You can also enter keyboard input, using input() statement and store whatever you have entered in a variable like below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*GSJD8AENHdty-K6Q5nA7WQ.png" /><figcaption>Here, in this image. Program first asked for Enter your name, and then i entered my name i.e. Nitish, which stored in name variable when i press Enter button, as below terminal output and using print statement, i printed Nice to meet you, Nitish. where nitish is stored in name variable.</figcaption></figure><p>In above example, i have written, print(“Nice to meet you, “, name). name variable after a space, why?</p><p>You can concatinate two string using + sign. If i will not provided space after comma (,), name should look like this and attached with comma (,Nitish). Same in input statement, so i can write my name separate with space. <em>Try without giving space.</em></p><p><strong>Variables</strong></p><p>There is no datatype issue in python to declare a variable.</p><p>Declare a variable: f = 0</p><p>Redeclare same variable: f = “abc”, you will not get error.</p><p>for decalring a variable you no need to write datatypes like int f =0 or string f = “abc”. Python can manage their memory itself.</p><p>Yes, you can’t concatinate string with integer type. Like print(“My age is “, 33). You will get TypeError, that, string can only concatinate string. So same statement you can write like this, print(“My age is “ + str(age)), if age = 33.</p><ul><li>You can cast string to int using int(“33”)</li><li>You can cast int to string using str(33) and same for float and others</li></ul><p>You can delete a variable from memory, using del statement. like <strong><em>del age</em></strong>. After this statement, if you will try to read <strong><em>age</em></strong> again, you will face error.</p><p><strong>Operators</strong></p><p>Operator in Python is same as C or Java. Just, as i know, there is no increament/decreament operator. Instead of ++ or — you can use x = x+1 or x=+1 and same for subtract with minus sign (Same as arithematic operator).</p><p>And for Ternary operator (condition?true: false), you can use single line conditional statement. Will will look at this on next section.</p><p>Local variable: Can’s access outside boundry</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*l3CdU2vhyxh-Fo3-1Zw3Yw.png" /></figure><p>Global Variable: Can be access anywhere</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*2FlI5sDA1xIhRxi7poh6aA.png" /></figure><p><strong>Functions</strong></p><p>A function in Python can be declared by def statement. It may have arguments or may not, It can return value or may not. So we will go with all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i743cUk3Q1atP6nshVM9gg.png" /><figcaption>as in red text, you can also describe your function in multiple comment</figcaption></figure><p>‘’’ : three single quotes used for multiple comment. You can also print something on print() on multiple line as above see.</p><p># : is used for single line comment in python</p><p>On the above example,</p><ul><li>def is used to declare function</li><li>funct1 is name of function</li><li>a and b is two parameter, where b has default value 1. You can use default value if there is a chance for user not mendatory to enter value for some argument.</li><li>return a+b is return statement to return sum of a and b</li></ul><p><em>Returning Multiple Value:</em></p><p>In Python you can also return multiple value from a function. You just need to write those variable with return statement and while calling you also need to call variable for all of those (as in my example there is two variable a and b in line 12 and 19).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*5MFjRSwJo_g2a9qStRKvOQ.png" /></figure><p><em>Function with number of arguments:</em></p><p>You can use * to define multiple arguments using one variable, as exmple in image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*6GwRrKSzlk8heBBWxNlmnQ.png" /><figcaption>Here i have called only two value from arguments, so if you will change number of argument, it will read only first two argument from arraya and if there is only one argument, you will face error. Try funct(3,2,2,2) or funct(3). So better use loop for this, as example below.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*9vOMJzV5voRa-6LTjG0UcA.png" /><figcaption>Same function with different arguments</figcaption></figure><p>Above example with key:</p><p>You can also use above example with keys and call them in function with key name. You just need to use ** (double astrik).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*P-BDy_6OSXGq4C2dqnUn_A.png" /></figure><p><strong>Conditional Statements</strong></p><p>In Python, you can write condition using if else statement. There is two types of if else statement, multiline or single line.</p><p>Multiline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*z5C5wpCOE_Xgu2jFyREvdg.png" /><figcaption>Multiline conditional statement</figcaption></figure><p>Same code in single line</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ixG-ZbzjsX__TAKmN-3rg.png" /><figcaption>Singleline conditional statement</figcaption></figure><p><strong>Loop</strong></p><p>Loop is used to iterate some statement multiple times based on given condition, so you no need to write same statement multiple times. Even it is very difficult when you don’t know how much times you need to iterate your statements. Think like reading data from database, where you do not have idea, how much row that table/ collections has contains. Might be in your company, you have 500 employees, in another company they have different number of employees, you can’t write static code. In that case we can use loop.</p><p>There is many types of loops in programming languages, like while, do-while, for, foreach. But, Python has only two types of loop, i.e. while and for loop.</p><p><em>Example of while:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*rPVxn_gY7IcV5wGs2_q7Vw.png" /><figcaption>Remember, there is no increment/ decrement operator in Python. So use assignment operator</figcaption></figure><p><em>Example of For Loop:</em></p><p>For loop you can use to iterate list, set, dict etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*7nEMAO1T48B8L3VCn-79yA.png" /><figcaption>Example without index</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*vcgxHK1a-pADgBUH6PR2fQ.png" /><figcaption>Example with index, named i</figcaption></figure><p>Range:</p><p>Range statement you can use to execute numbers, between some range. It contains three integer arguments start, stop and step, where step has default value 1.</p><p>range(start, stop, step=1)</p><p>So, if your statement is range(1, 10), then output will be 1,2,3,4,5,6,7,8,9 (before 10). If your statement is range(1,10,2), then output will be 1,3,5,7,9.</p><p>If you want to write range in reverse order, write range(10,0,-1). Here output will be 10 to 1 in reverse order. Just manage the step value and check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*9S3JIGuAyV_Kfe_OawOUxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*62dJ5qSUye69GQLHdMf3AQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*YfRQ88BfA6-gxkNzutfiGg.png" /><figcaption>Example of range in different order</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*4EsVhcUa8iUEWbjSxjPRCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*y9WYgU8hemi4ZAtsiAJTTA.png" /></figure><p>Try this with different values and check what’s happening.</p><p><em>Break:</em></p><p>As java and C, in Python also <em>break </em>keyword is used to break the running loop, if given condition becomes true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*OruPj4PU3xnHYw-vKoWp7A.png" /><figcaption>In this example, loop break when condition becomes true</figcaption></figure><p>Continue:</p><p><em>continue</em> keyword is used to pass running step to next step of the loop, when condition becomes true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*JxmQR6l-XiXP4vT3OAE4sA.png" /><figcaption>In this example, when i == 3, continue statement pass the loop to next step, without printing 3. Like break, it doesn’t break and stop the loop, it just pass for the next step.</figcaption></figure><p><strong>Substring of array</strong></p><p>You can think about any types of array, string as character array, list, dict etc. In Python there is easy way to substring a list or string, using [:]. Logic is same as range.</p><p>str = “this is a string”</p><p>print( str[0:4] ) # outputs ‘this’</p><p>print( str[0:4:2] ) # outputs ‘ti’</p><p>a = [1,2,3,4,5,6]</p><p>print( a[0:4] ) # outputs [1,2,3,4]</p><p>print( a[1:4] ) # outputs [2,3,4]</p><p>print( a[6:0:-1] ) # outputs [6,5,4,3,2]</p><p>Try as much you can.</p><p><strong>Class</strong></p><p>Class is a big thing to understand, till you will not understand why and where and how to use this. I will write details on class in python in another article. Here is just an small example of class in python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*PCTG8cGkmR2OS3cOIp_tqw.png" /><figcaption>Example of Class</figcaption></figure><p>Above is a basic example of class. You can initialize an object, like i have done in line number 8 and call class members using that object as i have done in line number 9.</p><p>As you can see, in line number 3, i have passed one argument self. Always remember, first argument of class functions is always its instance. same in line 5 i have called continue_contrl variable with self. Without self you can’t access class member.</p><p>(as geeksforgeeks)</p><p><strong><em>self</em></strong><em> represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.<br>The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.</em></p><p><em>Self is always pointing to Current Object.</em></p><p>We will talk about class in another article. If you think anything wrong here, or i need to describe more, you can comment here. But this article i only have written to understande basic. After this you can find details in many Python ebooks, so you can understand easily.</p><p><em>(Sorry for grammatical mistakes)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edd5ec6845e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/basic-of-python-edd5ec6845e5">Basic Of Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>