<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python Programs</title>
	<atom:link href="https://python-programs.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://python-programs.com</link>
	<description>Python Programs with Examples, How To Guides on Python</description>
	<lastBuildDate>Fri, 10 Jul 2026 05:56:39 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.4</generator>
<site xmlns="com-wordpress:feed-additions:1">196068054</site>	<item>
		<title>Basics of Python – Built-in Types</title>
		<link>https://python-programs.com/basics-of-python-built-in-types/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Jul 2026 11:44:29 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=2838</guid>

					<description><![CDATA[In this Page, We are Providing Basics of Python – Built-in Types. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf. Basics of Python – Built-in Types Built-in types This section describes the standard data types that are built into the interpreter. There are various built-in data types, for e.g., numeric, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this Page, We are Providing Basics of Python – Built-in Types. Students can visit for more Detail and Explanation of <a href="https://python-programs.com/python-handwritten-notes/">Python Handwritten Notes</a> Pdf.</p>
<h2>Basics of Python – Built-in Types</h2>
<p><strong>Built-in types</strong></p>
<p>This section describes the standard data types that are built into the interpreter. There are various built-in data types, for e.g., numeric, sequence, mapping, etc., but this book will cover few types. Schematic representation of various built-in types is shown in figure 2-1.</p>
<p><img fetchpriority="high" decoding="async" class="alignnone wp-image-2839 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Python-ch2-img-1.png" alt="Python Handwritten Notes Chapter 2 img 1" width="564" height="738" srcset="https://python-programs.com/wp-content/uploads/2021/04/Python-ch2-img-1.png 564w, https://python-programs.com/wp-content/uploads/2021/04/Python-ch2-img-1-229x300.png 229w" sizes="(max-width: 564px) 100vw, 564px" /></p>
<p><strong>Numeric types</strong></p>
<p>There are three distinct numeric types: integer, floating-point number, and complex number.</p>
<p><strong>Integer</strong></p>
<p>Integer can be sub-classified into three types:</p>
<p><strong>Plain integer</strong></p>
<p>Plain integer (or simply &#8221; integer &#8220;) represents an integer number in the range -2147483648 through 2147483647. When the result of an operation would fall outside this range, the result is normally returned as a long integer.</p>
<pre>&gt;&gt;&gt; a=2147483647 
&gt;&gt;&gt; type (a) 
&lt;type ' int '&gt;
&gt;&gt;&gt; a=a+1
&gt;&gt;&gt; type (a)
&lt;type ' long '&gt;
&gt;&gt;&gt; a=-2147483648 
&gt;&gt;&gt; type (a)
&lt;type ' int '&gt;
&gt;&gt;&gt; a=a-1
&gt;&gt;&gt; type (a)
&lt;type ' long ’&gt;</pre>
<p>The built-in function int(x = 0) converts a number or string x to an integer or returns 0 if no arguments are given.</p>
<pre>&gt;&gt;&gt; a =' 57 '
&gt;&gt;&gt; type (a) 
&lt;type ' str '&gt;
&gt;&gt;&gt; a = int (a)
&gt;&gt;&gt; a 
57
&gt;&gt;&gt; type (a)
&lt;type ' int '&gt;
&gt;&gt;&gt; a = 5.7
&gt;&gt;&gt; type (a)
&lt;type ' float '&gt; 
&gt;&gt;&gt; a = int (a)
&gt;&gt;&gt; a 
5 
&gt;&gt;&gt; type (a)
&lt;type ' int '&gt;
&gt;&gt;&gt; int( )
0</pre>
<p><strong>Long integer</strong></p>
<p>This represents integer numbers in a virtually unlimited range, subject to available memory. The built-in function long (x=0) converts a string or number to a long integer. If the argument is a string, it must contain a possibly signed number. If no argument is given, OL is returned.</p>
<pre>&gt;&gt;&gt; a = 5 
&gt;&gt;&gt; type (a) 
&lt;type ' int '&gt; 
&gt;&gt;&gt; a = long (a) 
&gt;&gt;&gt; a 
5L
&gt;&gt;&gt; type (a) 
&lt;type ' long '&gt; 
&gt;&gt;&gt; long ( )
OL
&gt;&gt;&gt; long (5)
5L
&gt;&gt;&gt; long (5.8) 
5L
&gt;&gt;&gt; long(' 5 ') 
5L
&gt;&gt;&gt; long(' -5 ')
-5L</pre>
<p>Integer literals with an L or 1 suffix yield long integers (L is preferred because 11 looks too much like eleven).</p>
<pre>&gt;&gt;&gt; a=10L 
&gt;&gt;&gt; type (a) 
&lt;type ' long '&gt;
&gt;&gt;&gt; a=101 
&gt;&gt;&gt; type (a)
&lt;type ' long '&gt;</pre>
<p>The following expressions are interesting.</p>
<pre>&gt;&gt;&gt; import sys 
&gt;&gt;&gt; a=sys.maxint 
&gt;&gt;&gt; a
2147483647
&gt;&gt;&gt; type (a)
&lt;type ' int '&gt;
&gt;&gt;&gt; a=a+1
&gt;&gt;&gt; a
21474836 48L
&gt;&gt;&gt; type (a)
&lt;type ' long ’&gt;</pre>
<p><strong>Boolean</strong></p>
<p>This represents the truth values False and True. The boolean type is a sub-type of plain integer, and boolean values behave like the values 0 and 1. The built-in function bool ( ) converts a value to boolean, using the standard truth testing procedure.</p>
<pre>&gt;&gt;&gt; bool ( ) 
False 
&gt;&gt;&gt; a=5
&gt;&gt;&gt; bool (a)
True
&gt;&gt;&gt; bool (0)
False
&gt;&gt;&gt; bool( ' hi ' )
True
&gt;&gt;&gt; bool(None)
False
&gt;&gt;&gt; bool(' ')
False
&gt;&gt;&gt; bool(False)
False
&gt;&gt;&gt; bool("False" )
True
&gt;&gt;&gt; bool(5 &gt; 3)
True</pre>
<p><strong>Floating point number</strong></p>
<p>This represents a decimal point number. Python supports only double-precision floating-point numbers (occupies 8 bytes of memory) and does not support single-precision floating-point numbers (occupies 4 bytes of memory). The built-in function float  ( ) converts a string or a number to a floating-point number.</p>
<pre>&gt;&gt;&gt; a = 57 
&gt;&gt;&gt; type (a)
&lt;type ' int '&gt;
&gt;&gt;&gt; a = float (a)
&gt;&gt;&gt; a
57.0 
&gt;&gt;&gt; type (a)
&lt;type ' float '&gt;
&gt;&gt;&gt; a = ' 65 ' 
&gt;&gt;&gt; type (a)
&lt;type ' str ' &gt; 
&gt;&gt;&gt; a = float (a) 
&gt;&gt;&gt; a
65.0 
&gt;&gt;&gt; type (a)
&lt;type ' float '&gt;
&gt;&gt;&gt; a = 1e308 
&gt;&gt;&gt; a 
1e+30 8 
&gt;&gt;&gt; type (a)
&lt;type ' float '&gt;
&gt;&gt;&gt; a = 1e309 
&gt;&gt;&gt; a
inf 
&gt;&gt;&gt; type (a)
&lt;type ' float '&gt;</pre>
<p><strong>Complex number</strong></p>
<p>This represents complex numbers having real and imaginary parts. The built-in function complex () is used to convert numbers or strings to complex numbers.</p>
<pre>&gt;&gt;&gt; a = 5.3
&gt;&gt;&gt; a = complex (a)
&gt;&gt;&gt; a 
(5 . 3 + 0 j)
&gt;&gt;&gt; type (a)
&lt;type ' complex '&gt;
&gt;&gt;&gt; a = complex ( )
&gt;&gt;&gt; a
0 j 
&gt;&gt;&gt; type (a)
&lt;type ' complex '&gt;</pre>
<p>Appending j or J to numeric literal yields a complex number.</p>
<pre>&gt;&gt;&gt; a = 3 . 4 j 
&gt;&gt;&gt; a 
3 . 4 j
&gt;&gt;&gt; type (a)
&lt;type ' complex '&gt;
&gt;&gt;&gt; a = 3 . 5 + 4 . 9 j 
&gt;&gt;&gt; type (a)
&lt;type ' complex '&gt;
&gt;&gt;&gt; a = 3 . 5+4 . 9 J
&gt;&gt;&gt; type (a)
&lt;type ' complex '&gt;</pre>
<p>The real and imaginary parts of a complex number z can be retrieved through the attributes z. real and z. imag.</p>
<pre>a=3 . 5 + 4 . 9 J
&gt;&gt;&gt; a . real
3 . 5
&gt;&gt;&gt; a . imag 
4 . 9</pre>
<p><strong>Sequence Types</strong></p>
<p>These represent finite ordered sets, usually indexed by non-negative numbers. When the length of a sequence is n, the index set contains the numbers 0, 1, . . ., n-1. Item i of sequence a is selected by a [i]. There are seven sequence types: string, Unicode string, list, tuple, bytearray, buffer, and xrange objects.</p>
<p>The sequence can be mutable or immutable. The immutable sequence is a sequence that cannot be changed after it is created. If an immutable sequence object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change. The mutable sequence is a sequence that can be changed after it is created. There are two intrinsic mutable sequence types: list and byte array.</p>
<p>Iterable is an object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like diet and file, etc. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map (), &#8230;). When an iterable object is passed as an argument to the built-in function iter (), it returns an iterator for the object. An iterator is an object representing a stream of data; repeated calls to the iterator&#8217;s next () method return successive items in the stream. When no more data are available, a Stoplteration exception is raised instead.</p>
<p>Some of the sequence types are discussed below:</p>
<p><strong>String</strong></p>
<p>It is a sequence type such that its value can be characters, symbols, or numbers. Please note that string is immutable.</p>
<pre>&gt;&gt;&gt; a=' Python : 2 . 7 '
&gt;&gt;&gt; type (a)
&lt;type ' str ’&gt;
&gt;&gt;&gt; a [2 ] =' S '
Traceback (most recent call last) :
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: 'str' object does not support item assignment</pre>
<p>The built-in function str (object =&#8217; &#8216; ) returns a string containing a nicely printable representation of an object. For strings, this returns the string itself. If no argument is given, an empty string is returned.</p>
<pre>&gt;&gt;&gt; a=57.3
&gt;&gt;&gt; type(a) 
&lt;type 'float'&gt;
&gt;&gt;&gt; a=str(a)
&gt;&gt;&gt; a
' 57.3 '
&gt;&gt;&gt; type (a)
&lt;type ' str '&gt;</pre>
<p><strong>Tuple</strong></p>
<p>A tuple is a comma-separated sequence of arbitrary Python objects enclosed in parenthesis (round brackets). Please note that the tuple is immutable. A tuple is discussed in detail in chapter 4.</p>
<pre>&gt;&gt;&gt; a=(1 , 2 , 3 ,4) 
&gt;&gt;&gt; type (a)
&lt;type ' tuple '&gt;
'a', 'b', 'c')</pre>
<p><strong>List</strong></p>
<p>The list is a comma-separated sequence of arbitrary Python objects enclosed in square brackets. Please note that list is mutable. More information on the list is provided in chapter 4.</p>
<pre>&gt;&gt;&gt; a=[1, 2 ,3, 4]
&gt;&gt;&gt; type(a) 
&lt;type ' list '&gt;</pre>
<p><strong>Set types</strong></p>
<p>These represent an unordered, finite set of unique objects. As such, it cannot be indexed by any subscript, however, they can be iterated over. Common uses of sets are fast membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. There are two set types:</p>
<p><strong>Set</strong></p>
<p>This represents a mutable set. It is created by the built-in function set (), and can be modified afterward by several methods, such as add () remove (), etc. More information on the set is given in chapter 4.</p>
<pre>&gt;&gt;&gt; set1=set ( )                                                    # A new empty set
&gt;&gt;&gt; set1.add (" cat ")                                           # Add a single member
&gt;&gt;&gt; set1.update ([" dog "," mouse "])                 # Add several members
&gt;&gt;&gt; set1.remove ("mouse")                                # Remove member
&gt;&gt;&gt; set1
set([' dog ', ' cat '])
&gt;&gt;&gt; set2=set([" dog "," mouse "])
&gt;&gt;&gt; print set1&amp;set2                                           # Intersection
set ( [' dog ' ] )
&gt;&gt;&gt; print set1 | set2                                           # Union
set([' mouse ', ' dog ', ' cat '])</pre>
<p>The set ( [ iterable ] ) return a new set object, optionally with elements taken from iterable.</p>
<p><strong>Frozenset</strong></p>
<p>This represents an immutable set. It is created by a built-in function frozenset ( ). As a frozenset is immutable, it can be used again as an element of another set, or as a dictionary key.</p>
<pre>&gt;&gt;&gt; frozenset ( ) 
frozenset ( [ ] )
&gt;&gt;&gt; frozenset (' aeiou ') 
frozenset{ [' a ', ' i ',' e ',' u ',' o '])
&gt;&gt;&gt; frozenset ( [0, 0, 0, 44, 0, 44, 18] ) 
frozenset (10, 18, 44])</pre>
<p>The frozenset ( [iterable] ) return return a new frozenset object, optionally with elements taken from iterable.</p>
<p><strong>Mapping Types</strong></p>
<p>This represents a container object that supports arbitrary key lookups. The notation a [k] selects the value indexed by key k from the mapping a; this can be used in expressions and as the target of assignments or del statements. The built-in function len () returns the number of items in a mapping. Currently, there is a single mapping type:</p>
<p><strong>Dictionary</strong></p>
<p>A dictionary is a mutable collection of unordered values accessed by key rather than by index. In the dictionary, arbitrary keys are mapped to values. More information is provided in chapter 4.</p>
<pre>&gt;&gt;&gt; dict1={"john":34,"mike":56}
&gt;&gt;&gt; dict1[" michael "] = 42 
&gt;&gt;&gt; dict1
{' mike ' : 56, ' john ' : 34, ' michael ' : 42}
&gt;&gt;&gt; dictl[" mike "]
56</pre>
<p><strong>None</strong></p>
<p>This signifies the absence of a value in a situation, e.g., it is returned from a function that does not explicitly return anything. Its truth value is False.</p>
<p>Some other built-in types such as function, method, class, class instance, file, module, etc. are discussed in later chapters.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2838</post-id>	</item>
		<item>
		<title>Python Check If there are Duplicates in a List</title>
		<link>https://python-programs.com/python-check-if-there-are-duplicates-in-a-list/</link>
		
		<dc:creator><![CDATA[Vikram Chiluka]]></dc:creator>
		<pubDate>Thu, 09 Jul 2026 10:35:07 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=2833</guid>

					<description><![CDATA[Lists are similar to dynamically sized arrays (e.g., vector in C++ and ArrayList in Java) that are declared in other languages. Lists don&#8217;t always have to be homogeneous, which makes them a useful tool in Python. Integers, Strings, and Objects are all DataTypes that can be combined into a single list. Lists are mutable, meaning [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Lists are similar to dynamically sized arrays (e.g., vector in C++ and ArrayList in Java) that are declared in other languages. Lists don&#8217;t always have to be homogeneous, which makes them a useful tool in Python. Integers, Strings, and Objects are all DataTypes that can be combined into a single list. Lists are mutable, meaning they can be modified after they&#8217;ve been formed.</p>
<p>Duplicates are integers, strings, or items in a list that are repeated more than once.</p>
<p>Given a list, the task is to check whether it has any duplicate element in it.</p>
<p><strong>Examples:</strong></p>
<p><strong>Input:</strong></p>
<pre>givenlist=["hello", "this", "is", "BTechGeeks" , "hello"]</pre>
<p><strong>Output:</strong></p>
<pre>True</pre>
<p><strong>Explanation:</strong></p>
<pre>hello is repeated twice so the answer is Yes</pre>
<h2>Check whether list contains any repeated values</h2>
<p>There are several ways to check duplicate elements some of them are:</p>
<ul>
<li><a href="#Using_list_and_count()_function">Using list and count() function</a></li>
<li><a href="#Using_set()">Using set()</a></li>
<li><a href="#Using_Counter()_function_from_collections_(Hashing)">Using Counter() function from collections (Hashing)</a></li>
</ul>
<h3 id="Using_list_and_count()_function">Method #1 :Using list and count() function</h3>
<p>The list class in Python has a method count() that returns the frequency count of a given list element.</p>
<p><code class="EnlighterJSRAW" data-enlighter-language="python">list.count(Element)</code></p>
<p>It returns the number of times an element appears in the list.</p>
<p><strong>Approach:</strong></p>
<p>The idea is to iterate over all of the list&#8217;s elements and count the number of times each element appears.</p>
<p>If the count is greater than one, this element has duplicate entries.</p>
<p>Below is the implementation:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># function which return true if duplicates are present in list else false
def checkDuplicates(givenlist):
    # Traverse the list
    for element in givenlist:
        # checking the count/frequency of each element
        if(givenlist.count(element) &gt; 1):
            return True
    # if the above loop do not return anuthing then there are no duplicates
    return False

#Driver code
# Given list
givenlist = ["hello", "this", "is", "BTechGeeks", "hello"]
# passing this list to checkDuplicates function
print(checkDuplicates(givenlist))

</pre>
<p><strong>Output:</strong></p>
<pre>True</pre>
<p><strong>Time Complexity :</strong> <strong>O(n^2)</strong></p>
<h3 id="Using_set()">Method #2 : Using set()</h3>
<p>Follow the steps below to see if a list contains any duplicate elements.</p>
<p>If the list does not contain any unhashable objects, such as list, use set().</p>
<p>When a list is passed to set(), the function returns set, which ignores duplicate values and keeps only unique values as elements..</p>
<p>Using the built-in function len(), calculate the number of elements in this set and the original list and compare them.</p>
<p>If the number of elements is the same, there are no duplicate elements in the original list ,if the number of elements is different, there are duplicate elements in the original list.</p>
<p>The following is the function that returns False if there are no duplicate elements and True if there are duplicate elements:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># function which return true if duplicates are present in list else false
def checkDuplicates(givenlist):
    # convert given list to set
    setlist = set(givenlist)
    # calculate length of set and list
    setlength = len(setlist)
    listlength = len(givenlist)
    # return the comparision between set length and list length
    return setlength != listlength


# Driver code
# Given list
givenlist = ["hello", "this", "is", "BTechGeeks", "hello"]
# passing this list to checkDuplicates function
print(checkDuplicates(givenlist))
</pre>
<p><strong>Output:</strong></p>
<pre>True</pre>
<p><strong>Time Complexity : </strong>O(n(log(n))</p>
<h3 id="Using_Counter()_function_from_collections_(Hashing)">Method #3: Using Counter() function from collections (Hashing)</h3>
<p>Calculate the frequencies of all elements using Counter() function which will be stored as frequency dictionary.</p>
<p>If the length of frequency dictionary is equal to length of list then it has no duplicates.</p>
<p>Below is the implementation:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># importing Counter function from collections
from collections import Counter

# function which return true if duplicates are present in list else false


def checkDuplicates(givenlist):
    # Calculating frequency using counter() function
    frequency = Counter(givenlist)
    # compare these two lengths and return it
    return len(frequency) != len(givenlist)


# Driver code
# Given list
givenlist = ["hello", "this", "is", "BTechGeeks", "hello"]
# passing this list to checkDuplicates function
print(checkDuplicates(givenlist))
</pre>
<p><strong>Output:</strong></p>
<pre>True</pre>
<p><strong>Time Complexity : </strong>O(n)<br />
<strong>Related Programs</strong>:</p>
<ul>
<li><a href="https://python-programs.com/python-check-if-all-elements-in-a-list-are-same-or-matches-a-condition/">python check if all elements in a list are same or matches a condition</a></li>
<li><a href="https://python-programs.com/check-if-all-elements-in-a-list-are-none-in-python/">check if all elements in a list are none in python</a></li>
<li><a href="https://python-programs.com/python-check-if-all-values-are-same-in-a-numpy-array-both-1d-and-2d/">python check if all values are same in a numpy array both 1d and 2d</a></li>
<li><a href="https://python-programs.com/python-check-if-a-value-exists-in-the-dictionary/">python check if a value exists in the dictionary</a></li>
<li><a href="https://python-programs.com/python-how-to-check-if-a-key-exists-in-dictionary/">python how to check if a key exists in dictionary</a></li>
<li><a href="https://python-programs.com/python-how-to-check-if-an-item-exists-in-list/">python how to check if an item exists in list</a></li>
<li><a href="https://python-programs.com/check-if-type-of-a-variable-is-string-in-python/">check if type of a variable is string in python</a></li>
</ul>
<p><strong>Related Programs</strong>:</p>
<ul>
<li><a href="https://python-programs.com/python-check-if-all-elements-in-a-list-are-same-or-matches-a-condition/">python check if all elements in a list are same or matches a condition</li>
<li><a href="https://python-programs.com/check-if-all-elements-in-a-list-are-none-in-python/">check if all elements in a list are none in python</li>
<li><a href="https://python-programs.com/python-check-if-all-values-are-same-in-a-numpy-array-both-1d-and-2d/">python check if all values are same in a numpy array both 1d and 2d</li>
<li><a href="https://python-programs.com/python-check-if-a-value-exists-in-the-dictionary/">python check if a value exists in the dictionary</li>
<li><a href="https://python-programs.com/python-how-to-check-if-a-key-exists-in-dictionary/">python how to check if a key exists in dictionary</li>
<li><a href="https://python-programs.com/python-how-to-check-if-an-item-exists-in-list/">python how to check if an item exists in list</li>
<li><a href="https://python-programs.com/check-if-type-of-a-variable-is-string-in-python/">check if type of a variable is string in python</li>
</ul>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2833</post-id>	</item>
		<item>
		<title>Basics of Python – Line Structure</title>
		<link>https://python-programs.com/basics-of-python-line-structure/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Jul 2026 09:11:11 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=2828</guid>

					<description><![CDATA[In this Page, We are Providing Basics of Python – Line Structure. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf. Basics of Python – Line Structure Line structure A Python program is divided into a number of logical lines. Physical and logical lines A physical line is a sequence of [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this Page, We are Providing Basics of Python – Line Structure. Students can visit for more Detail and Explanation of <a href="https://python-programs.com/python-handwritten-notes/">Python Handwritten Notes</a> Pdf.</p>
<h2>Basics of Python – Line Structure</h2>
<p><strong>Line structure</strong></p>
<p>A Python program is divided into a number of logical lines.</p>
<p><strong>Physical and logical lines</strong></p>
<p>A physical line is a sequence of characters terminated by an end-of-line sequence. The end of a logical line is represented by the token NEWLINE. A logical line is ignored (i.e. no NEWLINE token is generated) that contains only spaces, tabs, or a comment. This is called a &#8220;blank line&#8221;. The following code</p>
<pre>&gt;&gt;&gt; i=5 
&gt;&gt;&gt; print (5)
5</pre>
<p>is the same as:</p>
<pre>&gt;&gt;&gt; i=5; print (i)
5</pre>
<p>A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.</p>
<p><strong>Explicit line joining</strong></p>
<p>Two or more physical lines may be joined into logical lines using backslash characters (\), as shown in the following example:</p>
<pre>&gt;&gt;&gt; if 1900 &lt; year &lt; 2100 and 1 &lt;= month &lt;= 12 \
. . .   and 1 &lt;= day &lt;= 31 and 0 &lt;= hour &lt; 24 \
. . .   and 0 &lt;= minute &lt; 60 and 0 &lt;= second &lt; 60 :
. . .   print year</pre>
<p>A line ending in a backslash cannot carry a comment. Also, backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.</p>
<pre>&gt;&gt;&gt; str=' This is a \
. . .    string example ' 
&gt;&gt;&gt; str
' This is a string example'</pre>
<p><strong>Implicit line joining</strong></p>
<p>Expressions in parentheses, square brackets, or curly braces can be split over more than one physical line without using backslashes. For example:</p>
<pre>&gt;&gt;&gt; month_names=['Januari','Februari','Maart',          # These are the
. . .    'April ', ' Mei ', 'Juni',                                              # Dutch names
. . .    'Juli','Augustus','September',                                 # for the months
. . .   'Oktober','November','December']                        # of the year</pre>
<p>Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings; in that case, they cannot carry comments.</p>
<pre>&gt;&gt;&gt; str=" " "This is 
. . . a string 
. . . example" " "
&gt;&gt;&gt; str
' This is \na string \nexample'
&gt;&gt;&gt; str='' 'This is 
. . . a string 
. . . example'' '
&gt;&gt;&gt; str
' This is \na string \nexample'</pre>
<p><strong>Comment</strong></p>
<p>A comment starts with a hash character (#) that is not part of a string literal and terminates at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Also, comments are not executed.</p>
<p><strong>Indentation</strong></p>
<p>Whitespace is important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements. This means that statements that go together must have the same indentation. Each such set of statements is a block. One thing that should be remembered is that wrong indentation can give rise to error (IndentationError exception).</p>
<pre>&gt;&gt;&gt; i=10
&gt;&gt;&gt; print "Value is ",i 
Value is 10 
&gt;&gt;&gt; print "Value is ",i 
File "&lt;stdin&gt;", line 1
print "Value is ",i 
∧
IndentationError: unexpected indent</pre>
<p>The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens. One can observe that inserting whitespace, in the beginning, gave rise to the IndentationError exception.</p>
<p>The following example shows non-uniform indentation is not an error.</p>
<pre>var=100 
&gt;&gt;&gt; if var!=100:
. . .  print 'var does not have value 100'
. . .  else:
. . .                 print 'var has value 100'
. . . 
var has value 100</pre>
<p><strong>Need for indentation</strong></p>
<p>In the C programming language, there are numerous ways to place the braces for the grouping of statements. If a programmer is habitual of reading and writing code that uses one style, he or she will feel at least slightly uneasy when reading (or being required to write) another style. Many coding styles place begin/end brackets on a line by themselves. This makes programs considerably longer and wastes valuable screen space, making it harder to get a good overview of a program.</p>
<p>Guido van Rossum believes that using indentation for grouping is extremely elegant and contributes a lot to the clarity of the typical Python program. Since there are no begin/end brackets, there cannot be a disagreement between the grouping perceived by the parser and the human reader. Also, Python is much less prone to coding-style conflicts.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2828</post-id>	</item>
		<item>
		<title>How to Make a Discord Bot Python</title>
		<link>https://python-programs.com/how-to-make-a-discord-bot-python/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Thu, 09 Jul 2026 08:00:05 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=2407</guid>

					<description><![CDATA[In a world where video games are so important to so many people, communication and community around games are vital. Discord offers both of those and more in one well-designed package. In this tutorial, you’ll learn how to make a Discord bot in Python so that you can make the most of this fantastic platform. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In a world where video games are so important to so many people, communication and community around games are vital. Discord offers both of those and more in one well-designed package. In this tutorial, you’ll learn how to make a Discord bot in Python so that you can make the most of this fantastic platform.</p>
<section id="what-is-discord" class="section2">
<h3>What Is Discord?</h3>
<p>Discord is a voice and text communication platform for gamers.</p>
<p>Players, streamers, and developers use Discord to discuss games, answer questions, chat while they play, and much more. It even has a game store, complete with critical reviews and a subscription service. It is nearly a one-stop shop for gaming communities.</p>
<p>While there are many things you can build using Discord’s APIs this tutorial will focus on a particular learning outcome: how to make a Discord bot in Python.</p>
<div>
<div class="rounded border border-light">
<div></div>
</div>
</div>
</section>
<section id="what-is-a-bot" class="section2">
<h3>What Is a Bot?</h3>
<p>Discord is growing in popularity. As such, automated processes, such as banning inappropriate users and reacting to user requests are vital for a community to thrive and grow.</p>
<p>Automated programs that look and act like users and automatically respond to events and commands on Discord are called bot users. Discord bot users (or just bots) have nearly <a>unlimited application</a>.</p>
<p>How to Make a Discord Bot in the Developer Portal:</p>
<p>Before you can dive into any Python code to handle events and create exciting automations, you need to first create a few Discord components:</p>
<ol>
<li>An account</li>
<li>An application</li>
<li>A bot</li>
<li>A guild</li>
</ol>
<p>You’ll learn more about each piece in the following sections.</p>
<p>Once you’ve created all of these components, you’ll tie them together by registering your bot with your guild.</p>
<h3>Creating a Discord Account</h3>
<p>The first thing you’ll see is a landing page where you’ll need to either login, if you have an existing account, or create a new account:</p>
<p><img decoding="async" class="alignnone wp-image-2572 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account.png" alt="Creating-a-Discord-Account" width="1295" height="591" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account.png 1295w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-300x137.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-1024x467.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-768x350.png 768w" sizes="(max-width: 1295px) 100vw, 1295px" /></p>
<p>If you need to create a new account, then click on the <em>Register</em> button below <em>Login</em> and enter your account information.</p>
<p>Once you’re finished, you’ll be redirected to the Developer Portal home page, where you’ll create your application.</p>
<div>
<div class="rounded border border-light"><img decoding="async" class="alignnone wp-image-2573 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login.png" alt="Creating-a-Discord-Account-login" width="1288" height="544" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login.png 1288w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-300x127.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-1024x432.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-768x324.png 768w" sizes="(max-width: 1288px) 100vw, 1288px" /></div>
</div>
<h3>Creating an Application:</h3>
<p>An application allows you to interact with Discord’s APIs by providing authentication tokens, designating permissions, and so on.</p>
<p>To create a new application, select New Application:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2574 size-large" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-application-1024x470.png" alt="Creating-a-Discord-Account-application" width="1024" height="470" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-application-1024x470.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-application-300x138.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-application-768x352.png 768w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-application.png 1292w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></p>
<p>Next, you’ll be prompted to name your application. Select a name and click <em>Create</em>:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2575 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-creating.png" alt="Creating-a-Discord-Account-login-creating" width="836" height="572" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-creating.png 836w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-creating-300x205.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-creating-768x525.png 768w" sizes="auto, (max-width: 836px) 100vw, 836px" /></p>
<p>Congratulations! You made a Discord application. On the resulting screen, you can see information about your application:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2576 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-done.png" alt="Creating-a-Discord-Account-login-done.png" width="1305" height="541" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-done.png 1305w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-done-300x124.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-done-1024x425.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-Account-login-done-768x318.png 768w" sizes="auto, (max-width: 1305px) 100vw, 1305px" /></p>
<p>Keep in mind that any program that interacts with Discord APIs requires a Discord application, not just bots. Bot-related APIs are only a subset of Discord’s total interface.</p>
<p>However, since this tutorial is about how to make a Discord bot, navigate to the <em>Bot</em> tab on the left-hand navigation list.</p>
<h3>Creating a Bot</h3>
<p>As you learned in the previous sections, a bot user is one that listens to and automatically reacts to certain events and commands on Discord.</p>
<p>For your code to actually be manifested on Discord, you’ll need to create a bot user. To do so, select <em>Add Bot</em>:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2577 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-boat.png" alt="Creating-a-Discord-boat" width="1264" height="606" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-boat.png 1264w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-boat-300x144.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-boat-1024x491.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-boat-768x368.png 768w" sizes="auto, (max-width: 1264px) 100vw, 1264px" /></p>
<p>Once you confirm that you want to add the bot to your application, you’ll see the new bot user in the portal:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2578 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-boat-user.png" alt="Creating-a-Discord-account-new-boat-user" width="1294" height="561" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-boat-user.png 1294w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-boat-user-300x130.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-boat-user-1024x444.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-boat-user-768x333.png 768w" sizes="auto, (max-width: 1294px) 100vw, 1294px" /></p>
<p>Now, the bot’s all set and ready to go, but to where?</p>
<p>A bot user is not useful if it’s not interacting with other users. Next, you’ll create a guild so that your bot can interact with other users.</p>
<h3>Creating a Guild</h3>
<p>A guild (or a server, as it is often called in Discord’s user interface) is a specific group of channels where users congregate to chat.</p>
<p>You’d start by creating a guild. Then, in your guild, you could have multiple channels, such as:</p>
<ul>
<li>General Discussion: A channel for users to talk about whatever they want</li>
<li>Spoilers, Beware<strong>:</strong> A channel for users who have finished your game to talk about all the end game reveals</li>
<li>Announcements: A channel for you to announce game updates and for users to discuss them</li>
</ul>
<p>Once you’ve created your guild, you’d invite other users to populate it.</p>
<p>So, to create a guild, head to your Discord home page:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2586 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-home-page.png" alt="Creating-a-Discord-home-page" width="1294" height="566" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-home-page.png 1294w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-home-page-300x131.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-home-page-1024x448.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-home-page-768x336.png 768w" sizes="auto, (max-width: 1294px) 100vw, 1294px" /></p>
<p>From this home page, you can view and add friends, direct messages, and guilds. From here, select the <em>+</em> icon on the left-hand side of the web page to <em>Add a Server</em>:</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-2419 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Untitled9-1.png" alt="" width="1030" height="579" srcset="https://python-programs.com/wp-content/uploads/2021/04/Untitled9-1.png 1030w, https://python-programs.com/wp-content/uploads/2021/04/Untitled9-1-300x169.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Untitled9-1-1024x576.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Untitled9-1-768x432.png 768w" sizes="auto, (max-width: 1030px) 100vw, 1030px" /></p>
<p>This will present two options, <em>Create a server</em> and <em>Join a Server</em>. In this case, select <em>Create a server</em> and enter a name for your guild.</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2587 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-creating-a-server.png" alt="Creating-a-Discord-creating-a-server" width="1288" height="540" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-creating-a-server.png 1288w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-creating-a-server-300x126.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-creating-a-server-1024x429.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-creating-a-server-768x322.png 768w" sizes="auto, (max-width: 1288px) 100vw, 1288px" /></p>
<p>Once you’ve finished creating your guild, you’ll be able to see the users on the right-hand side and the channels on the left.</p>
<p>The final step on Discord is to register your bot with your new guild.</p>
<h3>Adding a Bot to a Guild</h3>
<p>A bot can’t accept invites like a normal user can. Instead, you’ll add your bot using the OAuth2 protocol.</p>
<p>To do so, head back to the Developer Portal and select the OAuth2 page from the left-hand navigation:</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-2423 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Oath2.png" alt="Add your bot using the OAuth2 protocol." width="1911" height="853" srcset="https://python-programs.com/wp-content/uploads/2021/04/Oath2.png 1911w, https://python-programs.com/wp-content/uploads/2021/04/Oath2-300x134.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Oath2-1024x457.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Oath2-768x343.png 768w, https://python-programs.com/wp-content/uploads/2021/04/Oath2-1536x686.png 1536w" sizes="auto, (max-width: 1911px) 100vw, 1911px" /></p>
<p>From this window, you’ll see the OAuth2 URL Generator.</p>
<p>This tool generates an authorization URL that hits Discord’s OAuth2 API and authorizes API access using your application’s credentials.</p>
<p>In this case, you’ll want to grant your application’s bot user access to Discord APIs using your application’s OAuth2 credentials.</p>
<p>To do this, scroll down and select <em>bot</em> from the <em>SCOPES</em> options and <em>Administrator</em> from <em>BOT PERMISSIONS</em>:</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-2424 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/BOT_PERMISSIONS.png" alt="BOT PERMISSIONS" width="1884" height="837" srcset="https://python-programs.com/wp-content/uploads/2021/04/BOT_PERMISSIONS.png 1884w, https://python-programs.com/wp-content/uploads/2021/04/BOT_PERMISSIONS-300x133.png 300w, https://python-programs.com/wp-content/uploads/2021/04/BOT_PERMISSIONS-1024x455.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/BOT_PERMISSIONS-768x341.png 768w, https://python-programs.com/wp-content/uploads/2021/04/BOT_PERMISSIONS-1536x682.png 1536w" sizes="auto, (max-width: 1884px) 100vw, 1884px" /></p>
<p>Now, Discord has generated your application’s authorization URL with the selected scope and permissions.</p>
<p>Select <em>Copy</em> beside the URL that was generated for you, paste it into your browser, and select your guild from the dropdown options:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2588 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-select-your-grid.png" alt="Creating-a-Discord-select-your-grid" width="1291" height="564" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-select-your-grid.png 1291w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-select-your-grid-300x131.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-select-your-grid-1024x447.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-select-your-grid-768x336.png 768w" sizes="auto, (max-width: 1291px) 100vw, 1291px" /></p>
<p>Click <em>Authorize</em>, and you’re done!</p>
</section>
<p>&nbsp;</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-2428 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Authorized-1.png" alt="Authorized" width="1911" height="839" srcset="https://python-programs.com/wp-content/uploads/2021/04/Authorized-1.png 1911w, https://python-programs.com/wp-content/uploads/2021/04/Authorized-1-300x132.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Authorized-1-1024x450.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Authorized-1-768x337.png 768w, https://python-programs.com/wp-content/uploads/2021/04/Authorized-1-1536x674.png 1536w" sizes="auto, (max-width: 1911px) 100vw, 1911px" /><br />
If you go back to your guild, then you’ll see that the bot has been added:</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-2429 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/AddedBotpng.png" alt="Bot added" width="1887" height="843" srcset="https://python-programs.com/wp-content/uploads/2021/04/AddedBotpng.png 1887w, https://python-programs.com/wp-content/uploads/2021/04/AddedBotpng-300x134.png 300w, https://python-programs.com/wp-content/uploads/2021/04/AddedBotpng-1024x457.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/AddedBotpng-768x343.png 768w, https://python-programs.com/wp-content/uploads/2021/04/AddedBotpng-1536x686.png 1536w" sizes="auto, (max-width: 1887px) 100vw, 1887px" /></p>
<p>In summary, you’ve created:</p>
<ul>
<li>An application that your bot will use to authenticate with Discord’s APIs</li>
<li>A bot user that you’ll use to interact with other users and events in your guild</li>
<li>A guild in which your user account and your bot user will be active</li>
<li>ADiscordaccount with which you created everything else and that you’ll use to interact with your bot</li>
</ul>
<p>Now, you know how to make a Discord bot using the Developer Portal. Next comes the fun stuff: implementing your bot in Python!</p>
<h3>How to Make a Discord Bot in Python</h3>
<p>Since you’re learning how to make a Discord bot with Python, you’ll be using discord.py.</p>
<p><span style="color: #222222;font-family: monospace"><span style="background-color: #e9ebec">discord.py </span></span>is a Python library that exhaustively implements Discord’s APIs in an efficient and Pythonic way. This includes utilizing Python’s implementation of Async IO</p>
<p>Begin by installing discord.py with <a href="https://realpython.com/what-is-pip/"><code>pip</code></a>:</p>
<pre><code><span class="gp">$ </span>pip install -U discord.py</code></pre>
<p>Now that you’ve installed discord.py, you’ll use it to create your first connection to Discord!</p>
<p><strong>Creating a Discord Connection</strong></p>
<p>The first step in implementing your bot user is to create a connection to Discord. With discord.py, you do this by creating an instance of Client:</p>
<pre><code><span class="c1"># bot.py</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="kn">import</span> <span class="nn">discord</span>
<span class="kn">from</span> <span class="nn">dotenv</span> <span class="kn">import</span> <span class="n">load_dotenv</span>

<span class="n">load_dotenv</span><span class="p">()</span>
<span class="n">TOKEN</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_TOKEN'</span><span class="p">)</span>

<span class="n">client</span> <span class="o">=</span> <span class="n">discord</span><span class="o">.</span><span class="n">Client</span><span class="p">()</span>

<span class="nd">@client</span><span class="o">.</span><span class="n">event</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">on_ready</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">client</span><span class="o">.</span><span class="n">user</span><span class="si">}</span><span class="s1"> has connected to Discord!'</span><span class="p">)</span>

<span class="n">client</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">TOKEN</span><span class="p">)</span></code></pre>
<p>A Client is an object that represents a connection to Discord. A Client handles events, tracks state, and generally interacts with Discord APIs.</p>
<p>Here, you’ve created a Client and implemented its on_ready() event handler, which handles the event when the Client has established a connection to Discord and it has finished preparing the data that Discord has sent, such as login state, guild and channel data, and more.</p>
<p>In other words, on_ready() will be called (and your message will be printed) once client is ready for further action. You’ll learn more about event handlers later in this article.</p>
<p>When you’re working with secrets such as your Discord token, it’s good practice to read it into your program from an environment variable. Using environment variables helps you:</p>
<ul>
<li>Avoid putting the secrets into source control</li>
<li>Use different variables for development and production environments without changing your code</li>
</ul>
<p>While you could export DISCORD_TOKEN={your-bot-token}, an easier solution is to save a .env file on all machines that will be running this code. This is not only easier, since you won’t have to export your token every time you clear your shell, but it also protects you from storing your secrets in your shell’s history.</p>
<p>Create a file named .env in the same directory as bot.py:</p>
<p>You’ll need to replace {your-bot-token} with your bot’s token, which you can get by going back to the <em>Bot</em> page on the Developer portal and clicking <em>Copy</em> under the <em>TOKEN</em> section:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2585 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-adding-bot-token.png" alt=" Creating-a-Discord-adding-bot-token" width="1303" height="478" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-adding-bot-token.png 1303w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-adding-bot-token-300x110.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-adding-bot-token-1024x376.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-adding-bot-token-768x282.png 768w" sizes="auto, (max-width: 1303px) 100vw, 1303px" /></p>
<p>Looking back at the bot.py code, you’ll notice a library called dotnev. This library is handy for working with .env files. load_dotenv()loads environment variables from a .env file into your shell’s environment variables so that you can use them in your code.</p>
<p>Install dotenv with pip:</p>
<pre><code>pip install -U python-dotenv</code></pre>
<p>Finally, client.run() runs your Client using your bot’s token.</p>
<p>Now that you’ve set up both bot.py and .env, you can run your code:</p>
<pre><code>python bot.py
<span class="go">Shikhaboat#5531 has connected to Discord!</span></code></pre>
<p>Great! Your Client has connected to Discord using your bot’s token. In the next section, you’ll build on this Client by interacting with more Discord APIs.</p>
<p><strong>Interacting With Discord APIs</strong></p>
<p>Using a Client, you have access to a wide range of Discord APIs.</p>
<p>For example, let’s say you wanted to write the name and identifier of the guild that you registered your bot user with to the console.</p>
<p>First, you’ll need to add a new environment variable:</p>
<div class="highlight text">
<pre><code># .env
DISCORD_TOKEN={your-bot-token}
<span class="hll">DISCORD_GUILD={your-guild-name}</span></code></pre>
</div>
<p>Don’t forget that you’ll need to replace the two placeholders with actual values:</p>
<ol>
<li>{your-bot-token}</li>
<li>{your-guild-name}</li>
</ol>
<p>Remember that Discord calls on_ready(), which you used before, once the Client has made the connection and prepared the data. So, you can rely on the guild data being available inside on_ready():</p>
<pre><code><span class="c1"># bot.py</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="kn">import</span> <span class="nn">discord</span>
<span class="kn">from</span> <span class="nn">dotenv</span> <span class="kn">import</span> <span class="n">load_dotenv</span>

<span class="n">load_dotenv</span><span class="p">()</span>
<span class="n">TOKEN</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_TOKEN'</span><span class="p">)</span>
<span class="n">GUILD</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_GUILD'</span><span class="p">)</span>

<span class="n">client</span> <span class="o">=</span> <span class="n">discord</span><span class="o">.</span><span class="n">Client</span><span class="p">()</span>

<span class="nd">@client</span><span class="o">.</span><span class="n">event</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">on_ready</span><span class="p">():</span>
    <span class="k">for</span> <span class="n">guild</span> <span class="ow">in</span> <span class="n">client</span><span class="o">.</span><span class="n">guilds</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">guild</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="n">GUILD</span><span class="p">:</span>
            <span class="k">break</span>

    <span class="nb">print</span><span class="p">(</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">client</span><span class="o">.</span><span class="n">user</span><span class="si">}</span><span class="s1"> is connected to the following guild:</span><span class="se">\n</span><span class="s1">'</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s1">(id: </span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">id</span><span class="si">}</span><span class="s1">)'</span>
    <span class="p">)</span>

<span class="n">client</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">TOKEN</span><span class="p">)</span></code></pre>
<p>Here, you looped through the guild data that Discord has sent client, namely client.guilds. Then, you found the guild with the matching name and printed a formatted string to stdout.</p>
<p>Run the program to see the results:</p>
<pre><code> python bot.py
<span class="go">Shikhaboat#5531 is connected to the following guild:</span>
<span class="go">Shikhaboat#5531(id: 571759877328732195)</span></code></pre>
<p>Great! You can see the name of your bot, the name of your server, and the server’s identification number.</p>
<p>Another interesting bit of data you can pull from a guild is the list of users who are members of the guild:</p>
<pre><code><span class="c1"># bot.py</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="kn">import</span> <span class="nn">discord</span>
<span class="kn">from</span> <span class="nn">dotenv</span> <span class="kn">import</span> <span class="n">load_dotenv</span>

<span class="n">load_dotenv</span><span class="p">()</span>
<span class="n">TOKEN</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_TOKEN'</span><span class="p">)</span>
<span class="n">GUILD</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_GUILD'</span><span class="p">)</span>

<span class="n">client</span> <span class="o">=</span> <span class="n">discord</span><span class="o">.</span><span class="n">Client</span><span class="p">()</span>

<span class="nd">@client</span><span class="o">.</span><span class="n">event</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">on_ready</span><span class="p">():</span>
    <span class="k">for</span> <span class="n">guild</span> <span class="ow">in</span> <span class="n">client</span><span class="o">.</span><span class="n">guilds</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">guild</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="n">GUILD</span><span class="p">:</span>
            <span class="k">break</span>

    <span class="nb">print</span><span class="p">(</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">client</span><span class="o">.</span><span class="n">user</span><span class="si">}</span><span class="s1"> is connected to the following guild:</span><span class="se">\n</span><span class="s1">'</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s1">(id: </span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">id</span><span class="si">}</span><span class="s1">)</span><span class="se">\n</span><span class="s1">'</span>
    <span class="p">)</span>

    <span class="n">members</span> <span class="o">=</span> <span class="s1">'</span><span class="se">\n</span><span class="s1"> - '</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">member</span><span class="o">.</span><span class="n">name</span> <span class="k">for</span> <span class="n">member</span> <span class="ow">in</span> <span class="n">guild</span><span class="o">.</span><span class="n">members</span><span class="p">])</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Guild Members:</span><span class="se">\n</span><span class="s1"> - </span><span class="si">{</span><span class="n">members</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>

<span class="n">client</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">TOKEN</span><span class="p">)</span></code></pre>
<p>By looping through guild.members, you pulled the names of all of the members of the guild and printed them with a formatted string.</p>
<p>When you run the program, you should see at least the name of the account you created the guild with and the name of the bot user itself:</p>
<pre><code><span class="gp">$ </span>python bot.py
<span class="go">Shikhaboat#5531 is connected to the following guild:</span>
<span class="go">Shikhaboat#5531(id: 571759877328732195)</span>
<span class="go">Guild Members:</span>
<span class="go"> - aronq2</span>
<span class="go"> - RealPythonTutorialBot</span></code></pre>
<p>These examples barely scratch the surface of the APIs available on Discord, be sure to check out their documentation to see all that they have to offer.</p>
<p>Next, you’ll learn about some utility functions and how they can simplify these examples.</p>
<h3>Using Utility Functions</h3>
<p>Let’s take another look at the example from the last section where you printed the name and identifier of the bot’s guild:</p>
<div class="highlight python">
<pre><code><span class="c1"># bot.py</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="kn">import</span> <span class="nn">discord</span>
<span class="kn">from</span> <span class="nn">dotenv</span> <span class="kn">import</span> <span class="n">load_dotenv</span>

<span class="n">load_dotenv</span><span class="p">()</span>
<span class="n">TOKEN</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_TOKEN'</span><span class="p">)</span>
<span class="n">GUILD</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_GUILD'</span><span class="p">)</span>

<span class="n">client</span> <span class="o">=</span> <span class="n">discord</span><span class="o">.</span><span class="n">Client</span><span class="p">()</span>

<span class="nd">@client</span><span class="o">.</span><span class="n">event</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">on_ready</span><span class="p">():</span>
    <span class="k">for</span> <span class="n">guild</span> <span class="ow">in</span> <span class="n">client</span><span class="o">.</span><span class="n">guilds</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">guild</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="n">GUILD</span><span class="p">:</span>
            <span class="k">break</span>

    <span class="nb">print</span><span class="p">(</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">client</span><span class="o">.</span><span class="n">user</span><span class="si">}</span><span class="s1"> is connected to the following guild:</span><span class="se">\n</span><span class="s1">'</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s1">(id: </span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">id</span><span class="si">}</span><span class="s1">)'</span>
    <span class="p">)</span>

<span class="n">client</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">TOKEN</span><span class="p">)</span>
</code></pre>
</div>
<p>You could clean up this code by using some of the utility functions available in discord.py.</p>
<p>discord.utils.find<a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find"><code></code></a> is one utility that can improve the simplicity and readability of this code by replacing the for loop with an intuitive, abstracted function:</p>
<div class="highlight python">
<pre><code><span class="c1"># bot.py</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="kn">import</span> <span class="nn">discord</span>
<span class="kn">from</span> <span class="nn">dotenv</span> <span class="kn">import</span> <span class="n">load_dotenv</span>

<span class="n">load_dotenv</span><span class="p">()</span>
<span class="n">TOKEN</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_TOKEN'</span><span class="p">)</span>
<span class="n">GUILD</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_GUILD'</span><span class="p">)</span>

<span class="n">client</span> <span class="o">=</span> <span class="n">discord</span><span class="o">.</span><span class="n">Client</span><span class="p">()</span>

<span class="nd">@client</span><span class="o">.</span><span class="n">event</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">on_ready</span><span class="p">():</span>
    <span class="n">guild</span> <span class="o">=</span> <span class="n">discord</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="k">lambda</span> <span class="n">g</span><span class="p">:</span> <span class="n">g</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="n">GUILD</span><span class="p">,</span> <span class="n">client</span><span class="o">.</span><span class="n">guilds</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">client</span><span class="o">.</span><span class="n">user</span><span class="si">}</span><span class="s1"> is connected to the following guild:</span><span class="se">\n</span><span class="s1">'</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s1">(id: </span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">id</span><span class="si">}</span><span class="s1">)'</span>
    <span class="p">)</span>

<span class="n">client</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">TOKEN</span><span class="p">)</span></code></pre>
</div>
<p>&lt;find() takes a function, called a predicate, which identifies some characteristic of the element in the iterable that you’re looking for. Here, you used a particular type of anonymous function, called a lambda, as the predicate.</p>
<p>In this case, you’re trying to find the guild with the same name as the one you stored in the DISCORD_GUILD environment variable. Once find() locates an element in the iterable that satisfies the predicate, it will return the element. This is essentially equivalent to the break statement in the previous example, but cleaner.</p>
<p>discord.py has even abstracted this concept one step further with the <span style="color: #222222;font-family: monospace"><span style="background-color: #e9ebec">get.utility():</span></span></p>
<div class="highlight python">
<pre><code><span class="c1"># bot.py</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="kn">import</span> <span class="nn">discord</span>
<span class="kn">from</span> <span class="nn">dotenv</span> <span class="kn">import</span> <span class="n">load_dotenv</span>

<span class="n">load_dotenv</span><span class="p">()</span>
<span class="n">TOKEN</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_TOKEN'</span><span class="p">)</span>
<span class="n">GUILD</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_GUILD'</span><span class="p">)</span>

<span class="n">client</span> <span class="o">=</span> <span class="n">discord</span><span class="o">.</span><span class="n">Client</span><span class="p">()</span>

<span class="nd">@client</span><span class="o">.</span><span class="n">event</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">on_ready</span><span class="p">():</span>
    <span class="n">guild</span> <span class="o">=</span> <span class="n">discord</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">client</span><span class="o">.</span><span class="n">guilds</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="n">GUILD</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">client</span><span class="o">.</span><span class="n">user</span><span class="si">}</span><span class="s1"> is connected to the following guild:</span><span class="se">\n</span><span class="s1">'</span>
        <span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s1">(id: </span><span class="si">{</span><span class="n">guild</span><span class="o">.</span><span class="n">id</span><span class="si">}</span><span class="s1">)'</span>
    <span class="p">)</span>

<span class="n">client</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">TOKEN</span><span class="p">)</span>
</code></pre>
</div>
<p>get() takes the iterable and some keyword arguments. The keyword arguments represent attributes of the elements in the iterable that must all be satisfied for get() to return the element.</p>
<p>In this example, you’ve identified name=GUILD as the attribute that must be satisfied.</p>
<p>Now that you’ve learned the basics of interacting with APIs, you’ll dive a little deeper into the function that you’ve been using to access them: <code>on_ready()</code>.</p>
<h2>Responding to Events</h2>
<p>You already learned that on_ready() is an event. In fact, you might have noticed that it is identified as such in the code by the client.event decorator.</p>
<p>But what is an event?</p>
<p>An event is something that happens on Discord that you can use to trigger a reaction in your code. Your code will listen for and then respond to events.</p>
<p>Using the example you’ve seen already, the on_ready() event handler handles the event that the Client has made a connection to Discord and prepared its response data.</p>
<p>So, when Discord fires an event, discord.py will route the event data to the corresponding event handler on your connected Client.</p>
<p>There are two ways in discord.py to implement an event handler:</p>
<ol>
<li>Using the client.event decorator</li>
<li>Creating a subclass of Client and overriding its handler methods</li>
</ol>
<p>You already saw the implementation using the decorator. Next, take a look at how to subclass Client:</p>
<div class="highlight python">
<pre><code><span class="c1"># bot.py</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="kn">import</span> <span class="nn">discord</span>
<span class="kn">from</span> <span class="nn">dotenv</span> <span class="kn">import</span> <span class="n">load_dotenv</span>

<span class="n">load_dotenv</span><span class="p">()</span>
<span class="n">TOKEN</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_TOKEN'</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">CustomClient</span><span class="p">(</span><span class="n">discord</span><span class="o">.</span><span class="n">Client</span><span class="p">):</span>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">on_ready</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">user</span><span class="si">}</span><span class="s1"> has connected to Discord!'</span><span class="p">)</span>

<span class="n">client</span> <span class="o">=</span> <span class="n">CustomClient</span><span class="p">()</span>
<span class="n">client</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">TOKEN</span><span class="p">)</span>
</code></pre>
</div>
<p>Here, just like before, you’ve created a client variable and called &lt;.run() with your Discord token. The actual Client is different, however. Instead of using the normal base class, client is an instance of CustomClient, which has an overridden on_ready() function.</p>
<p>There is no difference between the two implementation styles of events, but this tutorial will primarily use the decorator version because it looks similar to how you implement Bot commands, which is a topic you’ll cover in a bit.</p>
<h3>Welcoming New Members</h3>
<p>Previously, you saw the example of responding to the event where a member joins a guild. In that example, your bot user could send them a message, welcoming them to your Discord community.</p>
<p>Now, you’ll implement that behavior in your Client, using event handlers, and verify its behavior in Discord:</p>
<div class="highlight python">
<pre><code><span class="c1"># bot.py</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="kn">import</span> <span class="nn">discord</span>
<span class="kn">from</span> <span class="nn">dotenv</span> <span class="kn">import</span> <span class="n">load_dotenv</span>

<span class="n">load_dotenv</span><span class="p">()</span>
<span class="n">TOKEN</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">'DISCORD_TOKEN'</span><span class="p">)</span>

<span class="n">client</span> <span class="o">=</span> <span class="n">discord</span><span class="o">.</span><span class="n">Client</span><span class="p">()</span>

<span class="nd">@client</span><span class="o">.</span><span class="n">event</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">on_ready</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">client</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s1"> has connected to Discord!'</span><span class="p">)</span>

<span class="nd">@client</span><span class="o">.</span><span class="n">event</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">on_member_join</span><span class="p">(</span><span class="n">member</span><span class="p">):</span>
    <span class="k">await</span> <span class="n">member</span><span class="o">.</span><span class="n">create_dm</span><span class="p">()</span>
    <span class="k">await</span> <span class="n">member</span><span class="o">.</span><span class="n">dm_channel</span><span class="o">.</span><span class="n">send</span><span class="p">(</span>
        <span class="sa">f</span><span class="s1">'Hi </span><span class="si">{</span><span class="n">member</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s1">, welcome to my Discord server!'</span>
    <span class="p">)</span>

<span class="n">client</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">TOKEN</span><span class="p">)</span>
</code></pre>
</div>
<p>Like before, you handled the on_ready() event by printing the bot user’s name in a formatted string. New, however, is the implementation of the on_member_join() event handler.</p>
<p>on_member_join(), as its name suggests, handles the event of a new member joining a guild.</p>
<p>In this example, you used member.create_dm()to create a direct message channel. Then, you used that channel to send() a direct message to that new member.</p>
<p>Now, let’s test out your bot’s new behavior.</p>
<p>First, run your new version of <code>bot.py</code> and wait for the on_ready() event to fire, logging your message to stdout:</p>
<div class="highlight sh">
<pre><code><span class="gp">$ </span>python bot.py
<span class="go">ShikhaBot has connected to Discord!</span></code></pre>
</div>
<p>Now, head over to <a href="https://discordapp.com/">Discord</a>, log in, and navigate to your guild by selecting it from the left-hand side of the screen:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2583 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-navigate-to-server.png" alt="Creating-a-Discord-navigate-to-server" width="1283" height="569" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-navigate-to-server.png 1283w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-navigate-to-server-300x133.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-navigate-to-server-1024x454.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-navigate-to-server-768x341.png 768w" sizes="auto, (max-width: 1283px) 100vw, 1283px" /></p>
<p>Select <em>Invite People</em> just beside the guild list where you selected your guild. Check the box that says <em>Set this link to never expire</em> and copy the link:</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-2432 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/InvitePepole.png" alt="InvitePepole" width="1022" height="547" srcset="https://python-programs.com/wp-content/uploads/2021/04/InvitePepole.png 1022w, https://python-programs.com/wp-content/uploads/2021/04/InvitePepole-300x161.png 300w, https://python-programs.com/wp-content/uploads/2021/04/InvitePepole-768x411.png 768w" sizes="auto, (max-width: 1022px) 100vw, 1022px" /></p>
<p>Now, with the invite link copied, create a new account and join the guild using your invite link.</p>
<p>First, you’ll see that Discord introduced you to the guild by default with an automated message. More importantly though, notice the badge on the left-hand side of the screen that notifies you of a new message:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2580 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-message.png" alt=" Creating-a-Discord-account-new-message." width="1296" height="660" srcset="https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-message.png 1296w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-message-300x153.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-message-1024x521.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Creating-a-Discord-account-new-message-768x391.png 768w" sizes="auto, (max-width: 1296px) 100vw, 1296px" /><br />
When you select it, you’ll see a private message from your bot user:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2579 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Boat-is-created.png" alt=" Boat-is-created" width="1287" height="407" srcset="https://python-programs.com/wp-content/uploads/2021/04/Boat-is-created.png 1287w, https://python-programs.com/wp-content/uploads/2021/04/Boat-is-created-300x95.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Boat-is-created-1024x324.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Boat-is-created-768x243.png 768w" sizes="auto, (max-width: 1287px) 100vw, 1287px" /></p>
<p>Perfect! Your bot user is now interacting with other users with minimal code.</p>
<h3>Conclusion</h3>
<p>Congratulations! Now, you’ve learned how to make a Discord bot in Python. You’re able to build bots for interacting with users in guilds that you create or even bots that other users can invite to interact with their communities.</p>
<p>&nbsp;</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2407</post-id>	</item>
		<item>
		<title>Understanding the Two Sum Problem</title>
		<link>https://python-programs.com/understanding-the-two-sum-problem/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Thu, 09 Jul 2026 06:43:24 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=2825</guid>

					<description><![CDATA[The two sum problem is a  very common interview question, asked in companies.For the two sum problem we will write two algorithm that runs in O(n2) &#38; O(n) time. Two Sum Problem Given an array of integer return indices of the two numbers such that they add up to the specific target. You may assume [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>The two sum problem is a  very common interview question, asked in companies.For the two sum problem we will write two algorithm that runs in O(<i>n</i><sup>2</sup>) &amp; O(<i>n</i>) time.</p>
<h2>Two Sum Problem</h2>
<p>Given an array of integer return indices of the two numbers such that they add up to the specific target.</p>
<p>You may assume that each input would have exactly one solution and you are not going to use same element twice.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">Example:

Given numbers=[ 3 , 4 , 6 ,7 ] , target = 7,

Because num[0]+num[1] = 3 + 4 = 7,

return[0,1]</pre>
<p>Example has given above we have to execute two sum problem for any two number in list and give us targeted value.</p>
<p>There are mainly two way to execute two sum problem.</p>
<ol>
<li>Using Naive Method</li>
<li>Using hash table</li>
</ol>
<h3>Implementing Naive Method:</h3>
<p>In this method  we would be loop through each number and then loop again through the list looking for a pair that sums and give us final value. The running time for the below solution would be O(<i>n</i><sup>2</sup>).</p>
<p>So for this we will write an algorithm which mentioned below-</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">def twoSum(nums, target):
    for i in range(len(nums)):
        for j in range(i+1,len(nums)):
            if target - nums[i] == nums[j]:
                return[i,j]

    return None            

test = [2,7,11,15]
target = 9
print(twoSum(test,target))
</pre>
<p><strong>Output:</strong></p>
<pre>C:\New folder\Python project(APT)&gt;py twosum.py
[0, 1]

C:\New folder\Python project(APT)&gt;</pre>
<p>So you can see that it has return us those indices which has given target value.If we change the target then value and indices both will change.This is what we want to do but it increases the complexity because we run two loop.</p>
<p>So for increasing complexity we will use second method which is hash table.</p>
<h3>Implementing hash table:</h3>
<p>Below we will show use of hash table. We can write an another faster algorithm that will find pairs that sum to numbers in same time. As we pass through each element in the array, we check to see if M minus the current element exists in the hash table.</p>
<pre>Example:

If the array is: [6, 7, 1, 8] and the sum is 8.</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="python">class Solution:
    def twoSum(nums,target):
        prevMap = {}

        for i,n in enumerate(nums):
            diff = target - n
            if diff in prevMap:
               return[prevMap[diff],i]
            prevMap[n] = i
        return    
    nums=[6, 7, 1, 8]
    target= 8
    print(twoSum(nums,target))</pre>
<p><strong>Output:</strong></p>
<pre>C:\New folder\Python project(APT)&gt;py twosum.py [1, 2] 
C:\New folder\Python project(APT)&gt;</pre>
<p>So you can see that above program gives us index value of the two number which gives us our target value.</p>
<p><strong>Conclusion:</strong></p>
<p>Great!So in this article we have seen two methods for two sum problem in python.Naive method has complexity O(<i>n</i><sup>2</sup>)and Hash metod has complexity O(n),So best approach is Hash method and worst is Naive method.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2825</post-id>	</item>
		<item>
		<title>Basics of Python – Operators and Operands</title>
		<link>https://python-programs.com/basics-of-python-operators-and-operands/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Jul 2026 06:39:40 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=2809</guid>

					<description><![CDATA[In this Page, We are Providing Basics of Python – Operators and Operands. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf. Basics of Python – Operators and Operands Operators and operands An operator is a symbol (such as +, x, etc.) that represents an operation. An operation is an action [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this Page, We are Providing Basics of Python – Operators and Operands. Students can visit for more Detail and Explanation of <a href="https://python-programs.com/python-handwritten-notes/">Python Handwritten Notes</a> Pdf.</p>
<h2>Basics of Python – Operators and Operands</h2>
<p><strong>Operators and operands</strong></p>
<p>An operator is a symbol (such as +, x, etc.) that represents an operation. An operation is an action or •procedure that produces a new value from one or more input values called operands. There are two types of operators: unary and binary. The unary operator operates only on one operand, such as negation. On the other hand, the binary operator operates on two operands, which include addition, subtraction, multiplication, division, exponentiation operators, etc. Consider an expression 3 + 8, here 3 and 8 are called operands, while V is called operator. The operators can also be categorized into:</p>
<ul>
<li>Arithmetic operators.</li>
<li>Comparison (or Relational) operators.</li>
<li>Assignment operators.</li>
<li>Logical operators.</li>
<li>Bitwise operators.</li>
<li>Membership operators.</li>
<li>Identity operators.</li>
</ul>
<p><strong>Arithematics operators</strong></p>
<p>Table 2-2 enlists the arithmetic operators with a short note on the operators.</p>
<table>
<tbody>
<tr>
<td width="74">
<p style="text-align: center;">Operator</p>
</td>
<td width="550">
<p style="text-align: center;">Description</p>
</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">+</p>
</td>
<td width="550">Addition operator- Add operands on either side of the operator.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">&#8211;</p>
</td>
<td width="550">Subtraction operator &#8211; Subtract the right-hand operand from the left-hand operand.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">*</p>
</td>
<td width="550">Multiplication operator &#8211; Multiply operands on either side of the operator.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">/</p>
</td>
<td width="550">Division operator &#8211; Divide left-hand operand by right-hand operand.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">%</p>
</td>
<td width="550">Modulus operator &#8211; Divide left-hand operand by right-hand operand and return the remainder.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">**</p>
</td>
<td width="550">Exponent operator &#8211; Perform exponential (power) calculation on operands.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">//</p>
</td>
<td width="550">Floor Division operator &#8211; The division of operands where the result is the quotient in which the digits after the decimal point are removed.</td>
</tr>
</tbody>
</table>
<p>The following example illustrates the use of the above-discussed operators.</p>
<pre>&gt;&gt;&gt; a=20 
&gt;&gt;&gt; b=45.0
&gt;&gt;&gt; a+b
65.0
&gt;&gt;&gt; a-b
-25.0
&gt;&gt;&gt; a*b
900.0 
&gt;&gt;&gt; b/a 
2.25 
&gt;&gt;&gt; b%a
5.0
&gt;&gt;&gt; a**b
3.5184372088832e+58 
&gt;&gt;&gt; b//a
2.0</pre>
<p><strong>Relational operators</strong></p>
<p>A relational operator is an operator that tests some kind of relation between two operands. Tables 2-3 enlist the relational operators with descriptions.</p>
<table>
<tbody>
<tr>
<td width="74">
<p style="text-align: center;">Operator</p>
</td>
<td width="550">
<p style="text-align: center;">Description</p>
</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">==</p>
</td>
<td width="550">Check if the values of the two operands are equal.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">!=</p>
</td>
<td width="550">Check if the values of the two operands are not equal.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">&lt;&gt;</p>
</td>
<td width="550">Check if the value of two operands is not equal (same as != operator).</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">&gt;</p>
</td>
<td width="550">Check if the value of the left operand is greater than the value of the right operand.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">&lt;</p>
</td>
<td width="550">Check if the value of the left operand is less than the value of the right operand.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">&gt;=</p>
</td>
<td width="550">Check if the value of the left operand is greater than or equal to the value of the right operand.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">&lt;=</p>
</td>
<td width="550">Check if the value of the left operand is less than or equal to the value of the right operand.</td>
</tr>
</tbody>
</table>
<p>The following example illustrates the use of the above-discussed operators.</p>
<pre>&gt;&gt;&gt; a,b=20,40
&gt;&gt;&gt; a==b
False 
&gt;&gt;&gt; a!=b 
True
&gt;&gt;&gt; a&lt;&gt;b 
True 
&gt;&gt;&gt; a&gt;b 
False 
&gt;&gt;&gt; a&lt;b 
True
&gt;&gt;&gt; a&gt;=b 
False 
&gt;&gt;&gt; a&lt;=b 
True</pre>
<p><strong>Assignment operators</strong></p>
<p>The assignment operator is an operator which is used to bind or rebind names to values. The augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement. An augmented assignment expression like x+=l can be rewritten as x=x+l. Tables 2-4 enlist the assignment operators with descriptions.</p>
<table>
<tbody>
<tr>
<td width="78">
<p style="text-align: center;">Operator</p>
</td>
<td width="546">
<p style="text-align: center;">Description</p>
</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">=</p>
</td>
<td width="546">Assignment operator- Assigns values from right side operand to left side operand.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">+=</p>
</td>
<td width="546">Augmented assignment operator- It adds the right-side operand to the left side operand and assigns the result to the left side operand.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">-=</p>
</td>
<td width="546">Augmented assignment operator- It subtracts the right-side operand from the left side operand and assigns the result to the left side operand.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">*=</p>
</td>
<td width="546">Augmented assignment operator- It multiplies the right-side operand with the left side operand and assigns the result to the left side operand.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">/=</p>
</td>
<td width="546">Augmented assignment operator- It divides the left side operand with the right side operand and assigns the result to the left side operand.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">%=</p>
</td>
<td width="546">Augmented assignment operator- It takes modulus using two operands and assigns the result to left side operand.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">* *=</p>
</td>
<td width="546">Augmented assignment operator- Performs exponential (power) calculation on operands and assigns value to the left side operand.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">//=</p>
</td>
<td width="546">Augmented assignment operator- Performs floor division on operators and assigns value to the left side operand.</td>
</tr>
</tbody>
</table>
<p>The following example illustrates the use of the above-discussed operators.</p>
<pre>&gt;&gt;&gt; a,b=20,40 
&gt;&gt;&gt; c=a+b 
&gt;&gt;&gt; c 
60
&gt;&gt;&gt; a,b=2.0,4.5 
&gt;&gt;&gt;c=a+b
&gt;&gt;&gt; C
6.5
&gt;&gt;&gt; c+=a 
&gt;&gt;&gt; c
8.5
&gt;&gt;&gt; c-=a 
&gt;&gt;&gt; c
6.5
&gt;&gt;&gt; c*=a 
&gt;&gt;&gt; c
13.0
&gt;&gt;&gt; c/=a 
&gt;&gt;&gt; c 
6.5
&gt;&gt;&gt; c%=a 
&gt;&gt;&gt; c 
0.5
&gt;&gt;&gt; c**=a 
&gt;&gt;&gt; c 
0.25
&gt;&gt;&gt; c//=a 
&gt;&gt;&gt; c 
0.0</pre>
<p><strong>Bitwise operators</strong></p>
<p>A bitwise operator operates on one or more bit patterns or binary numerals at the level of their individual bits. Tables 2-5 enlist the bitwise operators with descriptions.</p>
<table>
<tbody>
<tr>
<td width="78">
<p style="text-align: center;">Operator</p>
</td>
<td width="546">
<p style="text-align: center;">Description</p>
</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">&amp;</p>
</td>
<td width="546">Binary AND operator- Copies corresponding binary 1 to the result, if it exists in both operands.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">|</p>
</td>
<td width="546">Binary OR operator- Copies corresponding binary 1 to the result, if it exists in either operand.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">∧</p>
</td>
<td width="546">Binary XOR operator- Copies corresponding binary 1 to the result, if it is set in one operand, but not both.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">~</p>
</td>
<td width="546">Binary ones complement operator- It is unary and has the effect of flipping bits.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">&lt;&lt;</p>
</td>
<td width="546">Binary left shift operator- The left side operand bits are moved to the left side by the number on the right-side operand.</td>
</tr>
<tr>
<td width="78">
<p style="text-align: center;">&gt;&gt;</p>
</td>
<td width="546">Binary right shift operator- The left side operand bits are moved to the right side by the number on the right-side operand.</td>
</tr>
</tbody>
</table>
<p>The following example illustrates the use of the above-discussed operators.</p>
<pre>&gt;&gt;&gt; a,b=60,13 
&gt;&gt;&gt; a&amp;b 
12
&gt;&gt;&gt; a | b
61 
&gt;&gt;&gt; a∧b
49 
&gt;&gt;&gt; ~a
-61 
&gt;&gt;&gt; a&lt; &lt; 2
240 
&gt;&gt;&gt; a&gt;&gt;2
15</pre>
<p>In the above example, the binary representation of variables a and b are 00111100 and 00001101, respectively. The above binary operations example is tabulated in Tables 2-6.</p>
<table width="534">
<tbody>
<tr>
<td width="156">
<p style="text-align: center;">Bitwise operation</p>
</td>
<td style="text-align: center;" width="186">Binary representation</td>
<td style="text-align: center;" width="192">Decimal representation</td>
</tr>
<tr>
<td style="text-align: center;" width="156">
<p style="text-align: center;">a&amp;b</p>
</td>
<td style="text-align: center;" width="186">00001100</td>
<td style="text-align: center;" width="192">
<p style="text-align: center;">12</p>
</td>
</tr>
<tr>
<td width="156">
<p style="text-align: center;">a | b</p>
</td>
<td style="text-align: center;" width="186">00111101</td>
<td width="192">
<p style="text-align: center;">61</p>
</td>
</tr>
<tr>
<td width="156">
<p style="text-align: center;">a<sup>∧</sup>b</p>
</td>
<td style="text-align: center;" width="186">00110001</td>
<td width="192">
<p style="text-align: center;">49</p>
</td>
</tr>
<tr>
<td width="156">
<p style="text-align: center;">~a</p>
</td>
<td style="text-align: center;" width="186">11000011</td>
<td style="text-align: center;" width="192">-61</td>
</tr>
<tr>
<td style="text-align: center;" width="156">a&lt;&lt;2</td>
<td style="text-align: center;" width="186">11110000</td>
<td width="192">
<p style="text-align: center;">240</p>
</td>
</tr>
<tr>
<td style="text-align: center;" width="156">a&gt;&gt;2</td>
<td style="text-align: center;" width="186">00001111</td>
<td width="192">
<p style="text-align: center;">15</p>
</td>
</tr>
</tbody>
</table>
<p><strong>Logical operators</strong></p>
<p>Logical operators compare boolean expressions and return a boolean result. Tables 2-6 enlist the logical operators with descriptions.</p>
<table>
<tbody>
<tr>
<td width="102">
<p style="text-align: center;">Operator</p>
</td>
<td width="522">
<p style="text-align: center;">Description</p>
</td>
</tr>
<tr>
<td width="102">
<p style="text-align: center;">and</p>
</td>
<td style="text-align: center;" width="522">
<p style="text-align: left;">Logical AND operator- If both the operands are true (or non-zero), then the condition becomes true.</p>
</td>
</tr>
<tr>
<td style="text-align: left;" width="102">
<p style="text-align: center;">or</p>
</td>
<td width="522">
<p style="text-align: left;">Logical OR&#8217;operator- If any of the two operands is true (or non-zero), then the condition becomes true.</p>
</td>
</tr>
<tr>
<td style="text-align: center;" width="102">not</td>
<td width="522">
<p style="text-align: left;">Logical NOT operator- The result is reverse of the logical state of its operand. If the operand is true (or non-zero), then the condition becomes false.</p>
</td>
</tr>
</tbody>
</table>
<p>The following example illustrates the use of the above-discussed operators.</p>
<pre>&gt;&gt;&gt; 5&gt;2 and 4&lt;8 
True
&gt;&gt;&gt; 5&gt;2 or 4&gt;8 
True
&gt;&gt;&gt; not (5&gt;2)
False</pre>
<p><strong>Membership operators</strong></p>
<p>A membership operator is an operator which tests for membership in a sequence, such as string, list, tuple, etc. Table 2-7 enlists the membership operators.</p>
<table>
<tbody>
<tr>
<td width="74">
<p style="text-align: center;">Operator</p>
</td>
<td width="550">
<p style="text-align: center;">Description</p>
</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">In</p>
</td>
<td width="550">Evaluate to true, if it finds a variable in the specified sequence; otherwise false.</td>
</tr>
<tr>
<td width="74">
<p style="text-align: center;">not in</p>
</td>
<td width="550">Evaluate to true, if it does not find a variable in the specified sequence; otherwise false.</td>
</tr>
</tbody>
</table>
<pre>&gt;&gt;&gt; 5 in [0, 5, 10, 15]
True 
&gt;&gt;&gt; 6 in [0, 5, 10, 15]
False
&gt;&gt;&gt; 5 not in [0, 5, 10, 15]
False 
&gt;&gt;&gt; 6 not in [0, 5, 10, 15]
True</pre>
<p><strong>Identity operators</strong></p>
<p>Identity operators compare the memory locations of two objects. Table 2-8 provides a list of identity operators including a small explanation.</p>
<table>
<tbody>
<tr>
<td width="84">
<p style="text-align: center;">Operator</p>
</td>
<td width="540">
<p style="text-align: center;">Description</p>
</td>
</tr>
<tr>
<td width="84">
<p style="text-align: center;">is</p>
</td>
<td width="540">Evaluates to true, if the operands on either side of the operator point to the same object, and false otherwise.</td>
</tr>
<tr>
<td width="84">
<p style="text-align: center;">is not</p>
</td>
<td width="540">Evaluates to false, if the operands on either side of the operator point to the same object, and true otherwise.</td>
</tr>
</tbody>
</table>
<p>The following example illustrates the use of the above-discussed operators.</p>
<pre>&gt;&gt;&gt; a=b=3.1
&gt;&gt;&gt; a is b 
True 
&gt;&gt;&gt; id (a)
3 0 9 8 4 5 2 8 
&gt;&gt;&gt; id (b)
30984528 
&gt;&gt;&gt; c,d=3.1,3.1 
&gt;&gt;&gt; c is d 
False 
&gt;&gt;&gt; id (c)
35058472 
&gt;&gt;&gt; id (d)
30984592
&gt;&gt;&gt; c is not d
True 
&gt;&gt;&gt; a is not b
False</pre>
<p><strong>Operator precedence</strong></p>
<p>Operator precedence determines how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. In the expression x=7+3*2, x is assigned 13, not 20, because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7.</p>
<p>Table 2-10 summarizes the operator&#8217;s precedence in Python, from lowest precedence to highest precedence (from top to bottom). Operators in the same box have the same precedence.</p>
<table>
<tbody>
<tr>
<td width="210">Operator</td>
</tr>
<tr>
<td width="210">not, or, and</td>
</tr>
<tr>
<td width="210">in, not in</td>
</tr>
<tr>
<td width="210">is, is not</td>
</tr>
<tr>
<td width="210">=, %, =/, =//, -=, +=, *=, **=</td>
</tr>
<tr>
<td width="210">&lt;&gt;, ==, !=</td>
</tr>
<tr>
<td width="210">&lt;=, &lt;, &gt;, &gt;=</td>
</tr>
<tr>
<td width="210"><sup>∧, |</sup></td>
</tr>
<tr>
<td width="210">&amp;</td>
</tr>
<tr>
<td width="210">&gt;&gt;,&lt;&lt;</td>
</tr>
<tr>
<td width="210">+, &#8211;</td>
</tr>
<tr>
<td width="210">*, /, %, //</td>
</tr>
<tr>
<td width="210">∼,+,-</td>
</tr>
<tr>
<td width="210">**</td>
</tr>
</tbody>
</table>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2809</post-id>	</item>
		<item>
		<title>Building an RSS feed Scraper with Python</title>
		<link>https://python-programs.com/building-an-rss-feed-scraper-with-python/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Thu, 09 Jul 2026 06:18:24 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=2640</guid>

					<description><![CDATA[What is RSS? RSS stands for Really Simple Syndication or Rich Site Summary. It is a type of web feed that allows users and applications to receive regular updates from a website or blog of their choice. Various website use their RSS feed to publish the frequently updated information like blog entries, news headlines etc, [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>What is RSS?</h2>
<p>RSS stands for Really Simple Syndication or Rich Site Summary. It is a type of web feed that allows users and applications to receive regular updates from a website or blog of their choice. Various website use their RSS feed to publish the frequently updated information like blog entries, news headlines etc, So this is where RSS feeds are mainly used.</p>
<p>So we can use that RSS feed to extract some important information from a particular website. In this article I will be showing how you will extract RSS feeds of any website.</p>
<h3>Installing packages</h3>
<p>You can install all packages using pip like the example below.</p>
<pre> pip install requests
 pip install bs4</pre>
<h3 id="936f" class="ln ke fn as kf lo lp lq ki lr ls lt kl lu lv lw kp lx ly lz kt ma mb mc kx md bx">Importing  libraries:</h3>
<p id="4d50" class="hx hy fn hz b ia kz ic id ie la ig ih ii lb ik il im lc io ip iq ld is it iu ff bx" data-selectable-paragraph="">Now our project setup is ready, we can start writing the code.</p>
<p id="1e85" class="hx hy fn hz b ia ib ic id ie if ig ih ii ij ik il im in io ip iq ir is it iu ff bx" data-selectable-paragraph="">Within our rssScrapy.py we’ll import the packages we’ve installed using pip.</p>
<pre>import requests

from bs4 import BeautifulSoup</pre>
<p>The above package will allow us to use the functions given to us by the Requests and BeautifulSoup libraries.</p>
<p>I am going to use the RSS feeds of a news website called Times of India.</p>
<pre>Link-"https://timesofindia.indiatimes.com/rssfeeds/1221656.cms"</pre>
<p>This is basically an XML file.</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2759 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_xml-file-e1618574028930.png" alt="Building-an-RSS-feed-scraper-with-Python_xml-file" width="1878" height="972" srcset="https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_xml-file-e1618574028930.png 1878w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_xml-file-e1618574028930-300x155.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_xml-file-e1618574028930-1024x530.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_xml-file-e1618574028930-768x397.png 768w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_xml-file-e1618574028930-1536x795.png 1536w" sizes="auto, (max-width: 1878px) 100vw, 1878px" /></p>
<p>So now I am going to show you how this particular xml file will scrape.</p>
<div class="">
<pre class="EnlighterJSRAW" data-enlighter-language="python">import requests
from bs4 import BeautifulSoup
url="https://timesofindia.indiatimes.com/rssfeeds/1221656.cms"
resp=requests.get(url)
soup=BeautifulSoup(resp.content,features="xml")
print(soup.prettify())</pre>
<p id="54c7" class="hx hy fn hz b ia ib ic id ie if ig ih ii ij ik il im in io ip iq ir is it iu ff bx" data-selectable-paragraph="">I have imported all necessary libraries.I have also defined url which give me link for news website RSS feed after that for get request I made resp object where I have pass that url.</p>
<p data-selectable-paragraph="">Now we have response object and we have also a beautiful soup object with me.Bydefault beautiful soup parse html file but we want xml file so we used features=&#8221;xml&#8221;.So now let me just show you the xml file we have parsed.</p>
<p data-selectable-paragraph=""><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2812" src="https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_output.png" alt="Building-an-RSS-feed-scraper-with-Python_output" width="1480" height="606" srcset="https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_output.png 1480w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_output-300x123.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_output-1024x419.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_output-768x314.png 768w" sizes="auto, (max-width: 1480px) 100vw, 1480px" /></p>
</div>
<p>We dont nedd all the data having in it.We want news description,title,publish date right.So for this we are going to create a list which contains all the content inside item tags.For this we have used   <code class="EnlighterJSRAW" data-enlighter-language="python">items=soup.findAll('item') </code></p>
<p>You can also check the length of items using this <code class="EnlighterJSRAW" data-enlighter-language="python">len(items)</code></p>
<p>So now I am writing whole code for scrapping the news RSS feed-</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import requests
from bs4 import BeautifulSoup
url="https://timesofindia.indiatimes.com/rssfeeds/1221656.cms"
resp=requests.get(url)
soup=BeautifulSoup(resp.content,features="xml")
items=soup.findAll('item')
item=items[0]
news_items=[]
for item in items:
    news_item={}
    news_item['title']=item.title.text
    news_item['description']=item.description.text
    news_item['link']=item.link.text
    news_item['guid']=item.guid.text
    news_item['pubDate']=item.pubDate.text
    news_items.append(news_item)
print(news_items[2])</pre>
<p>So we can see that I have used <code class="EnlighterJSRAW" data-enlighter-language="generic">item.title.text</code>for scrapping title because item is parent class and title is child class similarly we do for rest.</p>
<p>Each of the articles available on the RSS feed  containing all information within <em class="le">item</em> tags <code class="EnlighterJSRAW" data-enlighter-language="generic">&lt;item&gt;...&lt;/item&gt;.</code><br />
and follows the below structure-</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">&lt;item&gt;
    &lt;title&gt;...&lt;/title&gt;
    &lt;link&gt;...&lt;/link&gt;
    &lt;pubDate&gt;...&lt;/pubDate&gt;
    &lt;comments&gt;...&lt;/comments&gt;
    &lt;description&gt;...&lt;/description&gt;
&lt;/item&gt;</pre>
<p>We’ll be taking advantage of the consistent <em class="le">item</em> tags to parse our information.</p>
<p>I have also make an empty list news_items which append all in it.</p>
<p>So this is how we can parse particularly news item.</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2813 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_final-output-e1618639418855.png" alt="Building-an-RSS-feed-scraper-with-Python_final-output" width="1779" height="131" srcset="https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_final-output-e1618639418855.png 1779w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_final-output-e1618639418855-300x22.png 300w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_final-output-e1618639418855-1024x75.png 1024w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_final-output-e1618639418855-768x57.png 768w, https://python-programs.com/wp-content/uploads/2021/04/Building-an-RSS-feed-scraper-with-Python_final-output-e1618639418855-1536x113.png 1536w" sizes="auto, (max-width: 1779px) 100vw, 1779px" /></p>
<h3>Conclusion:</h3>
<p>We have successfully created an RSS feed scraping tool using Python, Requests, and BeautifulSoup. This allows us to parse XML information into a suitable format for us to work with in the future.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2640</post-id>	</item>
		<item>
		<title>Basics of Python – Variable, Identifier and Literal</title>
		<link>https://python-programs.com/basics-of-python-variable-identifier-and-literal/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Jul 2026 04:51:33 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=2803</guid>

					<description><![CDATA[In this Page, We are Providing Basics of Python – Variable, Identifier and Literal. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf. Basics of Python – Variable, Identifier and Literal Variable, identifier, and literal A variable is a storage location that has an associated symbolic name (called &#8220;identifier&#8221;), which contains [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this Page, We are Providing Basics of Python – Variable, Identifier and Literal. Students can visit for more Detail and Explanation of <a href="https://python-programs.com/python-handwritten-notes/">Python Handwritten Notes</a> Pdf.</p>
<h2>Basics of Python – Variable, Identifier and Literal</h2>
<p><strong>Variable, identifier, and literal</strong></p>
<p>A variable is a storage location that has an associated symbolic name (called &#8220;identifier&#8221;), which contains some value (can be literal or other data) that can change. An identifier is a name used to identify a variable, function, class, module, or another object. Literal is a notation for constant values of some built-in type. Literal can be string, plain integer, long integer, floating-point number, imaginary number. For e.g., in the expressions</p>
<pre>var1=5 
var2= 'Tom'</pre>
<p>var1 and var2 are identifiers, while 5 and &#8216; Tom&#8217; are integer and string literals, respectively.</p>
<p>Consider a scenario where a variable is referenced by the identifier a and the variable contains a list. If the same variable is referenced by the identifier b as well, and if an element in the list is changed, the change will be reflected in both identifiers of the same variable.</p>
<pre>&gt;&gt;&gt; a = [1, 2, 3]
&gt;&gt;&gt; b =a 
&gt;&gt;&gt; b 
[1, 2, 3]
&gt;&gt; a [ 1 ] =10
&gt;&gt;&gt; a
[1, 10, 3]
&gt;&gt;&gt; b
[1, 10, 3]</pre>
<p>Now, the above scenario can be modified a bit, where a and b are two different variables.</p>
<pre>&gt;&gt;&gt; a= [1,2,3 ]
&gt;&gt;&gt; b=a[:] # Copying data from a to b.
&gt;&gt;&gt; b 
[1, 2, 3]
&gt;&gt;&gt; a [1] =10 
&gt;&gt;&gt; a 
(1, 10, 3]
&gt;&gt;&gt; b
[1, 2, 3]</pre>
<p>There are some rules that need to be followed for valid identifier naming:</p>
<ul>
<li>The first character of the identifier must be a letter of the alphabet (uppercase or lowercase) or an underscore (&#8216;_&#8217;).</li>
<li>The rest of the identifier name can consist of letters (uppercase or lowercase character), underscores (&#8216;_&#8217;), or digits (0-9).</li>
<li>Identifier names are case-sensitive. For example, myname and myName are not the same.</li>
<li>Identifiers can be of unlimited length.</li>
</ul>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2803</post-id>	</item>
		<item>
		<title>Python Programming – Introduction to Python</title>
		<link>https://python-programs.com/python-programming-introduction-to-python/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Jul 2026 04:45:03 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=2799</guid>

					<description><![CDATA[In this Page, We are Providing Python Programming – Introduction to Python. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf. Python Programming – Introduction to Python Open-source software Before stepping into the world of programming using open source tools, one should try to understand the definition of open-source software given [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this Page, We are Providing Python Programming – Introduction to Python. Students can visit for more Detail and Explanation of <a href="https://python-programs.com/python-handwritten-notes/">Python Handwritten Notes</a> Pdf.</p>
<h2>Python Programming – Introduction to Python</h2>
<p><strong>Open-source software</strong></p>
<p>Before stepping into the world of programming using open source tools, one should try to understand the definition of open-source software given by &#8220;Open Source Initiative&#8221; (abbreviated as OSI). OSI is a non-profit corporation with global scope, formed to educate about and advocate the benefits of open source software, and to build bridges among different constituencies in the open-source community.</p>
<p>Open-source software is a defined as software whose source code is made available under a license that allows modification and re-distribution of the software at will. Sometimes a distinction is made between open source software and free software as given by GNU {http://www.gnu.org/). The detailed distribution terms of open-source software given by OSI are given on the website link: http://opensource. org/.</p>
<p><strong>Python(x,y)</strong></p>
<p>&#8220;Python(x,y)&#8221; is a free scientific and engineering development software for numerical computations, data analysis, and data visualization based on Python programming language and Spyder interactive development environment, the launcher (current version 2.7.6.0) is shown in figure 1-5. The executable file of Python(x,y) can be downloaded and then installed from the website link: http://code.google.eom/p/pythonxy/. The main features of Python(x,y) are:</p>
<ul>
<li>Bundled with scientific-oriented Python libraries and development environment tools.</li>
<li>Extensive documentation of various Python packages.</li>
<li>Providing an all-in-one setup program, so that the user can install or uninstall all these packages and features by clicking one button only.</li>
</ul>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-2800 size-full" src="https://python-programs.com/wp-content/uploads/2021/04/Python-img-5.png" alt="Python Handwritten Notes Chapter 1 img 5" width="296" height="460" srcset="https://python-programs.com/wp-content/uploads/2021/04/Python-img-5.png 296w, https://python-programs.com/wp-content/uploads/2021/04/Python-img-5-193x300.png 193w" sizes="auto, (max-width: 296px) 100vw, 296px" /></p>
<p><strong>EBNF</strong></p>
<p>A &#8220;syntactic metalanguage&#8221; is a notation for defining the syntax of a language by the use of a number of rules. A syntactic metalanguage is an important tool of computer science. Since the definition of the programming language &#8220;Algol 60&#8221;, it has been a custom to define the syntax of a programming language formally. Algol 60 was defined with a notation now known as &#8220;Backus-Naur Form&#8221; (BNF). This notation has proved a suitable basis for subsequent languages but has frequently been extended or slightly altered.</p>
<p>There are many different notations that are confusing and have prevented the advantages of formal unambiguous definitions from being widely appreciated. &#8220;Extended BNF&#8221; (abbreviated as EBNF, based on Backus-Naur Form) brings some order to the formal definition of the syntax and is useful not just for the definition of programming languages, but for many other formal definitions. Please refer international standard document (ISO/IEC 14977:1996(E)) for detailed information on EBNF (website link: http://standards.iso.org/ittf/PubliclyAvailobleStandards/).</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2799</post-id>	</item>
		<item>
		<title>Python Data Persistence &#8211; @Property DGCOrator</title>
		<link>https://python-programs.com/python-data-persistence-property-dgcorator/</link>
		
		<dc:creator><![CDATA[Prasanna]]></dc:creator>
		<pubDate>Thu, 09 Nov 2023 13:13:37 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8283</guid>

					<description><![CDATA[Python Data Persistence &#8211; @Property DGCOrator Although a detailed discussion on decorators is beyond the scope of this book, a brief introduction is necessary before we proceed to use @property decorator. The function is often termed a callable object. A function is also a passable object. Just as we pass a built-in object viz. number, [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2>Python Data Persistence &#8211; @Property DGCOrator</h2>
<p>Although a detailed discussion on decorators is beyond the scope of this book, a brief introduction is necessary before we proceed to use @property decorator.</p>
<p>The function is often termed a callable object. A function is also a passable object. Just as we pass a built-in object viz. number, string, list, and so on. as an argument to a function, we can define a function that receives another function as an argument. Moreover, you can have a function defined in another function (nested function), and a function whose return value is a function itself. Because of all these features, a function is called a first-order object.</p>
<p>The decorator function receives a function argument. The behavior of the argument function is then extended by wrapping it in a nested function. Definition of function subjected to decoration is preceded by name of decorator prefixed with @ symbol.<br />
Python-OOP &#8211; 113</p>
<p><strong>Example</strong></p>
<pre>def adecorator(function): 
def wrapper():
function() 
return wrapper 
@adecorator 
def decorate( ): 
pass</pre>
<p>We shall now use the property ( ) function as a decorator and define a name () method acting as a getter method for my name attribute in my class. py code above.</p>
<p><strong>Example</strong></p>
<pre>@property 
def name(self):
return self. ___myname
@property 
def age(self):
return self. __myage</pre>
<p>A property object’s getter, setter, and deleter methods are also decorators. Overloaded name ( ) and age ( ) methods are decorated with name, setter, and age. setter decorators respectively.</p>
<p><strong>Example</strong></p>
<pre>@name.setter
def name(self,name):
self. ___myname=name
@age.setter
def age(self, age):
self. myage=age</pre>
<p>When @property decorator is used, separate getter and setter methods defined previously are no longer needed. The complete code of myclass.py is as below:</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">#myclass. py
class MyClass:
__slots__=['__myname', '__myage']
def__init__(self, name=None, age=None):
self.__myname=name
self.__myage=age

@property
def name(self) :
print ('name getter method')
return self.__myname

@property
def age(self) :
print ('age getter method')
return self. ___myage

@name.setter
def name(self,name):
print ('name setter method')
self.___myname=name

@age.setter
def age(self, age):
print ('age setter method')
self.__myage=age

def about(self):
print ('My name is { } and I am { } years old'.format(self. myname,self. myage))</pre>
<p>Just import above class and test the functionality of property objects using decorators.</p>
<p><strong>Example</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">&gt;&gt;&gt; from myclass import MyClass
&gt;&gt;&gt; obj1=MyClass('Ashok', 21)
&gt;&gt;&gt; obj1.about() #initial values of object's attributes
My name is Ashok and I, am 21 years old
&gt;&gt;&gt; #change age property
&gt;&gt;&gt; obj1.age=30
age setter method
&gt;&gt;&gt; #access name property
&gt;&gt;&gt; obj1.name
name getter method
'Ashok'
&gt; &gt; &gt; obj1.about()
My name is Ashok and I am 30 years old</pre>
<p>&nbsp;</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8283</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: python-programs.com @ 2026-09-15 08:38:04 by W3 Total Cache
-->