Python Slicing Strings

Tutorials

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 − 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. Open Compiler On running the code, it will produce the following output − 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. Example Let us use negative indexing to fetch N, Y, and H characters. Open Compiler On executing the above code, it will give the following result − 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. Open Compiler It will produce the following output − The TypeError is because the string is immutable. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Python String Slicing Python defines “:” as string slicing operator. It returns a substring from the original string. Its general usage is as follows − 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 Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output − 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 It will produce the following output − 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 Open Compiler It will produce the following output −

October 3, 2024 / 0 Comments
read more

Strings

Tutorials

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 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 When the above code is executed, it produces the following result − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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 When the above code is executed, it produces the following result − 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 notation Hexadecimal character Description \a 0x07 Bell or alert \b 0x08 Backspace \cx Control-x \C-x Control-x \e 0x1b Escape \f 0x0c Formfeed \M-\C-x Meta-Control-x \n 0x0a Newline \nnn Octal notation, where n is in the range 0.7 \r 0x0d Carriage return \s 0x20 Space \t 0x09 Tab \v 0x0b Vertical tab \x Character x \xnn Hexadecimal 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 − Operator Description Example + Concatenation – Adds values on either side of the operator a + b will give HelloPython * Repetition – Creates new strings, concatenating multiple copies of the same string a*2 will give -HelloHello [] Slice – Gives the character from the given index a[1] will give e [ : ] Range Slice – Gives the characters from the given range a[1:4] will give ell in Membership – Returns true if a character exists in the given string H in a will give 1 not in Membership – Returns true if a character does not exist in the given string M not in a will give 1 r/R Raw 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 formatting See 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 When the above code is executed, it produces the following result − 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 2 –left justification 3 +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. 6 0pad from left with zeros (instead of spaces) 7 %‘%%’ leaves you with a single literal ‘%’ 8 (var)mapping variable (dictionary arguments) 9 m.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 Open Compiler It will produce the following output − Triple Quotes To form a string with triple quotes, you may use triple single quotes, or triple double quotes − both versions are similar. Example Open Compiler It will produce the following output − Python Multiline Strings Triple quoted string is useful to form a multi-line string. Example Open Compiler It will produce the following output − 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. Open Compiler On executing the above program it will generate the following error − Getting Type of Python Strings A

October 3, 2024 / 0 Comments
read more

Built-in Functions

Tutorials

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: In the above example, we are using two built-in functions print() and len(). Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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 1 Python aiter() functionReturns an asynchronous iterator for an asynchronous iterable. 2 Python all() functionReturns true when all elements in iterable is true. 3 Python anext() functionReturns the next item from the given asynchronous iterator. 4 Python any() functionChecks if any Element of an Iterable is True. 5 Python ascii() functionReturns String Containing Printable Representation. 6 Python bin() functionConverts integer to binary string. 7 Python bool() functionConverts a Value to Boolean. 8 Python breakpoint() functionThis function drops you into the debugger at the call site and calls sys.breakpointhook(). 9 Python bytearray() functionReturns array of given byte size. 10 Python bytes() functionReturns immutable bytes object. 11 Python callable() functionChecks if the Object is Callable. 12 Python chr() functionReturns a Character (a string) from an Integer. 13 Python classmethod() functionReturns class method for given function. 14 Python compile() functionReturns a code object. 15 Python complex() functionCreates a Complex Number. 16 Python delattr() functionDeletes Attribute From the Object. 17 Python dict() functionCreates a Dictionary. 18 Python dir() functionTries to Return Attributes of Object. 19 Python divmod() functionReturns a Tuple of Quotient and Remainder. 20 Python enumerate() functionReturns an Enumerate Object. 21 Python eval() functionRuns Code Within Program. 22 Python exec() functionExecutes Dynamically Created Program. 23 Python filter() functionConstructs iterator from elements which are true. 24 Python float() functionReturns floating point number from number, string. 25 Python format() functionReturns formatted representation of a value. 26 Python frozenset() functionReturns immutable frozenset object. 27 Python getattr() functionReturns value of named attribute of an object. 28 Python globals() functionReturns dictionary of current global symbol table. 29 Python hasattr() functionReturns whether object has named attribute. 30 Python hash() functionReturns hash value of an object. 31 Python help() functionInvokes the built-in Help System. 32 Python hex() functionConverts to Integer to Hexadecimal. 33 Python id() functionReturns Identify of an Object. 34 Python input() functionReads and returns a line of string. 35 Python int() functionReturns integer from a number or string. 36 Python isinstance() functionChecks if a Object is an Instance of Class. 37 Python issubclass() functionChecks if a Class is Subclass of another Class. 38 Python iter() functionReturns an iterator. 39 Python len() functionReturns Length of an Object. 40 Python list() functionCreates a list in Python. 41 Python locals() functionReturns dictionary of a current local symbol table. 42 Python map() functionApplies Function and Returns a List. 43 Python memoryview() functionReturns memory view of an argument. 44 Python next() functionRetrieves next item from the iterator. 45 Python object() functionCreates a featureless object. 46 Python oct() functionReturns the octal representation of an integer. 47 Python open() functionReturns a file object. 48 Python ord() functionReturns an integer of the Unicode character. 49 Python print() functionPrints the Given Object. 50 Python property() functionReturns the property attribute. 51 Python range() functionReturns a sequence of integers. 52 Python repr() functionReturns a printable representation of the object. 53 Python reversed() functionReturns the reversed iterator of a sequence. 54 Python set() functionConstructs and returns a set. 55 Python setattr() functionSets the value of an attribute of an object. 56 Python slice() functionReturns a slice object. 57 Python sorted() functionReturns a sorted list from the given iterable. 58 Python staticmethod() functionTransforms a method into a static method. 59 Python str() functionReturns the string version of the object. 60 Python super() functionReturns a proxy object of the base class. 61 Python tuple() functionReturns a tuple. 62 Python type() functionReturns the type of the object. 63 Python vars() functionReturns the __dict__ attribute. 64 Python zip() functionReturns an iterator of tuples. 65 Python __import__() functionFunction called by the import statement. 66 Python unichr() functionConverts a Unicode code point to its corresponding Unicode character. 67 Python 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 1 Python abs() functionThe abs() function returns the absolute value of x, i.e. the positive distance between x and zero. 2 Python max() functionThe max() function returns the largest of its arguments or largest number from the iterable (list or tuple). 3 Python 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) 4 Python 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 5 Python round() Functionround() is a built-in function in Python. It returns x rounded to n digits from the decimal point. 6 Python 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: Frequently Asked Questions about Built-in Functions How do I handle errors with built-in functions? While working with built-in functions, you

October 3, 2024 / 0 Comments
read more

Modules

Tutorials

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, classes, variables, 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. A 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 It will produce the following output − 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 osThis module provides a unified interface to a number of operating system functions. 2 stringThis module contains a number of functions for string processing 3 reThis 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 mathThis module implements a number of mathematical operations for floating point numbers. These functions are generally thin wrappers around the platform C library functions. 5 cmathThis module contains a number of mathematical operations for complex numbers. 6 datetimeThis module provides functions to deal with dates and the time within a day. It wraps the C runtime library. 7 gcThis module provides an interface to the built-in garbage collector. 8 asyncioThis module defines functionality required for asynchronous processing 9 CollectionsThis module provides advanced Container datatypes. 10 functoolsThis module has Higher-order functions and operations on callable objects. Useful in functional programming 11 operatorFunctions corresponding to the standard operators. 12 pickleConvert Python objects to streams of bytes and back. 13 socketLow-level networking interface. 14 sqlite3A DB-API 2.0 implementation using SQLite 3.x. 15 statisticsMathematical statistics functions 16 typingSupport for type hints 17 venvCreation of virtual environments. 18 jsonEncode and decode the JSON format. 19 wsgirefWSGI Utilities and Reference Implementation. 20 unittestUnit testing framework for Python. 21 randomGenerate pseudo-random numbers 22 sysProvides functions that acts strongly with the interpreter. 23 requestsIt simplifies HTTP requests by offering a user-friendly interface for sending and handling responses. Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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 You can now import mymodule in the current Python terminal. You can also import one module in another Python script. Save the following code as example.py Run this script from command terminal 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. 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. To call any function, use the module object’s reference. For example, mymodule.sum(). It will produce the following output − 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 It will produce the following output − 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. The alias should be prefixed to the function while calling. Take a look at the following example − Locating Modules When you import a module, the Python interpreter searches for the module in the following sequences − 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 − 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). 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. Open Compiler Module Attributes In Python, a module is an object of module class, and hence it is characterized by attributes. Following are the module attributes − Example Assuming that the following code is saved as mymodule.py Let us check the attributes of mymodule

October 3, 2024 / 0 Comments
read more

Function Annotations

Tutorials

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. Open Compiler It will produce the following output − 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. Open Compiler This will generate the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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. Open Compiler Following is the output − 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. The function in Python is also an object, and one of its attributes is __annotations__. You can check with dir() function. This will print the list of myfunction object containing __annotations__ as one of the attributes. Example 2 The __annotations__ attribute itself is a dictionary in which arguments are keys and anotations their values. Open Compiler It will produce the following output − Example 3 You may have arbitrary positional and/or arbitrary keyword arguments for a function. Annotations can be given for them also. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output −

October 3, 2024 / 0 Comments
read more

Python Variable Scope

Tutorials

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 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. Open Compiler In the above code, we have accessed the local variables through its function. Hence, the code will produce the following output − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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. Open Compiler The above code will produce the following output − 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. Open Compiler The above code will produce the below output − 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 − These namespaces are nested one inside the other. Following diagram shows relationship between namespaces. 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. 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 Calling globals() from inside this script returns following dictionary object − 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. Open Compiler The output shows that locals() returns a dictionary of variables and their values currently available in the function. 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. 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. Open Compiler It will produce the following output − Example If you try to manipulate value of a global variable from inside a function, Python raises UnboundLocalError as shown in example below − Open Compiler It will produce the following error message − 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. Open Compiler On executing the code, it will produce the following output − 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. Open Compiler It will produce the following error message −

October 3, 2024 / 0 Comments
read more

Arbitrary or, Variable-length Arguments

Tutorials

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. Arbitrary Arguments Example Given below is an example of arbitrary or variable length positional arguments − Open Compiler 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 − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. 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. Open Compiler 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 − 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. Open Compiler It will produce the following output − 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. Open Compiler It will produce the following output −

October 3, 2024 / 0 Comments
read more

Positional-Only Arguments

Tutorials

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 − 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. Open Compiler On executing, this code will show the following error message −<> 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. Open Compiler When you run the code, it will show the following result − Example 2 If we try to use the arguments as keywords, Python raises errors as shown in the below example. Open Compiler On running this code, it will show following error message − 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. Open Compiler The above code will show the following output −

October 3, 2024 / 0 Comments
read more

Positional Arguments

Tutorials

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 − Positional Arguments Examples Let’s discuss some examples of Positional arguments − Example 1 The following example shows the use of positional argument. Open Compiler It will produce the following output − 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. Open Compiler The error generated will be as shown below − Example 3 Similarly, if you pass more than the number of formal arguments an error will be generated stating the same − Open Compiler Following is the output − Example 4 Data type of corresponding actual and formal arguments must match. Change a to a string value and see the result. Open Compiler It will produce the following error − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Difference between Positional and Keyword argument The below table explains the difference between positional and keyword argument − Positional Argument Keyword 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,…)

October 3, 2024 / 0 Comments
read more

Keyword-Only Arguments

Tutorials

Keyword-Only Arguments You can use the variables in formal argument list as keywords to pass value. Use of keyword arguments is optional. But, you can force the function to accept arguments by keyword only. You should put an astreisk (*) before the keyword-only arguments list. Let us say we have a function with three arguments, out of which we want second and third arguments to be keyword-only. For that, put * after the first argument. Example of Keyword-Only Arguments The built-in print() function is an example of keyword-only arguments. You can give list of expressions to be printed in the parentheses. The printed values are separated by a white space by default. You can specify any other separation character instead using “sep” argument. Open Compiler It will print − Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career. Example: Using “sep” as non-keyword Argument The sep argument of the print() function is keyword-only. Try using it as non-keyword argument. Open Compiler You’ll get different output, not as desired − Using Keyword-Only argument in User-Defined Method To make an argument keyword-only, put the astreisk (*) before it while creating the user-defined function. Those Python functions that are defined by us within a given class to perform certain actions are called as user-defined function. They are not predefined by Python. Example In the following user defined function “intr()” the “rate” argument is keyword-only. To call this function, the value for rate must be passed by keyword. Open Compiler However, if you try to use the default positional way of calling the above function, you will encounter an error. Example The code below shows it is not possible to use positional arguments when keyword-only arguments are required. Open Compiler On executing, this code will show the following result −

October 3, 2024 / 0 Comments
read more

Posts pagination

Previous 1 … 12 13 14 … 18 Next