Python

Python Programming – Compound statement Functions Argument

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

Python Programming – Compound statement Functions Argument

Argument

The argument is the value passed to a function (or method) while calling the function. There are two types of arguments:

Keyword argument

Keyword argument is an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. For example, 10, 20, 30, and 40 are keyword arguments in the following calls to summation ( ) function:

>>> def summation( aa , bb , cc , dd ) : 
. . .                    print ' aa : ' , aa
. . .                    print ' bb : ' , bb
. . .                    print ' cc : ' , cc
. . .                    print ' dd : ' , dd
. . .                    total=aa+bb+cc+dd
. . .                    return total
. . .
>>> sumupl=summation( bb=20 , dd=40 , aa=10 , cc=30 )
aa : 10
bb : 20
cc : 30
dd : 40 
>>> print ' Sum is: ' , sumupl 
Sum is : 100
>>> sumup2=summation(** { ' bb ' : 20 , ' dd ' : 40 , ' aa ' : 10 , ' cc ' : 30 } ) 
aa : 10
bb : 20 
cc : 30
dd : 4 0
>>> print 'Sum is:',sumup2 
Sum is: 100

Positional argument

Positional argument is an argument that is not a keyword argument. Positional arguments can appear at the beginning of an argument list and can also be passed as elements of an iterable preceded by *. For example, 10, 20, 30 and 40 are positional arguments in the following calls to summation ( ) function:

>>> def summation ( aa , bb , cc , dd ): 
. . .           print ' aa : ' , aa
. . .           print ' bb : ' , bb
. . .           print ' cc : ' , cc
. . .           print ' dd  : ', dd
. . .           total=aa+bb+cc+dd
. . .           return total
>>> sumup3=summation( 10 , 20 , 30 , 40 )
aa : 10
bb : 20
cc : 30
dd : 40
>>> print 'Sum is:',sumup3 
Sum is : 100
>>> sumup4=summation( * ( 10 , 20 , 30 , 40 ) )
aa : 10
bb : 20
cc : 30
dd : 40
>>> print ' Sum is :  ',sumup4 
Sum is : 100

Python Programming – Scope

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

Python Programming – Scope

Scope

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one. The scope of names defined in a class block is limited to the class block. If a name is bound in a block, it is a local variable of that block. If a name is bound at the module level, it is a global variable. The variables of the module code block are local and global.

In Python, variables that are only referenced inside a function are implicitly global. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and the programmer need to explicitly declare it as global.

The scope is bit difficult to understand, the following examples might prove fruitful.

def f ( ) :
        print s
s=" I hate spam "
f ( )

The variable s is defined as the string “I hate spam”, before the function call f ( ). The only statement in f ( ) is the print statement. As there is no local variable s in f ( ), the value from the global s will be used. So the output will be the string “I hate spam”. The question is, what will happen, if the programmer changes the value of s inside of the function f ( ) ? Will it affect the global s as well? The test is in the following piece of code:

def f ( ) :
      s="Me too." 
      print s
s=" I hate spam." 
f ( )
print s

The output looks like the following. It can be observed that s in f ( ) is local variable of f ( ).

Me too.
I hate spam.

The following example tries to combine the previous two examples i.e. first access s and then assigning a value tp it in function
f ( ).

def f ( ) :
    print s 
    s="Me too." 
    print s

s=" I hate spam." 
f ( )
print s

The code will raise an exception- UnboundLocalError: local variable ‘s’ referenced before assignment

Python assumes that a local variable is required due to the assignment to s anywhere inside f ( ), so the first print statement gives the error message. Any variable which is changed or created inside of a function is local, if it has not been declared as a global variable. To tell Python to recognize the variable as global, use the keyword global, as shown in the following example.

def f ( ) :
      global s 
      print s
      s=" That's clear." 
      print s

s="Python is great ! " 
f ( )
print s

Now there is no ambiguity. The output is as follows:

Python is great !
That's clear.
That's clear.

Local variables of functions cannot be accessed from outside the function code block.

def f ( ) :
s=" I am globally not known" 
       print s
f ( )
print s

Executing the above code will give following error message- NameError : name ‘s’ is not defined

Python Programming – Exceptions

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

Python Programming – Exceptions

Exceptions

The exception is a way of breaking out of the normal flow of control of a code block in order to handle the error or other exceptional conditions. An exception is raised at the point where the error is detected.

>>> while True print ' Hello world '
SyntaxError: invalid syntax 
>>> 10 / 0

Traceback (most recent call last) : 
File "<pyshell#l>", line 1, in <module>
    10 / 0 
ZeroDivisionError: integer division or modulo by zero 
>>> 4+tt*3

Traceback (most recent call last) :
File "<pyshe11#2>", line 1, in <module>
4+tt*3
NameError: name ' tt ' is not defined 
>>> ' 5 '+7

Traceback (most recent call last) :
File "<pyshe11#3>", line 1, in <module>
' 5 '+7
TypeError: cannot concatenate ' str ' and ' int ' objects

The last line of the error message indicates what went wrong. Exceptions are of different types, and the type is printed as part of the message; the types in the above example are SyntaxError, ZeroDivisionError, NameError, and TypeError. Standard exception names are built-in identifiers (not reserved keywords). The rest of the lines provides detail based on the type of exception and what caused it.

Handling exceptions

If there is some suspicious code that may raise an exception, it can be handled by placing the suspicious code in a try compound statement. After the try clause, include an except clause, followed by a block of code that handles the problem. The following example attempts to open a file and write something in the file.

# ! / usr / bin / python 
try :
     fh = open ( " testflie " , " w " )
     fh.write ( " This is my test file for exception handling ! ! " ) 
except IOError :
print " Error: can\'t find the file or read data " 
else: 
print " Written content in the file successfully " 
fh.close ( )

Here are few important points that need to be remembered:

  • A single try statement can have multiple except clauses. This is useful when the try clause contains statements that may throw different types of exceptions.
  • A generic except clause can be provided, which handles any exception.
  • After the except clause(s), and else clause can be included. The code in the else clause is executed, if the code in the try clause does not raise an exception.

Python Programming – Basics of Python

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

Python Programming – Basics of Python

Token

A token is a string of one or more characters that is significant as a group. Consider an expression:

sum=6+2

The tokens in the above expression are given in table 2-1:

Token

Token type

Sum

Identifier

=

Assignment operator

6

Integer literal

+

Addition operator

2

Integer literal

The process of converting a sequence of characters into a sequence of tokens is called “lexical analysis”. A program or function that performs lexical analysis is called a lexical analyzer, lexer, or tokenizer. A lexer is generally combined with a parser (beyond the scope of this book), which together analyze the syntax of computer language. Python supports the following categories of tokens: NEWLINE, INDENT, DEDENT, identifiers, keywords, literals, operators, and delimiters.

Keywords

The following identifiers (as shown as output in the following code) are used as reserved words (or “keywords”) of the language, and cannot be used as ordinary identifiers.

>>> import keyword
>>> for kwd in keyword.kwlist:
. . .    print kwd
. . .
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield

One can also check if an identifier is a keyword or not using its keyword ( ) function.

>>> import keyword
>>> keyword . iskeyword ( ' hi ' )
False
>>> keyword . iskeyword ( ' print ' )
True

Delimiters

The delimiter is a character that separates and organizes items of data. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values. Table 2-11 provides a list of tokens that serves as delimiters in Python.

Delimiters

( ) [ ] @ { } , : . ; =
+= -= *= /= //= %= &= l= ∧= >>= <<= **=

The following example shows how the use of delimiters can affect the result.

 

>>> 5+6/2                                         # no delimiter used
8 . 0
>>> (5+6)/2                                      # delimiter used
5 . 5

Following are few points that a Python programmer should be aware of:

  • The period (.) can also occur in floating-point and imaginary literals.
  • The simple and augmented assignment operators, serve lexically as delimiters but also perform operations.
  • ASCII characters “, #, and \ have special meaning as part of other tokens or are otherwise significant to the lexical analyzer.
  • Whitespace is not a token but serves to delimit tokens.

Integer function

The following function operates on integers (plain and long).

int.bit_length ( )
Return the number of bits necessary to represent an integer (plain or long) in binary, excluding the sign and leading zeros.

>>> n=-37
>>> bin(n)       # bin ( ) convert' integer number to a binary string
' -0b100101 ' 
>>> n.bit_length ( )
6 
>>> n=2**31 
>>> n
2147483648L 
>>> bin(n)
'0b10000000000000000000000000000000'
>>> n.bit_length ( )
32

Float functions

Some of the functions for floating-point numbers are discussed below.

float.as_integer_ratio ( )
Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator.

>>> ( -0 .25 ) . as_integer_ratio ( )
(-1 , 4)

float.is_integer ( )
Return True if the float instance is finite with integral value, otherwise it return False.

>>> (-2 . 0) . is_integer ( )
True
>>> (3 . 2) . is_integer ( )
False

Basics of Python – Error

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

Basics of Python – Error

Error

An error (or software bug) is a fault in a computer program that produces an incorrect or unexpected result or causes it to behave in unintended ways. Most bugs arise from mistakes and errors made by people in either a program’s source code or its design. Usually, errors are classified as: syntax error, run-time error, and logical error.

Syntax error

Syntax error refers to an error in the syntax of tokens and/or sequence of tokens that are intended to be written in a particular programming language. For compiled languages, syntax errors occur strictly at compile-time. A program will not compile until all syntax errors are corrected. For interpreted languages, however, not all syntax errors can be reliably detected until run-time.

>>> prin ' Hi '
SyntaxError: invalid syntax 
>>> print " Hi '
SyntaxError: EOL while scanning string literal

Run-time error

A run-time error is an error that can be detected during the execution of a program. The code appears to be correct (it has no syntax errors), but it will not execute. For example, if a programmer has written a correct code to open a file using the open ( ) function, and if the file is corrupted, the application cannot carry out the execution of the open ( ) function, and it stops running.

Logical error

A logical error (or semantic error) is a bug in a program that causes it to operate incorrectly, but not terminate abnormally. A logical error produces an unintended or undesired output or other behavior, although it may not immediately be recognized. The logic error occurs both in compiled and interpreted languages.

Unlike a program with a syntax error, a program with a logical error is a valid program in the language, though it does not behave as intended. The only clue to the existence of logic errors in the production of wrong solutions. For example, if a program calculates the average of variables a and b, instead of writing the expression c= (a+b) / 2, one can write c=a+b / 2, which is a logical error.

>>> print a+b / 2 
6 . 5
>>> print ( a+b ) / 2
5 . 0

Basics of Python – Built-in Types

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, sequence, mapping, etc., but this book will cover few types. Schematic representation of various built-in types is shown in figure 2-1.

Python Handwritten Notes Chapter 2 img 1

Numeric types

There are three distinct numeric types: integer, floating-point number, and complex number.

Integer

Integer can be sub-classified into three types:

Plain integer

Plain integer (or simply ” integer “) 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.

>>> a=2147483647 
>>> type (a) 
<type ' int '>
>>> a=a+1
>>> type (a)
<type ' long '>
>>> a=-2147483648 
>>> type (a)
<type ' int '>
>>> a=a-1
>>> type (a)
<type ' long ’>

The built-in function int(x = 0) converts a number or string x to an integer or returns 0 if no arguments are given.

>>> a =' 57 '
>>> type (a) 
<type ' str '>
>>> a = int (a)
>>> a 
57
>>> type (a)
<type ' int '>
>>> a = 5.7
>>> type (a)
<type ' float '> 
>>> a = int (a)
>>> a 
5 
>>> type (a)
<type ' int '>
>>> int( )
0

Long integer

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.

>>> a = 5 
>>> type (a) 
<type ' int '> 
>>> a = long (a) 
>>> a 
5L
>>> type (a) 
<type ' long '> 
>>> long ( )
OL
>>> long (5)
5L
>>> long (5.8) 
5L
>>> long(' 5 ') 
5L
>>> long(' -5 ')
-5L

Integer literals with an L or 1 suffix yield long integers (L is preferred because 11 looks too much like eleven).

>>> a=10L 
>>> type (a) 
<type ' long '>
>>> a=101 
>>> type (a)
<type ' long '>

The following expressions are interesting.

>>> import sys 
>>> a=sys.maxint 
>>> a
2147483647
>>> type (a)
<type ' int '>
>>> a=a+1
>>> a
21474836 48L
>>> type (a)
<type ' long ’>

Boolean

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.

>>> bool ( ) 
False 
>>> a=5
>>> bool (a)
True
>>> bool (0)
False
>>> bool( ' hi ' )
True
>>> bool(None)
False
>>> bool(' ')
False
>>> bool(False)
False
>>> bool("False" )
True
>>> bool(5 > 3)
True

Floating point number

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.

>>> a = 57 
>>> type (a)
<type ' int '>
>>> a = float (a)
>>> a
57.0 
>>> type (a)
<type ' float '>
>>> a = ' 65 ' 
>>> type (a)
<type ' str ' > 
>>> a = float (a) 
>>> a
65.0 
>>> type (a)
<type ' float '>
>>> a = 1e308 
>>> a 
1e+30 8 
>>> type (a)
<type ' float '>
>>> a = 1e309 
>>> a
inf 
>>> type (a)
<type ' float '>

Complex number

This represents complex numbers having real and imaginary parts. The built-in function complex () is used to convert numbers or strings to complex numbers.

>>> a = 5.3
>>> a = complex (a)
>>> a 
(5 . 3 + 0 j)
>>> type (a)
<type ' complex '>
>>> a = complex ( )
>>> a
0 j 
>>> type (a)
<type ' complex '>

Appending j or J to numeric literal yields a complex number.

>>> a = 3 . 4 j 
>>> a 
3 . 4 j
>>> type (a)
<type ' complex '>
>>> a = 3 . 5 + 4 . 9 j 
>>> type (a)
<type ' complex '>
>>> a = 3 . 5+4 . 9 J
>>> type (a)
<type ' complex '>

The real and imaginary parts of a complex number z can be retrieved through the attributes z. real and z. imag.

a=3 . 5 + 4 . 9 J
>>> a . real
3 . 5
>>> a . imag 
4 . 9

Sequence Types

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.

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.

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 (), …). 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’s next () method return successive items in the stream. When no more data are available, a Stoplteration exception is raised instead.

Some of the sequence types are discussed below:

String

It is a sequence type such that its value can be characters, symbols, or numbers. Please note that string is immutable.

>>> a=' Python : 2 . 7 '
>>> type (a)
<type ' str ’>
>>> a [2 ] =' S '
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

The built-in function str (object =’ ‘ ) 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.

>>> a=57.3
>>> type(a) 
<type 'float'>
>>> a=str(a)
>>> a
' 57.3 '
>>> type (a)
<type ' str '>

Tuple

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.

>>> a=(1 , 2 , 3 ,4) 
>>> type (a)
<type ' tuple '>
'a', 'b', 'c')

List

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.

>>> a=[1, 2 ,3, 4]
>>> type(a) 
<type ' list '>

Set types

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:

Set

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.

>>> set1=set ( )                                                    # A new empty set
>>> set1.add (" cat ")                                           # Add a single member
>>> set1.update ([" dog "," mouse "])                 # Add several members
>>> set1.remove ("mouse")                                # Remove member
>>> set1
set([' dog ', ' cat '])
>>> set2=set([" dog "," mouse "])
>>> print set1&set2                                           # Intersection
set ( [' dog ' ] )
>>> print set1 | set2                                           # Union
set([' mouse ', ' dog ', ' cat '])

The set ( [ iterable ] ) return a new set object, optionally with elements taken from iterable.

Frozenset

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.

>>> frozenset ( ) 
frozenset ( [ ] )
>>> frozenset (' aeiou ') 
frozenset{ [' a ', ' i ',' e ',' u ',' o '])
>>> frozenset ( [0, 0, 0, 44, 0, 44, 18] ) 
frozenset (10, 18, 44])

The frozenset ( [iterable] ) return return a new frozenset object, optionally with elements taken from iterable.

Mapping Types

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:

Dictionary

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.

>>> dict1={"john":34,"mike":56}
>>> dict1[" michael "] = 42 
>>> dict1
{' mike ' : 56, ' john ' : 34, ' michael ' : 42}
>>> dictl[" mike "]
56

None

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.

Some other built-in types such as function, method, class, class instance, file, module, etc. are discussed in later chapters.

Check If there are Duplicates in a List

Python Check If there are Duplicates in a List

Lists are similar to dynamically sized arrays (e.g., vector in C++ and ArrayList in Java) that are declared in other languages. Lists don’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’ve been formed.

Duplicates are integers, strings, or items in a list that are repeated more than once.

Given a list, the task is to check whether it has any duplicate element in it.

Examples:

Input:

givenlist=["hello", "this", "is", "BTechGeeks" , "hello"]

Output:

True

Explanation:

hello is repeated twice so the answer is Yes

Check whether list contains any repeated values

There are several ways to check duplicate elements some of them are:

Method #1 :Using list and count() function

The list class in Python has a method count() that returns the frequency count of a given list element.

list.count(Element)

It returns the number of times an element appears in the list.

Approach:

The idea is to iterate over all of the list’s elements and count the number of times each element appears.

If the count is greater than one, this element has duplicate entries.

Below is the implementation:

# 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) > 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))

Output:

True

Time Complexity : O(n^2)

Method #2 : Using set()

Follow the steps below to see if a list contains any duplicate elements.

If the list does not contain any unhashable objects, such as list, use set().

When a list is passed to set(), the function returns set, which ignores duplicate values and keeps only unique values as elements..

Using the built-in function len(), calculate the number of elements in this set and the original list and compare them.

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.

The following is the function that returns False if there are no duplicate elements and True if there are duplicate elements:

# 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))

Output:

True

Time Complexity : O(n(log(n))

Method #3: Using Counter() function from collections (Hashing)

Calculate the frequencies of all elements using Counter() function which will be stored as frequency dictionary.

If the length of frequency dictionary is equal to length of list then it has no duplicates.

Below is the implementation:

# 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))

Output:

True

Time Complexity : O(n)
Related Programs:

Related Programs:

Basics of Python – Line Structure

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 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 “blank line”. The following code

>>> i=5 
>>> print (5)
5

is the same as:

>>> i=5; print (i)
5

A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.

Explicit line joining

Two or more physical lines may be joined into logical lines using backslash characters (\), as shown in the following example:

>>> if 1900 < year < 2100 and 1 <= month <= 12 \
. . .   and 1 <= day <= 31 and 0 <= hour < 24 \
. . .   and 0 <= minute < 60 and 0 <= second < 60 :
. . .   print year

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.

>>> str=' This is a \
. . .    string example ' 
>>> str
' This is a string example'

Implicit line joining

Expressions in parentheses, square brackets, or curly braces can be split over more than one physical line without using backslashes. For example:

>>> 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

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.

>>> str=" " "This is 
. . . a string 
. . . example" " "
>>> str
' This is \na string \nexample'
>>> str='' 'This is 
. . . a string 
. . . example'' '
>>> str
' This is \na string \nexample'

Comment

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.

Indentation

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).

>>> i=10
>>> print "Value is ",i 
Value is 10 
>>> print "Value is ",i 
File "<stdin>", line 1
print "Value is ",i 
∧
IndentationError: unexpected indent

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.

The following example shows non-uniform indentation is not an error.

var=100 
>>> if var!=100:
. . .  print 'var does not have value 100'
. . .  else:
. . .                 print 'var has value 100'
. . . 
var has value 100

Need for indentation

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.

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.

How to Make a Discord Bot Python

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.

What Is Discord?

Discord is a voice and text communication platform for gamers.

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.

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.

What Is a Bot?

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.

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 unlimited application.

How to Make a Discord Bot in the Developer Portal:

Before you can dive into any Python code to handle events and create exciting automations, you need to first create a few Discord components:

  1. An account
  2. An application
  3. A bot
  4. A guild

You’ll learn more about each piece in the following sections.

Once you’ve created all of these components, you’ll tie them together by registering your bot with your guild.

Creating a Discord Account

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:

Creating-a-Discord-Account

If you need to create a new account, then click on the Register button below Login and enter your account information.

Once you’re finished, you’ll be redirected to the Developer Portal home page, where you’ll create your application.

Creating-a-Discord-Account-login

Creating an Application:

An application allows you to interact with Discord’s APIs by providing authentication tokens, designating permissions, and so on.

To create a new application, select New Application:

Creating-a-Discord-Account-application

Next, you’ll be prompted to name your application. Select a name and click Create:

Creating-a-Discord-Account-login-creating

Congratulations! You made a Discord application. On the resulting screen, you can see information about your application:

Creating-a-Discord-Account-login-done.png

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.

However, since this tutorial is about how to make a Discord bot, navigate to the Bot tab on the left-hand navigation list.

Creating a Bot

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.

For your code to actually be manifested on Discord, you’ll need to create a bot user. To do so, select Add Bot:

Creating-a-Discord-boat

Once you confirm that you want to add the bot to your application, you’ll see the new bot user in the portal:

Creating-a-Discord-account-new-boat-user

Now, the bot’s all set and ready to go, but to where?

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.

Creating a Guild

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.

You’d start by creating a guild. Then, in your guild, you could have multiple channels, such as:

  • General Discussion: A channel for users to talk about whatever they want
  • Spoilers, Beware: A channel for users who have finished your game to talk about all the end game reveals
  • Announcements: A channel for you to announce game updates and for users to discuss them

Once you’ve created your guild, you’d invite other users to populate it.

So, to create a guild, head to your Discord home page:

Creating-a-Discord-home-page

From this home page, you can view and add friends, direct messages, and guilds. From here, select the + icon on the left-hand side of the web page to Add a Server:

This will present two options, Create a server and Join a Server. In this case, select Create a server and enter a name for your guild.

Creating-a-Discord-creating-a-server

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.

The final step on Discord is to register your bot with your new guild.

Adding a Bot to a Guild

A bot can’t accept invites like a normal user can. Instead, you’ll add your bot using the OAuth2 protocol.

To do so, head back to the Developer Portal and select the OAuth2 page from the left-hand navigation:

Add your bot using the OAuth2 protocol.

From this window, you’ll see the OAuth2 URL Generator.

This tool generates an authorization URL that hits Discord’s OAuth2 API and authorizes API access using your application’s credentials.

In this case, you’ll want to grant your application’s bot user access to Discord APIs using your application’s OAuth2 credentials.

To do this, scroll down and select bot from the SCOPES options and Administrator from BOT PERMISSIONS:

BOT PERMISSIONS

Now, Discord has generated your application’s authorization URL with the selected scope and permissions.

Select Copy beside the URL that was generated for you, paste it into your browser, and select your guild from the dropdown options:

Creating-a-Discord-select-your-grid

Click Authorize, and you’re done!

 

Authorized
If you go back to your guild, then you’ll see that the bot has been added:

Bot added

In summary, you’ve created:

  • An application that your bot will use to authenticate with Discord’s APIs
  • A bot user that you’ll use to interact with other users and events in your guild
  • A guild in which your user account and your bot user will be active
  • ADiscordaccount with which you created everything else and that you’ll use to interact with your bot

Now, you know how to make a Discord bot using the Developer Portal. Next comes the fun stuff: implementing your bot in Python!

How to Make a Discord Bot in Python

Since you’re learning how to make a Discord bot with Python, you’ll be using discord.py.

discord.py 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

Begin by installing discord.py with pip:

$ pip install -U discord.py

Now that you’ve installed discord.py, you’ll use it to create your first connection to Discord!

Creating a Discord Connection

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:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

client.run(TOKEN)

A Client is an object that represents a connection to Discord. A Client handles events, tracks state, and generally interacts with Discord APIs.

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.

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.

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:

  • Avoid putting the secrets into source control
  • Use different variables for development and production environments without changing your code

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.

Create a file named .env in the same directory as bot.py:

You’ll need to replace {your-bot-token} with your bot’s token, which you can get by going back to the Bot page on the Developer portal and clicking Copy under the TOKEN section:

 Creating-a-Discord-adding-bot-token

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.

Install dotenv with pip:

pip install -U python-dotenv

Finally, client.run() runs your Client using your bot’s token.

Now that you’ve set up both bot.py and .env, you can run your code:

python bot.py
Shikhaboat#5531 has connected to Discord!

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.

Interacting With Discord APIs

Using a Client, you have access to a wide range of Discord APIs.

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.

First, you’ll need to add a new environment variable:

# .env
DISCORD_TOKEN={your-bot-token}
DISCORD_GUILD={your-guild-name}

Don’t forget that you’ll need to replace the two placeholders with actual values:

  1. {your-bot-token}
  2. {your-guild-name}

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():

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

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.

Run the program to see the results:

 python bot.py
Shikhaboat#5531 is connected to the following guild:
Shikhaboat#5531(id: 571759877328732195)

Great! You can see the name of your bot, the name of your server, and the server’s identification number.

Another interesting bit of data you can pull from a guild is the list of users who are members of the guild:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})\n'
    )

    members = '\n - '.join([member.name for member in guild.members])
    print(f'Guild Members:\n - {members}')

client.run(TOKEN)

By looping through guild.members, you pulled the names of all of the members of the guild and printed them with a formatted string.

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:

$ python bot.py
Shikhaboat#5531 is connected to the following guild:
Shikhaboat#5531(id: 571759877328732195)
Guild Members:
 - aronq2
 - RealPythonTutorialBot

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.

Next, you’ll learn about some utility functions and how they can simplify these examples.

Using Utility Functions

Let’s take another look at the example from the last section where you printed the name and identifier of the bot’s guild:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

You could clean up this code by using some of the utility functions available in discord.py.

discord.utils.find is one utility that can improve the simplicity and readability of this code by replacing the for loop with an intuitive, abstracted function:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    guild = discord.utils.find(lambda g: g.name == GUILD, client.guilds)
    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

<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.

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.

discord.py has even abstracted this concept one step further with the get.utility():

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    guild = discord.utils.get(client.guilds, name=GUILD)
    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

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.

In this example, you’ve identified name=GUILD as the attribute that must be satisfied.

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: on_ready().

Responding to Events

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.

But what is an event?

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.

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.

So, when Discord fires an event, discord.py will route the event data to the corresponding event handler on your connected Client.

There are two ways in discord.py to implement an event handler:

  1. Using the client.event decorator
  2. Creating a subclass of Client and overriding its handler methods

You already saw the implementation using the decorator. Next, take a look at how to subclass Client:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

class CustomClient(discord.Client):
    async def on_ready(self):
        print(f'{self.user} has connected to Discord!')

client = CustomClient()
client.run(TOKEN)

Here, just like before, you’ve created a client variable and called <.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.

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.

Welcoming New Members

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.

Now, you’ll implement that behavior in your Client, using event handlers, and verify its behavior in Discord:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to my Discord server!'
    )

client.run(TOKEN)

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.

on_member_join(), as its name suggests, handles the event of a new member joining a guild.

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.

Now, let’s test out your bot’s new behavior.

First, run your new version of bot.py and wait for the on_ready() event to fire, logging your message to stdout:

$ python bot.py
ShikhaBot has connected to Discord!

Now, head over to Discord, log in, and navigate to your guild by selecting it from the left-hand side of the screen:

Creating-a-Discord-navigate-to-server

Select Invite People just beside the guild list where you selected your guild. Check the box that says Set this link to never expire and copy the link:

InvitePepole

Now, with the invite link copied, create a new account and join the guild using your invite link.

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:

 Creating-a-Discord-account-new-message.
When you select it, you’ll see a private message from your bot user:

 Boat-is-created

Perfect! Your bot user is now interacting with other users with minimal code.

Conclusion

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.

 

Understanding the Two Sum Problem

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) & 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 that each input would have exactly one solution and you are not going to use same element twice.

Example:

Given numbers=[ 3 , 4 , 6 ,7 ] , target = 7,

Because num[0]+num[1] = 3 + 4 = 7,

return[0,1]

Example has given above we have to execute two sum problem for any two number in list and give us targeted value.

There are mainly two way to execute two sum problem.

  1. Using Naive Method
  2. Using hash table

Implementing Naive Method:

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(n2).

So for this we will write an algorithm which mentioned below-

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))

Output:

C:\New folder\Python project(APT)>py twosum.py
[0, 1]

C:\New folder\Python project(APT)>

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.

So for increasing complexity we will use second method which is hash table.

Implementing hash table:

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.

Example:

If the array is: [6, 7, 1, 8] and the sum is 8.
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))

Output:

C:\New folder\Python project(APT)>py twosum.py [1, 2] 
C:\New folder\Python project(APT)>

So you can see that above program gives us index value of the two number which gives us our target value.

Conclusion:

Great!So in this article we have seen two methods for two sum problem in python.Naive method has complexity O(n2)and Hash metod has complexity O(n),So best approach is Hash method and worst is Naive method.