Author: Saim Khalid

  • Modify Strings

    String modification refers to the process of changing the characters of a string. If we talk about modifying a string in Python, what we are talking about is creating a new string that is a variation of the original one.

    In Python, a string (object of str class) is of immutable type. Here, immutable refers to an object thatcannotbe modified in place once it’s created in memory. Unlike a list, we cannot overwrite any character in the sequence, nor can we insert or append characters to it directly. If we need to modify a string, we will use certain string methods that return anewstring object. However, the original string remains unchanged.

    We can use any of the following tricks as a workaround to modify a string.

    Converting a String to a List

    Both strings and lists in Python are sequence types, they are interconvertible. Thus, we can cast a string to a list, modify the list using methods like insert()append(), or remove() and then convert the list back to a string to obtain a modified version.

    Suppose, we have a string variable s1 with WORD as its value and we are required to convert it into a list. For this operation, we can use the list() built-in function and insert a character L at index 3. Then, we can concatenate all the characters using join() method of str class.

    Example

    The below example practically illustrates how to convert a string into a list.

    s1="WORD"print("original string:", s1)
    l1=list(s1)
    
    l1.insert(3,"L")print(l1)
    
    s1=''.join(l1)print("Modified string:", s1)

    It will produce the following output −

    original string: WORD
    ['W', 'O', 'R', 'L', 'D']
    Modified string: WORLD

    Using the Array Module

    To modify a string, construct an array object using the Python standard library named array module. It will create an array of Unicode type from a string variable.

    Example

    In the below example, we are using array module to modify the specified string.

    import array as ar
    
    # initializing a string
    s1="WORD"print("original string:", s1)# converting it to an array
    sar=ar.array('u', s1)# inserting an element
    sar.insert(3,"L")# getting back the modified string
    s1=sar.tounicode()print("Modified string:", s1)

    It will produce the following output −

    original string: WORD
    Modified string: WORLD
    

    Using the StringIO Class

    Python’s io module defines the classes to handle streams. The StringIO class represents a text stream using an in-memory text buffer. A StringIO object obtained from a string behaves like a File object. Hence we can perform read/write operations on it. The getvalue() method of StringIO class returns a string.

    Example

    Let us use the above discussed principle in the following program to modify a string.

    import io
    
    s1="WORD"print("original string:", s1)
    
    sio=io.StringIO(s1)
    sio.seek(3)
    sio.write("LD")
    s1=sio.getvalue()print("Modified string:", s1)

    It will produce the following output −

    original string: WORD
    Modified string: WORLD
  •  Slicing Strings

    Python String slicing is a way of creating a sub-string from a given string. In this process, we extract a portion or piece of a string. Usually, we use the slice operator “[ : ]” to perform slicing on a Python String. Before proceeding with string slicing let’s understand string indexing.

    In Python, a string is an ordered sequence of Unicode characters. Each character in the string has a unique index in the sequence. The index starts with 0. First character in the string has its positional index 0. The index keeps incrementing towards the end of string.

    If a string variable is declared as var=”HELLO PYTHON”, index of each character in the string is as follows −

    string index representation

    Python String Indexing

    Python allows you to access any individual character from the string by its index. In this case, 0 is the lower bound and 11 is the upper bound of the string. So, var[0] returns H, var[6] returns P. If the index in square brackets exceeds the upper bound, Python raises IndexError.

    Example

    In the below example, we accessing the characters of a string through index.

    var ="HELLO PYTHON"print(var[0])print(var[7])print(var[11])print(var[12])

    On running the code, it will produce the following output −

    H
    Y
    N
    ERROR!
    Traceback (most recent call last):
      File "<main.py>", line 5, in <module>
    IndexError: string index out of range

    Python String Negative & Positive Indexing

    One of the unique features of Python sequence types (and therefore a string object) is that it has a negative indexing scheme also. In the example above, a positive indexing scheme is used where the index increments from left to right. In case of negative indexing, the character at the end has -1 index and the index decrements from right to left, as a result the first character H has -12 index.

    positive negative indexing

    Example

    Let us use negative indexing to fetch N, Y, and H characters.

    var ="HELLO PYTHON"print(var[-1])print(var[-5])print(var[-12])

    On executing the above code, it will give the following result −

    N
    Y
    H
    

    We can therefore use positive or negative index to retrieve a character from the string.

    In Python, string is an immutable object. The object is immutable if it cannot be modified in-place, once stored in a certain memory location. You can retrieve any character from the string with the help of its index, but you cannot replace it with another character.

    Example

    In the following example, character Y is at index 7 in HELLO PYTHON. Try to replace Y with y and see what happens.

    var="HELLO PYTHON"
    var[7]="y"print(var)

    It will produce the following output −

    Traceback (most recent call last):
     File "C:\Users\users\example.py", line 2, in <module>
      var[7]="y"
      ~~~^^^
    TypeError: 'str' object does not support item assignment
    

    The TypeError is because the string is immutable.

    Python String Slicing

    Python defines “:” as string slicing operator. It returns a substring from the original string. Its general usage is as follows −

    substr=var[x:y]

    The “:” operator needs two integer operands (both of which may be omitted, as we shall see in subsequent examples). The first operand x is the index of the first character of the desired slice. The second operand y is the index of the character next to the last in the desired string. So var(x:y] separates characters from xth position to (y-1)th position from the original string.

    Example

    var="HELLO PYTHON"print("var:",var)print("var[3:8]:", var[3:8])

    It will produce the following output −

    var: HELLO PYTHON
    var[3:8]: LO PY
    

    Python String Slicing With Negative Indexing

    Like positive indexes, negative indexes can also be used for slicing.

    Example

    The below example shows how to slice a string using negative indexes.

    var="HELLO PYTHON"print("var:",var)print("var[3:8]:", var[3:8])print("var[-9:-4]:", var[-9:-4])

    It will produce the following output −

    var: HELLO PYTHON
    var[3:8]: LO PY
    var[-9:-4]: LO PY
    

    Default Values of Indexes with String Slicing

    Both the operands for Python’s Slice operator are optional. The first operand defaults to zero, which means if we do not give the first operand, the slice starts of character at 0th index, i.e. the first character. It slices the leftmost substring up to “y-1” characters.

    Example

    In this example, we are performing slice operation using default values.

    var="HELLO PYTHON"print("var:",var)print("var[0:5]:", var[0:5])print("var[:5]:", var[:5])

    It will produce the following output −

    var: HELLO PYTHON
    var[0:5]: HELLO
    var[:5]: HELLO
    

    Example

    Similarly, y operand is also optional. By default, it is “-1”, which means the string will be sliced from the xth position up to the end of string.

    var="HELLO PYTHON"print("var:",var)print("var[6:12]:", var[6:12])print("var[6:]:", var[6:])

    It will produce the following output −

    var: HELLO PYTHON
    var[6:12]: PYTHON
    var[6:]: PYTHON
    

    Example

    Naturally, if both the operands are not used, the slice will be equal to the original string. That’s because “x” is 0, and “y” is the last index+1 (or -1) by default.

    var="HELLO PYTHON"print("var:",var)print("var[0:12]:", var[0:12])print("var[:]:", var[:])

    It will produce the following output −

    var: HELLO PYTHON
    var[0:12]: HELLO PYTHON
    var[:]: HELLO PYTHON
    

    Example

    The left operand must be smaller than the operand on right, for getting a substring of the original string. Python doesn’t raise any error, if the left operand is greater, bu returns a null string.

    Open Compiler

    var="HELLO PYTHON"print("var:",var)print("var[-1:7]:", var[-1:7])print("var[7:0]:", var[7:0])

    It will produce the following output −

    var: HELLO PYTHON
    var[-1:7]:
    var[7:0]:
    

    Return Type of String Slicing

    Slicing returns a new string. You can very well perform string operations like concatenation, or slicing on the sliced string.

    Example

    var="HELLO PYTHON"print("var:",var)print("var[:6][:2]:", var[:6][:2])
    
    var1=var[:6]print("slice:", var1)print("var1[:2]:", var1[:2])

    It will produce the following output −

    var: HELLO PYTHON
    var[:6][:2]: HE
    slice: HELLO
    var1[:2]: HE
  •  Strings

    In Python, a string is an immutable sequence of Unicode characters. Each character has a unique numeric value as per the UNICODE standard. But, the sequence as a whole, doesn’t have any numeric value even if all the characters are digits. To differentiate the string from numbers and other identifiers, the sequence of characters is included within single, double or triple quotes in its literal representation. Hence, 1234 is a number (integer) but ‘1234’ is a string.

    Creating Python Strings

    As long as the same sequence of characters is enclosed, single or double or triple quotes don’t matter. Hence, following string representations are equivalent.

    Example

    >>>'Welcome To TutorialsPoint''Welcome To TutorialsPoint'>>>"Welcome To TutorialsPoint"'Welcome To TutorialsPoint'>>>'''Welcome To TutorialsPoint''''Welcome To TutorialsPoint'>>>"""Welcome To TutorialsPoint"""'Welcome To TutorialsPoint'

    Looking at the above statements, it is clear that, internally Python stores strings as included in single quotes.

    In older versions strings are stored internally as 8-bit ASCII, hence it is required to attach ‘u’ to make it Unicode. Since Python 3, all strings are represented in Unicode. Therefore, It is no longer necessary now to add ‘u’ after the string.

    Accessing Values in Strings

    Python does not support a character type; these are treated as strings of length one, thus also considered a substring.

    To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −

    Open Compiler

    var1 ='Hello World!'
    var2 ="Python Programming"print("var1[0]: ", var1[0])print("var2[1:5]: ", var2[1:5])

    When the above code is executed, it produces the following result −

    var1[0]:  H
    var2[1:5]:  ytho
    

    Updating Strings

    You can “update” an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example −

    Open Compiler

    var1 ='Hello World!'print("Updated String :- ", var1[:6]+'Python')

    When the above code is executed, it produces the following result −

    Updated String :-  Hello Python
    

    Visit our Python – Modify Strings tutorial to know more about updating/modifying strings.

    Escape Characters

    Following table is a list of escape or non-printable characters that can be represented with backslash notation.

    An escape character gets interpreted; in a single quoted as well as double quoted strings.

    Backslash notationHexadecimal characterDescription
    \a0x07Bell or alert
    \b0x08Backspace
    \cxControl-x
    \C-xControl-x
    \e0x1bEscape
    \f0x0cFormfeed
    \M-\C-xMeta-Control-x
    \n0x0aNewline
    \nnnOctal notation, where n is in the range 0.7
    \r0x0dCarriage return
    \s0x20Space
    \t0x09Tab
    \v0x0bVertical tab
    \xCharacter x
    \xnnHexadecimal notation, where n is in the range 0.9, a.f, or A.F

    String Special Operators

    Assume string variable a holds ‘Hello’ and variable b holds ‘Python’, then −

    OperatorDescriptionExample
    &plus;Concatenation – Adds values on either side of the operatora &plus; b will give HelloPython
    *Repetition – Creates new strings, concatenating multiple copies of the same stringa*2 will give -HelloHello
    []Slice – Gives the character from the given indexa[1] will give e
    [ : ]Range Slice – Gives the characters from the given rangea[1:4] will give ell
    inMembership – Returns true if a character exists in the given stringH in a will give 1
    not inMembership – Returns true if a character does not exist in the given stringM not in a will give 1
    r/RRaw String – Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter “r,” which precedes the quotation marks. The “r” can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.print r’\n’ prints \n and print R’\n’prints \n
    %Format – Performs String formattingSee at next section

    String Formatting Operator

    One of Python’s coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C’s printf() family. Following is a simple example −

    Open Compiler

    print("My name is %s and weight is %d kg!"%('Zara',21))

    When the above code is executed, it produces the following result −

    My name is Zara and weight is 21 kg!
    

    Here is the list of complete set of symbols which can be used along with % −

    Sr.No.Format Symbol & Conversion
    1%ccharacter
    2%sstring conversion via str() prior to formatting
    3%isigned decimal integer
    4%dsigned decimal integer
    5%uunsigned decimal integer
    6%ooctal integer
    7%xhexadecimal integer (lowercase letters)
    8%Xhexadecimal integer (UPPERcase letters)
    9%eexponential notation (with lowercase ‘e’)
    10%Eexponential notation (with UPPERcase ‘E’)
    11%ffloating point real number
    12%gthe shorter of %f and %e
    13%Gthe shorter of %f and %E

    Other supported symbols and functionality are listed in the following table −

    Sr.No.Symbol & Functionality
    1*argument specifies width or precision
    2left justification
    3&plus;display the sign
    4<sp>leave a blank space before a positive number
    5#add the octal leading zero ( ‘0’ ) or hexadecimal leading ‘0x’ or ‘0X’, depending on whether ‘x’ or ‘X’ were used.
    60pad from left with zeros (instead of spaces)
    7%‘%%’ leaves you with a single literal ‘%’
    8(var)mapping variable (dictionary arguments)
    9m.n.m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

    Visit our Python – String Formatting tutorial to learn about various ways to format strings.

    Double Quotes in Python Strings

    You want to embed some text in double quotes as a part of string, the string itself should be put in single quotes. To embed a single quoted text, string should be written in double quotes.

    Example

    var ='Welcome to "Python Tutorial" from TutorialsPoint'print("var:", var)
    
    var ="Welcome to 'Python Tutorial' from TutorialsPoint"print("var:", var)

    It will produce the following output −

    var: Welcome to "Python Tutorial" from TutorialsPoint
    var: Welcome to 'Python Tutorial' from TutorialsPoint
    

    Triple Quotes

    To form a string with triple quotes, you may use triple single quotes, or triple double quotes − both versions are similar.

    Example

    var ='''Welcome to TutorialsPoint'''print("var:", var)
    
    var ="""Welcome to TutorialsPoint"""print("var:", var)

    It will produce the following output −

    var: Welcome to TutorialsPoint
    var: Welcome to TutorialsPoint
    

    Python Multiline Strings

    Triple quoted string is useful to form a multi-line string.

    Example

    var ='''
    Welcome To
    Python Tutorial
    from TutorialsPoint
    '''print("var:", var)

    It will produce the following output −

    var:
    Welcome To
    Python Tutorial
    from TutorialsPoint
    

    Arithmetic Operators with Strings

    A string is a non-numeric data type. Obviously, we cannot use arithmetic operators with string operands. Python raises TypeError in such a case.

    print("Hello"-"World")

    On executing the above program it will generate the following error −

    >>> "Hello"-"World"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for -: 'str' and 'str'
    

    Getting Type of Python Strings

    A string in Python is an object of str class. It can be verified with type() function.

    Example

    var ="Welcome To TutorialsPoint"print(type(var))

    It will produce the following output −

    <class 'str'>
    

    Built-in String Methods

    Python includes the following built-in methods to manipulate strings −

    Sr.No.Methods with Description
    1capitalize()Capitalizes first letter of string.
    2casefold()Converts all uppercase letters in string to lowercase. Similar to lower(), but works on UNICODE characters alos.
    3center(width, fillchar)Returns a space-padded string with the original string centered to a total of width columns.
    4count(str, beg= 0,end=len(string))Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
    5decode(encoding=’UTF-8′,errors=’strict’)Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.
    6encode(encoding=’UTF-8′,errors=’strict’)Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.
    7endswith(suffix, beg=0, end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
    8expandtabs(tabsize=8)Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
    9find(str, beg=0 end=len(string))Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
    10format(*args, **kwargs)This method is used to format the current string value.
    11format_map(mapping)This method is also use to format the current string the only difference is it uses a mapping object.
    12index(str, beg=0, end=len(string))Same as find(), but raises an exception if str not found.
    13isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
    14isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
    15isascii()Returns True is all the characters in the string are from the ASCII character set.
    16isdecimal()Returns true if a unicode string contains only decimal characters and false otherwise.
    17isdigit()Returns true if string contains only digits and false otherwise.
    18isidentifier()Checks whether the string is a valid Python identifier.
    19islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
    20isnumeric()Returns true if a unicode string contains only numeric characters and false otherwise.
    21isprintable()Checks whether all the characters in the string are printable.
    22isspace()Returns true if string contains only whitespace characters and false otherwise.
    23istitle()Returns true if string is properly “titlecased” and false otherwise.
    24isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
    25join(seq)Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.
    26ljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns.
    27lower()Converts all uppercase letters in string to lowercase.
    28lstrip()Removes all leading white space in string.
    29maketrans()Returns a translation table to be used in translate function.
    30partition()Splits the string in three string tuple at the first occurrence of separator.
    31removeprefix()Returns a string after removing the prefix string.
    32removesuffix()Returns a string after removing the suffix string.
    33replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given.
    34rfind(str, beg=0,end=len(string))Same as find(), but search backwards in string.
    35rindex( str, beg=0, end=len(string))Same as index(), but search backwards in string.
    36rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.
    37rpartition()Splits the string in three string tuple at the ladt occurrence of separator.
    38rsplit()Splits the string from the end and returns a list of substrings.
    39rstrip()Removes all trailing whitespace of string.
    40split(str=””, num=string.count(str))Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.
    41splitlines( num=string.count(‘\n’))Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
    42startswith(str, beg=0,end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.
    43strip([chars])Performs both lstrip() and rstrip() on string.
    44swapcase()Inverts case for all letters in string.
    45title()Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.
    46translate(table, deletechars=””)Translates string according to translation table str(256 chars), removing those in the del string.
    47upper()Converts lowercase letters in string to uppercase.
    48zfill (width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).

    Built-in Functions with Strings

    Following are the built-in functions we can use with strings −

    Sr.No.Function with Description
    1len(list)Returns the length of the string.
    2max(list)Returns the max alphabetical character from the string str.
    3min(list)Returns the min alphabetical character from the string str.

  •  Builtin Functions

    Built-in Functions in Python?

    Built-in functions are those functions that are pre-defined in the Python interpreter and you don’t need to import any module to use them. These functions help to perform a wide variety of operations on strings, iterators, and numbers. For instance, the built-in functions like sum(), min(), and max() are used to simplify mathematical operations.

    How to Use Built-in Function in Python?

    To use built-in functions in your code, simply call the specific function by passing the required parameter (if any) inside the parentheses. Since these functions are pre-defined, you don’t need to import any module or package.

    Example of Using Built-in Functions

    Consider the following example demonstrating the use of built-in functions in your code:

    # Using print() and len() function
    
    text ="Tutorials Point"print(len(text))# Prints 15

    In the above example, we are using two built-in functions print() and len().

    List of Python Built-in Functions

    As of Python 3.12.2 version, the list of built-in functions is given below −

    Sr.No.Function & Description
    1Python aiter() functionReturns an asynchronous iterator for an asynchronous iterable.
    2Python all() functionReturns true when all elements in iterable is true.
    3Python anext() functionReturns the next item from the given asynchronous iterator.
    4Python any() functionChecks if any Element of an Iterable is True.
    5Python ascii() functionReturns String Containing Printable Representation.
    6Python bin() functionConverts integer to binary string.
    7Python bool() functionConverts a Value to Boolean.
    8Python breakpoint() functionThis function drops you into the debugger at the call site and calls sys.breakpointhook().
    9Python bytearray() functionReturns array of given byte size.
    10Python bytes() functionReturns immutable bytes object.
    11Python callable() functionChecks if the Object is Callable.
    12Python chr() functionReturns a Character (a string) from an Integer.
    13Python classmethod() functionReturns class method for given function.
    14Python compile() functionReturns a code object.
    15Python complex() functionCreates a Complex Number.
    16Python delattr() functionDeletes Attribute From the Object.
    17Python dict() functionCreates a Dictionary.
    18Python dir() functionTries to Return Attributes of Object.
    19Python divmod() functionReturns a Tuple of Quotient and Remainder.
    20Python enumerate() functionReturns an Enumerate Object.
    21Python eval() functionRuns Code Within Program.
    22Python exec() functionExecutes Dynamically Created Program.
    23Python filter() functionConstructs iterator from elements which are true.
    24Python float() functionReturns floating point number from number, string.
    25Python format() functionReturns formatted representation of a value.
    26Python frozenset() functionReturns immutable frozenset object.
    27Python getattr() functionReturns value of named attribute of an object.
    28Python globals() functionReturns dictionary of current global symbol table.
    29Python hasattr() functionReturns whether object has named attribute.
    30Python hash() functionReturns hash value of an object.
    31Python help() functionInvokes the built-in Help System.
    32Python hex() functionConverts to Integer to Hexadecimal.
    33Python id() functionReturns Identify of an Object.
    34Python input() functionReads and returns a line of string.
    35Python int() functionReturns integer from a number or string.
    36Python isinstance() functionChecks if a Object is an Instance of Class.
    37Python issubclass() functionChecks if a Class is Subclass of another Class.
    38Python iter() functionReturns an iterator.
    39Python len() functionReturns Length of an Object.
    40Python list() functionCreates a list in Python.
    41Python locals() functionReturns dictionary of a current local symbol table.
    42Python map() functionApplies Function and Returns a List.
    43Python memoryview() functionReturns memory view of an argument.
    44Python next() functionRetrieves next item from the iterator.
    45Python object() functionCreates a featureless object.
    46Python oct() functionReturns the octal representation of an integer.
    47Python open() functionReturns a file object.
    48Python ord() functionReturns an integer of the Unicode character.
    49Python print() functionPrints the Given Object.
    50Python property() functionReturns the property attribute.
    51Python range() functionReturns a sequence of integers.
    52Python repr() functionReturns a printable representation of the object.
    53Python reversed() functionReturns the reversed iterator of a sequence.
    54Python set() functionConstructs and returns a set.
    55Python setattr() functionSets the value of an attribute of an object.
    56Python slice() functionReturns a slice object.
    57Python sorted() functionReturns a sorted list from the given iterable.
    58Python staticmethod() functionTransforms a method into a static method.
    59Python str() functionReturns the string version of the object.
    60Python super() functionReturns a proxy object of the base class.
    61Python tuple() functionReturns a tuple.
    62Python type() functionReturns the type of the object.
    63Python vars() functionReturns the __dict__ attribute.
    64Python zip() functionReturns an iterator of tuples.
    65Python __import__() functionFunction called by the import statement.
    66Python unichr() functionConverts a Unicode code point to its corresponding Unicode character.
    67Python long() functionRepresents integers of arbitrary size.

    Built-in Mathematical Functions

    There are some additional built-in functions that are used for performing only mathematical operations in Python, they are listed below −

    Sr.No.Function & Description
    1Python abs() functionThe abs() function returns the absolute value of x, i.e. the positive distance between x and zero.
    2Python max() functionThe max() function returns the largest of its arguments or largest number from the iterable (list or tuple).
    3Python min() functionThe function min() returns the smallest of its arguments i.e. the value closest to negative infinity, or smallest number from the iterable (list or tuple)
    4Python pow() functionThe pow() function returns x raised to y. It is equivalent to x**y. The function has third optional argument mod. If given, it returns (x**y) % mod value
    5Python round() Functionround() is a built-in function in Python. It returns x rounded to n digits from the decimal point.
    6Python sum() functionThe sum() function returns the sum of all numeric items in any iterable (list or tuple). An optional start argument is 0 by default. If given, the numbers in the list are added to start value.

    Advantages of Using Built-in Functions

    The following are the advantages of using built-in functions:

    • The use of the built-in functions simplifies and reduces the code length and enhances the readability of the code.
    • Instead of writing the same logic repeatedly, you can use these functions across different sections of the program. This not only saves time but also helps in maintaining consistency of code.
    • These functions provide a wide range of functionalities including mathematical operations, datatype conversion, and performing operations on iterators.
    • These functions have descriptive names that make the code easier to understand and maintain. Developers need not write additional complex code for performing certain operations.

    Frequently Asked Questions about Built-in Functions

    How do I handle errors with built-in functions?

    While working with built-in functions, you may encounter errors and to handle those errors you can use the try-except blocks. This may help you identify the type of error and exceptions raised.

    Can we extend the functionality of built-in functions?

    Yes, we can extend the functionality of built-in functions by using it with other methods and by applying your logic as per the need. However, it will not affect the pre-defined feature of the used function.

    Can I create my built-in functions?

    No, you cannot create your built-in function. But, Python allows a user to create user-defined functions.

    How do I use built-in functions?

    Using a built-in function is very simple, call it by its name followed by parentheses, and pass the required arguments inside the parentheses.

  •  Modules

    Python Modules

    The concept of module in Python further enhances the modularity. You can define more than one related functions together and load required functions. A module is a file containing definition of functions, classesvariables, constants or any other Python object. Contents of this file can be made available to any other program. Python has the import keyword for this purpose.

    function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

    Example of Python Module

    Open Compiler

    import math
    print("Square root of 100:", math.sqrt(100))

    It will produce the following output −

    Square root of 100: 10.0
    Python Built-in Modules
    Python's standard library comes bundled with a large number of modules. They are called built-in modules. Most of these built-in modules are written in C (as the reference implementation of Python is in C), and pre-compiled into the library. These modules pack useful functionality like system-specific OS management, disk IO, networking, etc.

    Here is a select list of built-in modules −

    Sr.No. Name & Brief Description
    1

    os

    This module provides a unified interface to a number of operating system functions.

    2

    string

    This module contains a number of functions for string processing

    3

    re

    This module provides a set of powerful regular expression facilities. Regular expression (RegEx), allows powerful string search and matching for a pattern in a string

    4

    math

    This module implements a number of mathematical operations for floating point numbers. These functions are generally thin wrappers around the platform C library functions.

    5

    cmath

    This module contains a number of mathematical operations for complex numbers.

    6

    datetime

    This module provides functions to deal with dates and the time within a day. It wraps the C runtime library.

    7

    gc

    This module provides an interface to the built-in garbage collector.

    8

    asyncio

    This module defines functionality required for asynchronous processing

    9

    Collections

    This module provides advanced Container datatypes.

    10

    functools

    This module has Higher-order functions and operations on callable objects. Useful in functional programming

    11

    operator

    Functions corresponding to the standard operators.

    12

    pickle

    Convert Python objects to streams of bytes and back.

    13

    socket

    Low-level networking interface.

    14

    sqlite3

    A DB-API 2.0 implementation using SQLite 3.x.

    15

    statistics

    Mathematical statistics functions

    16

    typing

    Support for type hints

    17

    venv

    Creation of virtual environments.

    18

    json

    Encode and decode the JSON format.

    19

    wsgiref

    WSGI Utilities and Reference Implementation.

    20

    unittest

    Unit testing framework for Python.

    21

    random

    Generate pseudo-random numbers

    22

    sys

    Provides functions that acts strongly with the interpreter.

    23

    requests

    It simplifies HTTP requests by offering a user-friendly interface for sending and handling responses.

    24

    itertools

    An iterator object is used to traverse through a collection (i.e., list, tuple etc..). This module provides various tools which are used to create and manipulate iterators.

    25

    locale

    The locale module in Python is used to set and manage cultural conventions for formatting data. It allows programmers to adapt their programs to different languages and regional formatting standards by changing how numbers, dates, and currencies are displayed.

    Python User-defined Modules
    Any text file with .py extension and containing Python code is basically a module. It can contain definitions of one or more functions, variables, constants as well as classes. Any Python object from a module can be made available to interpreter session or another Python script by import statement. A module can also include runnable code.

    Creating a Python Module
    Creating a module is nothing but saving a Python code with the help of any editor. Let us save the following code as mymodule.py

    def SayHello(name):
    print ("Hi {}! How are you?".format(name))
    return
    You can now import mymodule in the current Python terminal.

    >>> import mymodule
    >>> mymodule.SayHello("Harish")
    Hi Harish! How are you?
    You can also import one module in another Python script. Save the following code as example.py

    import mymodule
    mymodule.SayHello("Harish")
    Run this script from command terminal

    Hi Harish! How are you?
    The import Statement
    In Python, the import keyword has been provided to load a Python object from one module. The object may be a function, class, a variable etc. If a module contains multiple definitions, all of them will be loaded in the namespace.

    Let us save the following code having three functions as mymodule.py.

    def sum(x,y):
    return x+y

    def average(x,y):
    return (x+y)/2

    def power(x,y):
    return x**y
    The import mymodule statement loads all the functions in this module in the current namespace. Each function in the imported module is an attribute of this module object.

    >>> dir(mymodule)
    ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'average', 'power', 'sum']
    To call any function, use the module object's reference. For example, mymodule.sum().

    import mymodule
    print ("sum:",mymodule.sum(10,20))
    print ("average:",mymodule.average(10,20))
    print ("power:",mymodule.power(10, 2))
    It will produce the following output −

    sum:30
    average:15.0
    power:100
    The from ... import Statement
    The import statement will load all the resources of the module in the current namespace. It is possible to import specific objects from a module by using this syntax. For example −

    Out of three functions in mymodule, only two are imported in following executable script example.py

    from mymodule import sum, average
    print ("sum:",sum(10,20))
    print ("average:",average(10,20))
    It will produce the following output −

    sum: 30
    average: 15.0
    Note that function need not be called by prefixing name of its module to it.

    The from...import * Statement
    It is also possible to import all the names from a module into the current namespace by using the following import statement −

    from modname import *
    This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.

    The import ... as Statement
    You can assign an alias name to the imported module.

    from modulename as alias
    The alias should be prefixed to the function while calling.

    Take a look at the following example −

    import mymodule as x
    print ("sum:",x.sum(10,20))
    print ("average:", x.average(10,20))
    print ("power:", x.power(10, 2))
    Locating Modules
    When you import a module, the Python interpreter searches for the module in the following sequences −

    The current directory.

    If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.

    If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.

    The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.

    The PYTHONPATH Variable
    The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.

    Here is a typical PYTHONPATH from a Windows system −

    set PYTHONPATH = c:\python20\lib;
    And here is a typical PYTHONPATH from a UNIX system −

    set PYTHONPATH = /usr/local/lib/python
    Namespaces and Scoping
    Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).

    A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.

    Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.

    Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.

    In order to assign a value to a global variable within a function, you must first use the global statement.

    The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.

    Example
    For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.

    Money = 2000
    def AddMoney():
    # Uncomment the following line to fix the code:
    # global Money
    Money = Money + 1
    print (Money)
    AddMoney()
    print (Money)
    Module Attributes
    In Python, a module is an object of module class, and hence it is characterized by attributes.

    Following are the module attributes −

    __file__ returns the physical name of the module.

    __package__ returns the package to which the module belongs.

    __doc__ returns the docstring at the top of the module if any

    __dict__ returns the entire scope of the module

    __name__ returns the name of the module

    Example

    Assuming that the following code is saved as mymodule.py

    "The docstring of mymodule"defsum(x,y):return x+y
    
    defaverage(x,y):return(x+y)/2defpower(x,y):return x**y
    

    Let us check the attributes of mymodule by importing it in the following script −

    import mymodule
    
    print("__file__ attribute:", mymodule.__file__)print("__doc__ attribute:", mymodule.__doc__)print("__name__ attribute:", mymodule.__name__)

    It will produce the following output −

    __file__ attribute: C:\math\examples\mymodule.py
    __doc__ attribute: The docstring of mymodule
    __name__ attribute: mymodule
    

    The __name__Attribute

    The __name__ attribute of a Python module has great significance. Let us explore it in more detail.

    In an interactive shell, __name__ attribute returns ‘__main__’

    >>> __name__
    '__main__'

    If you import any module in the interpreter session, it returns the name of the module as the __name__ attribute of that module.

    >>>import math
    >>> math.__name__
    'math'

    From inside a Python script, the __name__ attribute returns ‘__main__’

    #example.pyprint("__name__ attribute within a script:", __name__)

    Run this in the command terminal −

    __name__ attribute within a script: __main__
    

    This attribute allows a Python script to be used as executable or as a module. Unlike in C++, Java, C# etc., in Python, there is no concept of the main() function. The Python program script with .py extension can contain function definitions as well as executable statements.

    Save mymodule.py and with the following code −

    "The docstring of mymodule"defsum(x,y):return x+y
       
    print("sum:",sum(10,20))

    You can see that sum() function is called within the same script in which it is defined.

    sum: 30
    

    Now let us import this function in another script example.py.

    import mymodule
    print("sum:",mymodule.sum(10,20))

    It will produce the following output −

    sum: 30
    sum: 30
    

    The output “sum:30” appears twice. Once when mymodule module is imported. The executable statements in imported module are also run. Second output is from the calling script, i.e., example.py program.

    What we want to happen is that when a module is imported, only the function should be imported, its executable statements should not run. This can be done by checking the value of __name__. If it is __main__, means it is being run and not imported. Include the executable statements like function calls conditionally.

    Add if statement in mymodule.py as shown −

    "The docstring of mymodule"defsum(x,y):return x+y
    
    if __name__ =="__main__":print("sum:",sum(10,20))

    Now if you run example.py program, you will find that the sum:30 output appears only once.

    sum: 30
    

    The dir( ) Function

    The dir() built-in function returns a sorted list of strings containing the names defined by a module.

    The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −

    # Import built-in module mathimport math
    
    content =dir(math)print(content)

    When the above code is executed, it produces the following result −

    ['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 
    'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 
    'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
    'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 
    'sqrt', 'tan', 'tanh']
    

    The reload() Function

    Sometimes you may need to reload a module, especially when working with the interactive interpreter session of Python.

    Assume that we have a test module (test.py) with the following function −

    defSayHello(name):print("Hi {}! How are you?".format(name))return

    We can import the module and call its function from Python prompt as −

    >>> import test
    >>> test.SayHello("Deepak")
    Hi Deepak! How are you?
    

    However, suppose you need to modify the SayHello() function, such as −

    defSayHello(name, course):print("Hi {}! How are you?".format(name))print("Welcome to {} Tutorial by TutorialsPoint".format(course))return

    Even if you edit the test.py file and save it, the function loaded in the memory won’t update. You need to reload it, using reload() function in imp module.

    >>> import imp
    >>> imp.reload(test)
    >>> test.SayHello("Deepak", "Python")
    Hi Deepak! How are you?
    Welcome to Python Tutorial by TutorialsPoint
    

    Packages in Python

    A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules, subpackages and, sub-subpackages, and so on.

    Consider a file Pots.py available in Phone directory. This file has following line of source code −

    defPots():print"I'm Pots Phone"

    Similar way, we have another two files having different functions with the same name as above −

    • Phone/Isdn.py file having function Isdn()
    • Phone/G3.py file having function G3()

    Now, create one more file __init__.py in Phone directory −

    • Phone/__init__.py

    To make all of your functions available when you’ve imported Phone, you need to put explicit import statements in __init__.py as follows −

    from Pots import Pots
    from Isdn import Isdn
    from G3 import G3
    

    After you add these lines to __init__.py, you have all of these classes available when you import the Phone package.

    # Now import your Phone Package.import Phone
    
    Phone.Pots()
    Phone.Isdn()
    Phone.G3()

    When the above code is executed, it produces the following result −

    I'm Pots Phone
    I'm 3G Phone
    I'm ISDN Phone
    

    In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.

  •  Function Annotations

    Function Annotations

    The function annotation feature of Python enables you to add additional explanatory metadata about the arguments declared in a function definition, and also the return data type. They are not considered by Python interpreter while executing the function. They are mainly for the Python IDEs for providing a detailed documentation to the programmer.

    Although you can use the docstring feature of Python for documentation of a function, it may be obsolete if certain changes in the function’s prototype are made. Hence, the annotation feature was introduced in Python as a result of PEP 3107.

    Annotations are any valid Python expressions added to the arguments or return data type. Simplest example of annotation is to prescribe the data type of the arguments. Annotation is mentioned as an expression after putting a colon in front of the argument.

    Example

    Remember that Python is a dynamically typed language, and doesn’t enforce any type checking at runtime. Hence annotating the arguments with data types doesn’t have any effect while calling the function. Even if non-integer arguments are given, Python doesn’t detect any error.

    defmyfunction(a:int, b:int):
       c = a+b
       return c
       
    print(myfunction(10,20))print(myfunction("Hello ","Python"))

    It will produce the following output −

    30
    Hello Python
    Function Annotations With Return Type
    Annotations are ignored at runtime, but are helpful for the IDEs and static type checker libraries such as mypy.

    You can give annotation for the return data type as well. After the parentheses and before the colon symbol, put an arrow (->) followed by the annotation.

    Example
    In this example, we are providing annotation for return type.

    def myfunction(a: int, b: int) -> int:
    c = a+b
    return c
    print(myfunction(56,88))
    print(myfunction.__annotations__)
    This will generate the following output −

    144
    {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
    Function Annotations With Expression
    As using the data type as annotation is ignored at runtime, you can put any expression which acts as the metadata for the arguments. Hence, function may have any arbitrary expression as annotation.

    Example
    In the below example, we are using expression as a function annotation.

    def total(x : 'marks in Physics', y: 'marks in chemistry'):
    return x+y
    print(total(86, 88))
    print(total.__annotations__)
    Following is the output −

    174
    {'x': 'marks in Physics', 'y': 'marks in chemistry'}
    Function Annotations With Default Arguments
    If you want to specify a default argument along with the annotation, you need to put it after the annotation expression. Default arguments must come after the required arguments in the argument list.

    Example 1
    The following example demonstrates how to provide annotation for default arguments of a function.

    def myfunction(a: "physics", b:"Maths" = 20) -> int:
    c = a+b
    return c
    print (myfunction(10))
    The function in Python is also an object, and one of its attributes is __annotations__. You can check with dir() function.

    print (dir(myfunction))
    This will print the list of myfunction object containing __annotations__ as one of the attributes.

    ['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__getstate__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
    Example 2
    The __annotations__ attribute itself is a dictionary in which arguments are keys and anotations their values.

    def myfunction(a: "physics", b:"Maths" = 20) -> int:
    c = a+b
    return c
    print (myfunction.__annotations__)
    It will produce the following output −

    {'a': 'physics', 'b': 'Maths', 'return': <class 'int'>}
    Example 3
    You may have arbitrary positional and/or arbitrary keyword arguments for a function. Annotations can be given for them also.

    def myfunction(*args: "arbitrary args", **kwargs: "arbitrary keyword args") -> int:
    pass
    print (myfunction.__annotations__)
    It will produce the following output −

    {'args': 'arbitrary args', 'kwargs': 'arbitrary keyword args', 'return': <class 'int'>}
    Example 4
    In case you need to provide more than one annotation expressions to a function argument, give it in the form of a dictionary object in front of the argument itself.

    def division(num: dict(type=float, msg='numerator'), den: dict(type=float, msg='denominator')) -> float:
    return num/den
    print (division.__annotations__)
    It will produce the following output −

    {'num': {'type': <class 'float'>, 'msg': 'numerator'}, 'den': {'type': <class 'float'>, 'msg': 'denominator'}, 'return': <class 'float'>}
  • Variable Scope

    The scope of a variable in Python is defined as the specific area or region where the variable is accessible to the user. The scope of a variable depends on where and how it is defined. In Python, a variable can have either a global or a local scope.

    Types of Scope for Variables in Python

    On the basis of scope, the Python variables are classified in three categories −

    • Local Variables
    • Global Variables
    • Nonlocal Variables

    Local Variables

    A local variable is defined within a specific function or block of code. It can only be accessed by the function or block where it was defined, and it has a limited scope. In other words, the scope of local variables is limited to the function they are defined in and attempting to access them outside of this function will result in an error. Always remember, multiple local variables can exist with the same name.

    Example

    The following example shows the scope of local variables.

    defmyfunction():
       a =10
       b =20print("variable a:", a)print("variable b:", b)return a+b
       
    print(myfunction())

    In the above code, we have accessed the local variables through its function. Hence, the code will produce the following output −

    variable a: 10
    variable b: 20
    30
    

    Global Variables

    A global variable can be accessed from any part of the program, and it is defined outside any function or block of code. It is not specific to any block or function.

    Example

    The following example shows the scope of global variable. We can access them inside as well as outside of the function scope.

    #global variables
    name ='TutorialsPoint'
    marks =50defmyfunction():# accessing inside the functionprint("name:", name)print("marks:", marks)# function call   
    myfunction()

    The above code will produce the following output −

    name: TutorialsPoint
    marks: 50
    

    Nonlocal Variables

    The Python variables that are not defined in either local or global scope are called nonlocal variables. They are used in nested functions.

    Example

    The following example demonstrates the how nonlocal variables works.

    defyourfunction():
       a =5
       b =6# nested functiondefmyfunction():# nonlocal function nonlocal a
    
      nonlocal b
      a =10
      b =20print("variable a:", a)print("variable b:", b)return a+b
    print(myfunction()) yourfunction()

    The above code will produce the below output −

    variable a: 10
    variable b: 20
    30
    

    Namespace and Scope of Python Variables

    A namespace is a collection of identifiers, such as variable names, function names, class names, etc. In Python, namespace is used to manage the scope of variables and to prevent naming conflicts.

    Python provides the following types of namespaces −

    • Built-in namespace contains built-in functions and built-in exceptions. They are loaded in the memory as soon as Python interpreter is loaded and remain till the interpreter is running.
    • Global namespace contains any names defined in the main program. These names remain in memory till the program is running.
    • Local namespace contains names defined inside a function. They are available till the function is running.

    These namespaces are nested one inside the other. Following diagram shows relationship between namespaces.

    Types Of Namespace

    The life of a certain variable is restricted to the namespace in which it is defined. As a result, it is not possible to access a variable present in the inner namespace from any outer namespace.

    Python globals() Function

    Python’s standard library includes a built-in function globals(). It returns a dictionary of symbols currently available in global namespace.

    Run the globals() function directly from the Python prompt.

    >>> globals()
    {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
    

    It can be seen that the built-in module which contains definitions of all built-in functions and built-in exceptions is loaded.

    Example

    Save the following code that contains few variables and a function with few more variables inside it.

    Open Compiler

    name ='TutorialsPoint'
    marks =50
    result =Truedefmyfunction():
       a =10
       b =20return a+b
       
    print(globals())

    Calling globals() from inside this script returns following dictionary object −

    {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000263E7255250>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\user\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000263E72004A0>}
    

    The global namespace now contains variables in the program and their values and the function object in it (and not the variables in the function).

    Python locals() Function

    Python’s standard library includes a built-in function locals(). It returns a dictionary of symbols currently available in the local namespace of the function.

    Example

    Modify the above script to print dictionary of global and local namespaces from within the function.

    name ='TutorialsPoint'
    marks =50
    result =Truedefmyfunction():
       a =10
       b =20
       c = a+b
       print("globals():",globals())print("locals():",locals())return c
    myfunction()

    The output shows that locals() returns a dictionary of variables and their values currently available in the function.

    globals(): {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000169AE265250>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\mlath\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000169AE2104A0>}
    locals(): {'a': 10, 'b': 20, 'c': 30}
    

    Since both globals() and locals functions return dictionary, you can access value of a variable from respective namespace with dictionary get() method or index operator.

    print(globals()['name'])# displays TutorialsPointprint(locals().get('a'))# displays 10

    Namespace Conflict in Python

    If a variable of same name is present in global as well as local scope, Python interpreter gives priority to the one in local namespace.

    Example

    In the following example, we define a local and a global variable.

    marks =50# this is a global variabledefmyfunction():
       marks =70# this is a local variableprint(marks)
       
    myfunction()print(marks)# prints global value

    It will produce the following output −

    70
    50
    

    Example

    If you try to manipulate value of a global variable from inside a function, Python raises UnboundLocalError as shown in example below −

    # this is a global variable
    marks =50defmyfunction():
       marks = marks +20print(marks)
    
    myfunction()# prints global valueprint(marks)

    It will produce the following error message −

       marks = marks + 20
    
           ^^^^^
    UnboundLocalError: cannot access local variable 'marks' where it is not associated with a value

    Example

    To modify a global variable, you can either update it with a dictionary syntax, or use the global keyword to refer it before modifying.

    var1 =50# this is a global variable
    var2 =60# this is a global variabledefmyfunction():"Change values of global variables"globals()['var1']=globals()['var1']+10global var2
       var2 = var2 +20
    
    myfunction()print("var1:",var1,"var2:",var2)#shows global variables with changed values

    On executing the code, it will produce the following output −

    var1: 60 var2: 80
    

    Example

    Lastly, if you try to access a local variable in global scope, Python raises NameError as the variable in local scope can’t be accessed outside it.

    var1 =50# this is a global variable
    var2 =60# this is a global variabledefmyfunction(x, y):
       total = x+y
       print("Total is a local variable: ", total)
    
    myfunction(var1, var2)print(total)# This gives NameError

    It will produce the following error message −

    Total is a local variable: 110
    Traceback (most recent call last):
       File "C:\Users\user\examples\main.py", line 9, in <module>
       print (total) # This gives NameError
    
          ^^^^^
    NameError: name 'total' is not defined
  •  Arbitrary or Variable-length Arguments

    Arbitrary Arguments (*args)

    You may want to define a function that is able to accept arbitrary or variable number of arguments. Moreover, the arbitrary number of arguments might be positional or keyword arguments.

    • An argument prefixed with a single asterisk * for arbitrary positional arguments.
    • An argument prefixed with two asterisks ** for arbitrary keyword arguments.

    Arbitrary Arguments Example

    Given below is an example of arbitrary or variable length positional arguments −

    # sum of numbersdefadd(*args):
       s=0for x in args:
    
      s=s+x
    return s result = add(10,20,30,40)print(result) result = add(1,2,3)print(result)

    The args variable prefixed with “*” stores all the values passed to it. Here, args becomes a tuple. We can run a loop over its items to add the numbers.

    It will produce the following output −

    100
    6
    

    Required Arguments With Arbitrary Arguments

    It is also possible to have a function with some required arguments before the sequence of variable number of values.

    Example

    The following example has avg() function. Assume that a student can take any number of tests. First test is mandatory. He can take as many tests as he likes to better his score. The function calculates the average of marks in first test and his maximum score in the rest of tests.

    The function has two arguments, first is the required argument and second to hold any number of values.

    #avg of first test and best of following testsdefavg(first,*rest):
       second=max(rest)return(first+second)/2
       
    result=avg(40,30,50,25)print(result)

    Following call to avg() function passes first value to the required argument first, and the remaining values to a tuple named rest. We then find the maximum and use it to calculate the average.

    It will produce the following output −

    45.0
    

    Arbitrary Keyword Arguments (**kwargs)

    If a variable in the argument list has two asterisks prefixed to it, the function can accept arbitrary number of keyword arguments. The variable becomes a dictionary of keyword:value pairs.

    Example

    The following code is an example of a function with arbitrary keyword arguments. The addr() function has an argument **kwargs which is able to accept any number of address elements like name, city, phno, pin, etc. Inside the function kwargs dictionary of kw:value pairs is traversed using items() method.

    defaddr(**kwargs):for k,v in kwargs.items():print("{}:{}".format(k,v))print("pass two keyword args")
    addr(Name="John", City="Mumbai")print("pass four keyword args")# pass four keyword args
    addr(Name="Raam", City="Mumbai", ph_no="9123134567", PIN="400001")

    It will produce the following output −

    pass two keyword args
    Name:John
    City:Mumbai
    pass four keyword args
    Name:Raam
    City:Mumbai
    ph_no:9123134567
    PIN:400001

    Multiple Arguments With Arbitrary Keyword Arguments

    If the function uses mixed types of arguments, the arbitrary keyword arguments should be after positional, keyword and arbitrary positional arguments in the argument list.

    Example

    Imagine a case where science and maths are mandatory subjects, in addition to which student may choose any number of elective subjects.

    The following code defines a percent() function where marks in science and marks are stored in required arguments, and the marks in variable number of elective subjects in **optional argument.

    defpercent(math, sci,**optional):print("maths:", math)print("sci:", sci)
       s=math+sci
       for k,v in optional.items():print("{}:{}".format(k,v))
    
      s=s+v
    return s/(len(optional)+2) result=percent(math=80, sci=75, Eng=70, Hist=65, Geo=72)print("percentage:", result)

    It will produce the following output −

    maths: 80
    sci: 75
    Eng:70
    Hist:65
    Geo:72
    percentage: 72.4
  • PositionalOnly Arguments

    Positional Only Arguments

    It is possible in Python to define a function in which one or more arguments can not accept their value with keywords. Such arguments are called positional-only arguments.

    To make an argument positional-only, use the forward slash (/) symbol. All the arguments before this symbol will be treated as positional-only.

    Python’s built-in input() function is an example of positional-only arguments. The syntax of input function is −

    input(prompt ="")

    Prompt is an explanatory string for the benefit of the user. However, you cannot use the prompt keyword inside the parentheses.

    Example

    In this example, we are using prompt keyword, which will lead to error.

    name =input(prompt="Enter your name ")

    On executing, this code will show the following error message −

       name = input (prompt="Enter your name ")
    
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: input() takes no keyword arguments

    Positional-Only Arguments Examples

    Let’s understand positional-only arguments with the help of some examples −

    Example 1

    In this example, we make both the arguments of intr() function as positional-only by putting “/” at the end.

    defintr(amt, rate,/):
       val = amt * rate /100return val
       
    print(intr(316200,4))

    When you run the code, it will show the following result −

    12648.0
    

    Example 2

    If we try to use the arguments as keywords, Python raises errors as shown in the below example.

    defintr(amt, rate,/):
       val = amt * rate /100return val
       
    print(intr(amt=1000, rate=10))

    On running this code, it will show following error message −

       interest = intr(amt=1000, rate=10)
    
              ^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: intr() got some positional-only arguments passed as keyword arguments: 'amt, rate'

    Example 3

    A function may be defined in such a way that it has some keyword-only and some positional-only arguments. Here, x is a required positional-only argument, y is a regular positional argument, and z is a keyword-only argument.

    defmyfunction(x,/, y,*, z):print(x, y, z)
       
    myfunction(10, y=20, z=30)
    myfunction(10,20, z=30)

    The above code will show the following output −

    10 20 30
    10 20 30 
  • Positional Arguments

    Positional Arguments

    The list of variables declared in the parentheses at the time of defining a function are the formal arguments. And, these arguments are also known as positional arguments. A function may be defined with any number of formal arguments.

    While calling a function −

    • All the arguments are required.
    • The number of actual arguments must be equal to the number of formal arguments.
    • They Pick up values in the order of definition.
    • The type of arguments must match.
    • Names of formal and actual arguments need not be same.

    Positional Arguments Examples

    Let’s discuss some examples of Positional arguments −

    Example 1

    The following example shows the use of positional argument.

    Open Compiler

    defadd(x,y):
       z = x+y
       print("x={} y={} x+y={}".format(x,y,z))
    a =10
    b =20
    add(a, b)

    It will produce the following output −

    x=10 y=20 x+y=30
    

    Here, the add() function has two formal arguments, both are numeric. When integers 10 and 20 passed to it. The variable “a” takes 10 and “b” takes 20, in the order of declaration. The add() function displays the addition.

    Example 2

    Python also raises error when the number of arguments don’t match. If you give only one argument and check the result you can see an error.

    defadd(x,y):
       z=x+y
       print(z)
    a=10;
    add(a)

    The error generated will be as shown below −

    TypeError: add() missing 1 required positional argument: 'y'
    

    Example 3

    Similarly, if you pass more than the number of formal arguments an error will be generated stating the same −

    defadd(x,y):
       z=x+y
       print("x={} y={} x+y={}".format(x,y,z))
    add(10,20,30)

    Following is the output −

    TypeError: add() takes 2 positional arguments but 3 were given
    

    Example 4

    Data type of corresponding actual and formal arguments must match. Change a to a string value and see the result.

    defadd(x,y):
       z=x+y
       print(z)
    a="Hello"
    b=20
    add(a,b)

    It will produce the following error −

    z=x+y
    
     ~^~
    TypeError: can only concatenate str (not "int") to str

    Difference between Positional and Keyword argument

    The below table explains the difference between positional and keyword argument −

    Positional ArgumentKeyword Argument
    Only the names of arguments are used to pass data to the given function.Keyword arguments are passed to a function in name=value form.
    Arguments are passed in the order defined in function declaration.While passing arguments, their order can be changed.
    Syntax: function(param1, param2,…)Syntax: function(param1 = value1,…)