Search

Introduction to the loops

Python has a powerful conceptcalled loops.Loops makes use of called looping (iteration), which helps cut out our repetitive code. This is very helpful when you want to do something times simply write the initial code then you can repeat multiple times till a particular condition will not met.The purpose of loops is to repeat the same, or similar, code several times. This number of times could be specified to a certain number, or the number of times could be dictated by a certain condition being met.  A conditional loop has the potential to become an infinite loop when nothing in the loop's body can affect the outcome of the loop's conditional statement. The While loop and the For loop are the two common types of conditional loops. You can also provide a numerical range(sequence) of values to control how many times the code will execute.  In Python, there are two primary structures for loops: for while For Loop: “for” loop is iteratively execute code for each item in a pre-defined list Iterations that you know how many times it will occur (even if you can stop it before) means that you know how many times loop will run. The syntax of a for loop is for (followed by (: ) ) With the for loop we can execute a number of statements, once for each item in a list, tuple, set. Let say, you want to repeat some code multiple times but you will not care about variable I, so it will be good practice to replace I with _, this means that we will not care about this valueWhere can we use for loop? A for loop is used for iterating over a sequence (either a list, a tuple, a dictionary, a set, or a strings). for loop are used for sequential traversal. Ex- traversing a list or strings or array etc. Syntax: for i in sequence: Body of for “All values inside the sequence will take i variable”In this above example, we have created list i.e A having strings values, “for” is the syntax of for loop followed by “:”, then there is a variable i that is called placeholder it will take all the values from the sequence i.e. A and then it will print all the values inside the placeholder i.e. i, print(i)In above example, we have created list B in that we took non-sequential order integer value, however loop will execute on each of the item, in the same manner in which we are defined in the list B.Placeholder(i) is the unique variable inside the for loop it will represent all the values inside the sequence i.e. B, i is not a pre-defined variable so in place of i we can use anything means that any variable, anystrings, except numeric value we can use anything. In the below example you will better understand how this placeholder will work, in place of placeholder we can use X variable and completely unrelated strings also we can putHope you will better understand that whichever placeholder you will put it does not matter. In the above example, list B contains only numeric values, but you can use other type as well like text strings.for loop on Text Strings:In the example below, a list called B is defined with two text strings that represent two statement. The for loop will run iteratively on each text strings (represented by the placeholder strings in each iteration). List B contains two text strings i.e. “This is str” and “This is boolean” so in the first iteration “This is str” will print then in the next iteration “This is boolean” will print.We can achieve the output in another way by using range method to loop.for loop on Data Structures:In the below example, we have created a list i.e. List, that contains other lists i.e Months and Income. Placeholder flist represent all the elements from the List and List contains two lists i.e Months and Income so it will repeat one by one in which you have defined.In the first iteration Months will print and in the second iteration Income will print.while loop: A loop is used to repetitively execute program until a defined condition will not met  Iterations that you will observe something else to decide when to stop an iteration - those are the while loops.While loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition will not satisfied then, after the loop in the program will execute.If the test expression is true, statements inside the body of while loop will execute. Then, the test expression is evaluated again. The process goes on till the test expression is evaluated to false. A while loop can also terminate when a break or return within the statement body is executed. You can use continue to terminate the current iteration without exiting the while loop. continue it will pass control to the next iteration of the while loop. The termination condition will evaluate at the top of the loop. Where can we use while loops? The while loop in Python will iterate over a block of code if the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand. Ex: - let say, If we want to check the grade of every student in the class, we loop from 1 to that particular range of number. When the number of times is not known, we use a "while" loop. The while loop is used repeat a section of code an unknown number of times until a specific condition is met. Ex- say we want to know how many times a given number can be divided by 2 before it is less than or equal to 1. Syntax: while condition: body_of_while Condition can be a limit that how many times the while loop will run, you can see in the below example the loop will run till 9 we have restrict the iteration. Once loop will reaches 10 (x=10) then loop will not executeA while loop start with while and then condition.  In the below code if you notice that we have given the indentation, it must have to give the indentation means that statement is inside the loop. In this example, we add 1 in the x and value of x does not exceed the given condition (x<10). In the below code we used ‘<’ operator that means the value of x will start from 0 till 9 exclude 10. We have used one more operator i.e. ‘+=’ that means 1 will add in each of the element of the xWhen loop will reaches 10 (x=10) then the condition no longer satisfied so the loop will not execute another iteration In the above example, the code will executed in order that means the first 1 will add in the value of x then print() function will execute. You can change the position if you want to print the value of x first then also you can add the 1 value in the xYou can also use the range operator instead of the comparison operator in this you need to specify the range for the iteration  In this range operator starting value is inclusive but not end value In the below example, while loop runs till 5 and 5 will not include then we have increment x by 1 means that it will add 1 in each of the x element. When x reaches to 5 then it will not execute another iteration of code.You can notice that structure of the while loop will remains same except condition and indentation Nested Loops: nested loopsare loopswhich run within another loop. Where can we use nested loops? Nested loops are useful when for each pass through the outer loop, you need to repeat some action on the data in the outer loop. Ex- you read a file line by line and for each line you must count how many times the word “the” is found. Nested for loop: Syntax: for iterating_var in sequence:     for iterating_var in sequence:        statements(s)     statements(s) Here,  iterating_varis the variable that takes the value of the item inside the sequence on each iteration. These are constructed like:In the above example, the program first runs the outer loop, execute the first code then it will runs the inner loop i.e. nested loop, nested loop will runs till sequence then program return to the top of the outer loop, run the next iteration and again run the nested loop till sequence and again program return back to top of the outer loop it will execute till the sequence will not complete.In the below example you can see how nested for loop will work, we have created two lists, A consist of numeric value and B consist of strings value. First program will runs the outer loop and print 1 then program will runs the nested loop, it will run till the sequence will not complete and print a, b, c then program return back to the top of the outer loop and run the next iteration and print 2 then program will run the nested loop till the sequence will not complete and print a, b, c etc. This will execute till the sequence of the outer loop will not complete.Nested while loop: When the while loop is present inside another while loop then it is called nested while loop. Syntax: while expression:     while expression:        statement(s)     statement(s) A nested while loop will present while statement inside another while statement. In a nested while loop, first iteration of the outer loop is first executed, after which the inner loop will execute. Once the condition of the inner loop is satisfied, the program moves to the next iteration of the outer loop.Practical examples of for loop: Ex: Calculate the sum Practical examples of while loops: Ex: Calculate the table from 1 to 2 Conclusion: In this post, we have learnt about  Loops: for loopfor loop will iteratively execute code for each item in a pre-defined list Nested for loop A nested loop is a loop that will occurs within another loop while loop A while loop is used to iteratively execute code until a pre-defined condition is no longer satisfied (i.e. results in a value of False) Nested while loop When the while loop is present inside another while loop then it is called nested while loop.
Introduction to the loops
KnowledgeHut
Rated 4.0/5 based on 16 customer reviews

Introduction to the loops

Python has a powerful conceptcalled loops.Loops makes use of called looping (iteration), which helps cut out our repetitive code. This is very helpful when you want to do something times simply write the initial code then you can repeat multiple times till a particular condition will not met.The purpose of loops is to repeat the same, or similar, code several times. This number of times could be specified to a certain number, or the number of times could be dictated by a certain condition being met.  A conditional loop has the potential to become an infinite loop when nothing in the loop's body can affect the outcome of the loop's conditional statement. The While loop and the For loop are the two common types of conditional loops. You can also provide a numerical range(sequence) of values to control how many times the code will execute.  In Python, there are two primary structures for loops: for while For Loop: “for” loop is iteratively execute code for each item in a pre-defined list Iterations that you know how many times it will occur (even if you can stop it before) means that you know how many times loop will run. The syntax of a for loop is for (followed by (: ) ) With the for loop we can execute a number of statements, once for each item in a list, tuple, set. Let say, you want to repeat some code multiple times but you will not care about variable I, so it will be good practice to replace I with _, this means that we will not care about this valueWhere can we use for loop? A for loop is used for iterating over a sequence (either a list, a tuple, a dictionary, a set, or a strings). for loop are used for sequential traversal. Ex- traversing a list or strings or array etc. Syntax: for i in sequence: Body of for “All values inside the sequence will take i variable”In this above example, we have created list i.e A having strings values, “for” is the syntax of for loop followed by “:”, then there is a variable i that is called placeholder it will take all the values from the sequence i.e. A and then it will print all the values inside the placeholder i.e. i, print(i)In above example, we have created list B in that we took non-sequential order integer value, however loop will execute on each of the item, in the same manner in which we are defined in the list B.Placeholder(i) is the unique variable inside the for loop it will represent all the values inside the sequence i.e. B, i is not a pre-defined variable so in place of i we can use anything means that any variable, anystrings, except numeric value we can use anything. In the below example you will better understand how this placeholder will work, in place of placeholder we can use X variable and completely unrelated strings also we can putHope you will better understand that whichever placeholder you will put it does not matter. In the above example, list B contains only numeric values, but you can use other type as well like text strings.for loop on Text Strings:In the example below, a list called B is defined with two text strings that represent two statement. The for loop will run iteratively on each text strings (represented by the placeholder strings in each iteration). List B contains two text strings i.e. “This is str” and “This is boolean” so in the first iteration “This is str” will print then in the next iteration “This is boolean” will print.We can achieve the output in another way by using range method to loop.for loop on Data Structures:In the below example, we have created a list i.e. List, that contains other lists i.e Months and Income. Placeholder flist represent all the elements from the List and List contains two lists i.e Months and Income so it will repeat one by one in which you have defined.In the first iteration Months will print and in the second iteration Income will print.while loop: A loop is used to repetitively execute program until a defined condition will not met  Iterations that you will observe something else to decide when to stop an iteration - those are the while loops.While loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition will not satisfied then, after the loop in the program will execute.If the test expression is true, statements inside the body of while loop will execute. Then, the test expression is evaluated again. The process goes on till the test expression is evaluated to false. A while loop can also terminate when a break or return within the statement body is executed. You can use continue to terminate the current iteration without exiting the while loop. continue it will pass control to the next iteration of the while loop. The termination condition will evaluate at the top of the loop. Where can we use while loops? The while loop in Python will iterate over a block of code if the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand. Ex: - let say, If we want to check the grade of every student in the class, we loop from 1 to that particular range of number. When the number of times is not known, we use a "while" loop. The while loop is used repeat a section of code an unknown number of times until a specific condition is met. Ex- say we want to know how many times a given number can be divided by 2 before it is less than or equal to 1. Syntax: while condition: body_of_while Condition can be a limit that how many times the while loop will run, you can see in the below example the loop will run till 9 we have restrict the iteration. Once loop will reaches 10 (x=10) then loop will not executeA while loop start with while and then condition.  In the below code if you notice that we have given the indentation, it must have to give the indentation means that statement is inside the loop. In this example, we add 1 in the x and value of x does not exceed the given condition (x
Rated 4.0/5 based on 16 customer reviews
6329
Introduction to the loops

Python has a powerful conceptcalled loops.Loops ma... Read More

Introduction to Yield in Python

When we write a function, which should perform some operation and provide some result back, we generally use the return statement for returning the result.The yield statement is only used when defining a generator function and is only used in the body of the generator function. Yield are used in Python generators. A python generator is defined like a normal function, but whenever it will needto generate a value, it does so with the yield keyword rather than return. If the body of a def function contains yield, the function will becomea generator function. A Python generator is a function return a generator iterator (just an object we can iterate over) by calling yield .Yield maybe called with a value, in which case that value is treated as the "generated" value. Yield is a keyword in Python that will used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Return sends a value back to its caller, whereas yield can produce a sequence of values. We must use yield when we want to iterate over a sequence but don't want to store the entire sequence in memory so in that case you can use yield Python generators. The function will continue the execution immediately after the last yield run. It will allow its code to produce a series of values and sending them back like a list.Example:In the above example, yield is the keyword and 1, 2, 3 are the values that will store in the generator and to print the value inside the generator we are using for loop. We can use yield when we want to iterate over a sequence, but don't want to store the entire sequence in memory.Explaining the Iterables: To understand what yield does, you must understand what generators are. And before generators come iterables.Aniterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop. Ex- iterables include lists, tuples, and strings - any such sequence can be iterated over in a for-loop. In simpler words, whatever that will appear on the right-side of a for-loop: for x in iterable:  is aniterable.Iterablecan be anything that you can loop over with a for loop.An object can becallediterable,if we can get an iterator from iterable. Maximum built-in containers in Python like: list, tuple, string etc. areiterables.Important property(Method) of an iterable is that it has an __iter__() method or iter() method which allows any iterable to return an iterator object. Sequences Sequences are a very common type of iterable. Ex- for built-in sequence types are lists, strings, and tuples.Iterable will support element access using integer indices via the __getitem()__ special method (indexing) and define a __length()__ method that returns the length of the sequence. Also, we can use the slicing technique on them.Other IterablesMany things in Python are iterables, but not all of them are sequences. Dictionaries, file objects, sets, and generators all are iterables, but none of them is a sequence.We can loop over an iterable without using a for loop. Some of us may think that we can use a while loop and generate indices to get this output.It seems that this approach works very well for lists and other sequence objects as well. What about the non-sequence objects? They don’t support indexing, so this approach will not work for them, we will get an error.But how the Python’s for loop works on these iterables then? We can see that it works with sets.When you create a list, you can read its items one by oneWhat is an Iterator? Iterator is an object which can be looped through and maintains its state during the iteration which means it remembers where it is during an iteration. An iterator is an object that enables a programmer to traverse a container, particularly lists. Different types of iterators are often provided via a container's interface. It has a __next__() method that returns the next value from the iteration and updates the state to point at the next value. Iterator is simplyan object that can be iterated upon. An object it will return data, one element at a time.Python iterator object must implement two special methods, that is __iter__() and __next__() , collectively called the iterator protocol.Thepurpose of an iterator is allow to process with every element of a container while isolating the user from the internal structure of the container. The container provides the methods for creating iterators. Iterator is an object and it will represent a stream of data. You can create an iterator object by applying the iter() function to an iterable.Difference between iterable and iterator. Iterable is an object, which can iterate over. It will create an Iterator when passed to iter() method. Iterator is an object, which is used to iterate over an iterable object using __next__() method. For example, a list is iterable but a list is not an iterator.When we will apply the iter() function to an iterable we will get an iterator. If we will call the iter() function on an iterator it will give us itself back in python.You can use an iterator to manually loop over the iterable it came from. if repeated passing of iterator to the built-in function next() it will return successive items in the stream. Once, when you consumed an item from an iterator, it has gone. When data aren’t available it will give us a StopIteration and exception is raised.Iterators also have the __iter__() method and it will return self object.List is an iterable. When you will use a list comprehension, you create a list, and so an iterableThese iterables are handy because you can read them, but you store all the values in memory and it’s not always what you want when you have a lot of values. Iterator Protocol The iterator objects are required to support the following two methods, which together form the iterator protocol: iterator.__iter__() Return the iterator object itself. This is required to allow both containers and iterators to be used with the for statements. iterator.__next__() Return the next item from the container. If there are no items, then it will raise the StopIteration exception. We have seen some examples with iterators. Python has many built-in-classes that are iterators. Ex- an enumerate and reversed objects are iterators. Enumerate ExampleReversed ExampleThe Python’s zip, map and filer objects are also iterators. Explaining the Generators: A Generator is a function use to store the value by using yield keyword. A function which returns a generator iterator. This is a normal function only except that it will contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the next() function in python.If function will contains the yield keyword then that function will become a generator and you can print the value by using for loop.You can convert a function into generator simply you need to use yield keyword in below example you can see that we can use multiple yield statement to return the dataIn above example, we defined new_generator() function in this we have assign a variable n and giving the value as 1 then print the statement and then yield the valueIf we execute generator function as a normal function then it will give us the object so for that we have to store the function in the variable x then we have use next method for executionYielding into Python List:We can use directly generator for making a list and we can store the value inside the mylist then we can print the mylist by using for loopPython Generators with a Loop:In the below example, we defined a function i.e. reverse_string and it is a generator because we are using yield keyword and we are iterating each word from the statementGenerator Expressions in Python: We use a generator function or generator expression when we want to create a custom iterator. They are simpler to use and need less code to achieve the output. Generator expressions are similar to the list comprehensions,Just like a list comprehension, the general expressions are concise. In most cases, they use to written in one line of code.An expression that returns an iterator. It looks like a normal expression followed by a for expression defining a loop variable, range, and an optional if expression ex,We can also add a conditional expression on the iterable. You can see in the above example, we did square root of the even number, we directly print the value without store the single value and we print the class i.e. generator  Explaining the Yield: Yield is a simple statement. Its primary job is to control the flow of a generator function similar tothat return statements. Yield that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that will present a yield keyword is termed as generator When you call a generator function or use a generator expression, you return a iterator called a generator. You can try to assign this generator to a variable in order to use it. When you will call to special methods on the generator, such as next(), the code within the function is executed till yield. When the yield statement is hit, the program suspends function execution and returns the yielded value to the caller. (Return stops function execution completely.) When a function is suspended, the state of that function is saved. This includes any variable bindings local to the generator in python, the instruction pointer, the internal stack, and any exception handling. This allows you to resume function execution whenever you will call one of the generator’s methods. Like this, all function evaluation picks back up right after yield. You can see this in action by using multiple yield statements:In the above example, we defined a function i.e. counter consist of while loop which has one condition (x < 5) and is yielding the value of x and then it will increment by 1. If we use yield keyword in the function then that function will become as Generator Yield is the special keyword in python, yield will know what it execute in the last time.In the above function, when we executed first time we are getting 0 as output but in the second execution it will increment by 1 and we got 1 as output and again it will iterate the loop till the condition will not satisfy. When we use yield keyword in the function it will store the state of the local variableExample:In the above example, you can see that with the help of yield keyword It is easy to find the word inside the string statement and it will count the number of times that word will occur because yield keyword will know the last state Benefits of yield: Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. We should use yield when we want to iterate over a sequence but don't want to store the entire sequence in memory yield is used in Python generators. A generator function or expression will defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. Conclusion: In this tutorial, you have learned about Iterable, Generator functions, Yield Iterable: An iterable is something you can loop over. Sequences are a very common type of iterable. So many things in Python are iterables, but not all of them are in sequences. An iterator is an object and it will represent a stream of data. It does the iterating over an iterable. You can use an iterator in python to get the next value or to loop over it. Once, your loop over an iterator, there are no more stream values. Additionally, in Python, the iterators are also iterables which act as their own iterators. However, the difference is that iterators don’t have some of the features that some iterables have. They don’t have length and can’t be indexed. Many built-in classes in Python are iterators. Generator: We have learnt, how to use and write generator functions and generator expressions A generator function is a function which returns an iterator. A generator expression is an expression that returns an iterator. Yield: The yield keyword in python is used to return a value from a function(just like return ) but this keyword also maintains the state of the local variables of the function and when the function is called again in python, the execution is started from the yield statement executed last time.We should use python yield when we want to iterate over a sequence but don't want to store the entire sequence in memory
Rated 4.0/5 based on 13 customer reviews
7898
Introduction to Yield in Python

When we write a function, which should perform som... Read More

How to use Split in Python

The split function is a string manipulation tool in Python.  A string is a collection or array of characters in a sequence that is written inside single quotes, double quotes, or triple quotes; a character ‘a’ in Python is also considered a string value with length 1. The split function is used when we need to break down a large string into smaller strings.Strings represent Unicode character values and are mutable in nature which means the value of a string cannot be altered after it has been declared.  An example of declaring and displaying a string in Python: name = “Python”  print(name[0]) Although we cannot change a string after the declaration, we can split a string into different strings using a variety of different ways in Python.  In this article, we will take a deeper dive and understand how to use Split is in Python. We will begin by understanding what the Split function does, what the need is for such a function and how we work with this function. We will then take a look at Split parameters in Python and the different ways of using the Split function. What is Split in Python? If you have worked on the concatenation of strings that are used to merge or combine different strings into one, the split function performs just the opposite of it. The function scans through a string and separates it when it encounters a separator which has been specified before.  However, if the function does not find any defined separator, it uses white space by default.  The syntax of the Split function is as follows: string.split(separator,max) The separator is a character that has been pre-defined and it gets placed between each variable in the output. The split function depends on the value of the separator variable. What is the need for Split function? The Split function returns a list of words after separating the string or line with the help of a delimiter string such as the comma ( , ) character. Some of the merits of using Split function in Python are listed as follows: It is useful in situations where you need to break down a large string into smaller strings. If the separator is not present within the split function, the white spaces are considered as separators. The split function helps to analyze and deduce conclusions easily. It is also useful in decoding strings encrypted in some manner.  How to work with Split function? Strings variables in Python contain numeric and alphanumeric data which are used to store data directories or display different messages. They are very useful tools for programmers working in Python.  The .split() method is a beneficial tool for manipulating strings. It returns a list of strings after the main string is separated by a delimiter. The method returns one or more new strings and the substrings also get returned in the list datatype.  A simple example of the split function is as follows: x = ‘red,orange,yellow’  x.split(“,”)  [‘red’, ‘orange’, ‘yellow’] Here, we have declared a string variable x with three strings. When the split function is implemented with a comma ( , ) as a separator, the strings get separated with commas in between them.  What are Split parameters in Python? The Split function analyses through a string and separates it whenever the program comes across a pre-defined separator. It depends on mainly three different parameters to optimize the execution of the program: Separator - It instructs Python where to break the string. It works as a delimiter and the string is separated depending upon the pre-defined separator. It is optional which means if the separator is not specified in split, the function uses white space as the default separator. However, if the separator is specified as a string value, the output will be an empty string. Maxsplit-  It specifies the number of times the string can be broken up. It is also optional and it’s default value is -1 which denotes that there are no limits on the number of times a string can be split. If the maxsplit is not defined in the split function, the entire string is scanned and Python separates it whenever a delimiter is encountered.    Return - It returns a list of strings after the split function breaks the string by the specified separator. What are the different ways of using the Split function? Python consists of several different ways by which we can implement the Split function. The different techniques are explained below: Python consists of several different ways by which we can implement the Split function. The different techniques are explained below: Splitting String by Space The split() method in Python splits the string on whitespace if no argument is specified in the function. An example of splitting a string without an argument is shown below: str = “Python is cool”  print(str.split()) The output of the above code is as follows: [‘Python’, ‘is’, ‘cool’] In the example above, we have declared variable str with a string value. You can see that we have not defined any arguments in the Split function, so the string gets split with whitespaces.  Splitting String on first occurrence When we split a string based on the first occurrence of a character, it results in two substrings – the first substring contains the characters before the separator and the second substring contains the character after the separator.  An example of splitting a string on the first occurrence of a character is shown below: str = “abcabc”  print(str.split(c)) The output of the above code is as follows: [‘ab’, ‘abc’] Here, we have declared str with a string value “abcabc”. The split function is implemented with separator as “c” and maxsplit value is taken as 1. Whenever the program encounters “c” in the string, it separates the string into two substrings  – the first string contains characters before “c” and the second one contains characters after “c”.  Splitting a file into a list When you want to split a file into a list, the result turns out to be another list wherein each of the elements is a line of your file. Consider you have a file that contains two lines “First line\nSecond Line”. The resulting output of the split function will be [ “First Line”, “Second line”]. You can perform a file split using the Python in-built function splitlines(). Consider you have a file named “sample.txt” which contains two lines with two strings in each line respectively – “Hi there”, “You are learning Python”. An example of splitting “sample.txt” into a list is shown below: f = open(“sample.txt”, “r”)  info = f.read()  print(info.splitlines())  f.close() The output of the above code is as follows: [‘Hi there’, ‘You are learning Python’] We have a file “sample.txt” which is opened in read (“r”) mode using the open() function. Then, we have called f.read() which returns the entire file as a string. The splitlines() function is implemented and it splits the file into two different substrings which are the two lines contained in “sample.txt”. Splitting a String by newline character (\n) You can split a string using the newline character (\n) in Python. We will take a string which will be separated by the newline character and then split the string. The newline character will act as the separator in the Split function.  An example of splitting a string by newline character is shown below: str = “Welcome\nto\nPython\nSplit”  print(str.split(‘\n’)) The output of the above code is as follows: [‘Welcome’, ‘to’, ‘Python’, ‘Split’] Here, we have declared a variable str with a string that contains newline characters (\n) in between the original string.The Split function is implemented with “\n”  as the separator. Whenever the function sees a newline character, it separates the string into substrings.  You can also perform split by newline character with the help of the splitlines() function. Splitting a String by tab (\t) Tabs are considered as escape characters “\t” in text (.txt) files. When we split a string by tabs, the Split function separates the string at each tab and the result is a list of substrings. The escape character “\t” is used as the separator in the Split function. An example of splitting a string by tab is shown below: str = “Python\tis\ta\tscripting\tlanguage”  print(str.split(“\t”)) The output of the above code is as follows: ['Python', 'is', 'a', 'scripting', 'language'] Here, the variable str is declared with a string with tabs (“\t”). The Split function is executed with “\t” as the separator. Whenever the function finds an escape character, it splits the string and the output comes out to be a list of substrings. Splitting a String by comma (,) We can also split a string by commas (“,”) where commas act as the delimiter in the Split function. The result is a list of strings that are contained in between the commas in the original string.  An example of splitting a string by commas is shown below: str = “Python,was,released,in,1991”  print(str.split(“,”)) The output of the above code is as follows: ['Python', 'was', 'released', 'in', '1991'] Here, the variable str is declared with a string with commas (“,”)  in between them. The Split function is implemented with “,”  as the separator. Whenever the function sees a comma character, it separates the string and the output is a list of substrings between the commas in str. Splitting a String with multiple delimiters You can split a string using multiple delimiters by putting different characters as separator in the Split function. A delimiter is one or more characters in a sequence that are used to denote the bounds between regions in a text. A comma character (“,”) or a colon (“:”) is an example of a delimiter. A string with multiple delimiters can be split using the re.split() function. An example of splitting a string with multiple delimiters is shown below: import re  str = 'Python\nis; an*easy\nlanguage'  print(re.split('; |, |\*|\n',str)) The output of the above code is as follows: ['Python', 'is', 'an', 'easy', 'language'] In the example above, we import the built-in module re which imports the libraries and functions of Regular Expressions. The variable str is declared with a string with multiple delimiters like newline (\n), semicolon (;), or an asterisk (*). There.split() function is implemented with different delimiters as separator and the output is a list of strings excluding the delimiters.  Splitting a String into a list When you split a string into a list around a delimiter, the output comes out to be a partitioned list of substrings. You can take any delimiter as a separator in the Split function to separate the string into a list. An example of splitting a string into a list is shown below: str = “New York-Texas-Colombia”  print(str.split(“-”)) The output of the above code is as follows: ['New York', 'Texas', 'Colombia'] The variable str is declared with a string with dash characters( - ) in between and the Split function is executed with a dash ( - )  as the separator. The function splits the string whenever it encounters a dash and the result is a list of substrings. Splitting a String by hash (#) You can also split any string with a hash character (#) as the delimiter. The Split function takes a hash (#) as the separator and then splits the string at the point where a hash is found. The result is a list of substrings.  An example of splitting a string using a hash is shown below: str = “Python#isa#multi-purpose#language”  print(str.split(“#”)) The output of the above code is as follows: ['Python', 'is a', 'multi-purpose', 'language'] The variable str is declared with a string with hash characters( # ) in between them. The Split function is executed with a hash as the separator. The function splits the string wherever it finds a hash  ( # ) and the result is a list of substrings excluding the hash character. Splitting a String using maxsplit parameter The maxsplit parameter defines the maximum number of splits the function can do. You can perform split by defining a value to the maxsplit parameter. If you put whitespaces as separator and the maxsplit value to be 2, the Split function splits the string into a list with maximum two items.  An example of splitting a string using the maxsplit parameter is shown below: subjects = “Maths Science English History Geography”  print(subjects.split(“ ”,2)) The output of the above code is as follows: ['Maths', 'Science', 'English History Geography']  Here, you can see the variable str is declared with a string of different subject names. The Split function takes whitespace (“ ”) as a separator and the maximum number of splits or maxsplit is 2. The first two strings “Maths” and “Science” are split and the rest of them are in a single string. Splitting a String into an array of characters You can separate a string into an array of characters with the help of the list() function. The result is a list where each of the element is a specific character.  An example of splitting a string into an array of characters  is shown below: str = “PYTHON”  print(list(str)) The output of the above code is as follows: ['P', 'Y', 'T', 'H', 'O', 'N'] Here, the variable str is a string. The string is separated into individual characters using the list() function and the result is a list of elements with each character of the string. Splitting a String using substring You can obtain a string after or before a specific substring with the split() function. A specific string is given as the separator in the Split function and the result comes out to be the strings before and after that particular string.   An example of splitting a string using substring  is shown below: fruits = “Orange Banana Mango Apple Cherry”  print(fruits.split(“Mango”)) The output of the above code is as follows: ['Orange Banana ', ' Apple Cherry'] Here, the variable fruits is a string with names of different fruits. We take the string “Mango” as the separator in the Split function. Whenever the function finds the string “Mango”, it splits the whole string into two substrings – one substring before “Mango” and another substring after “Mango”.  Miscellaneous tips on Split function Since we have now reached at the end of the article, let me give you some useful tips on the Split function: If the maxsplit is not defined in the function and there are enough delimiters in the string, the result will have a length of maxsplit +1.If you want to recombine a string that has been already split in Python, you can perform the concatenation of strings.The Python Split function only works on string variables. If you come across any problem with working with split, you can force the compiler to treat the variable as a string with str(x).Conclusion The .split() function in Python is a very useful tool to split strings into chunks depending upon a delimiter which could be anything starting from characters or numbers or even text. You can also specify the number of splits you want the function to perform using maxsplit, which is used to extract a specific value or text from any given string using list or Arrays. Here are the key areas you should have gained a good understanding on by reading this article: What is a String. What is Split and why is it needed. How does a Python Split function work. What are the Split parameters. What are the many different ways of Splitting strings in Python Important tips on Split You have learned about the Python split function and the different ways to implement in your program. With this, you can begin to work on any project which requires the use of the Split.  If you wish to extend your knowledge about Strings and Split function in Python, you can refer to the official documentation of Python. Also, don’t forget to check out the remaining tutorials made freely available to you. 
Rated 4.0/5 based on 12 customer reviews
6618
How to use Split in Python

The split function is a string manipulation tool i... Read More

How to concatenate strings using Python

The string data type in Python is a very important building block of programming. It is basically a sequence of one or more characters that represent Unicode characters. The characters could be letters, numbers, or symbols. The strings are immutable in nature, which means they are unchanging.  You can implement string formatting techniques in Python like merging or splitting strings in Python. When you merge or combine two or more strings in Python, it is called string concatenation. In this article, we will understand what concatenation is and its importance. We will delve into different ways of concatenating strings including the + operator, * operator and % operator and take you through various concatenation methods including the join() method, format() function, the f-string and StringIO methods. What is concatenation in Python? String Concatenation is the operation of joining character strings end-to-end. If you have just started working on Python, you might come through a time when you will need to merge or combine the contents of two or more strings together. In technical terms, this merging or combining of strings together into a single string is called String concatenation. The simplest way to explain concatenation in Python is when you take two separate strings stored in the Interpreter and combine them so that they become one single string. For example, if you take one string as “foot” and another string as “ball” and then merge them into using concatenation technique it comes out to be a single string “football”. There are several ways in which you can perform string concatenation in Python. However, the simplest method is using the “+” operator. What is the need for String formatting in Python? String formatting in Python is a robust and important part of the toolkit of any Python programmer. String formatting techniques have greatly evolved since the time Python was developed. Almost every piece of production software created has its advantage in some way or the other.  Formatted strings in Python are evaluated at run time which acts as a basic capability of any high-level language. At a basic level, String concatenation using the “+” operator might seem inefficient and also difficult to make expressive. This is where Python’s string formatting starting from the “%” formatting to the format() method comes into action. They exhibit great potential when it comes to crafting strings. How can we concatenate strings in Python? Python comprises of a number of ways when it comes to concatenate or combine strings together. Since Python is an object-oriented programming language, everything in Python is an object. So, the new string that is created after concatenation is also referred to as a string object in Python.  Let us see what are the different ways by which we can concatenate strings in Python. Using the + operator The simplest and most common method of concatenating a string is using the plus symbol (“+”). Let us see an example to understand it better: a = “Python”  b = “is”  c = “cool”  print(a + b + c) PythoniscoolHere, we have declared three string variables “a”, “b” and “c” with three different string values. Then, we concatenate the three strings with the help of the “+” operator and display the output using the print statement. The output is the combination of the three strings together.  You might use the “+” operator when you have few strings to concatenate. This is because strings are immutable i.e. they cannot be changed once created. So, for each concatenating statement, the interpreter creates a new object. Thus, it will be quite inefficient if you try to concatenate many strings using the “+” operator. Another disadvantage of the “+” operator is that it does not allow any separator or delimiter between the strings. If you want to concatenate “Hello” and “World” with whitespace as a separator, you need to fo something like this “Hello” + “ ” + “World” and the output will be “Hello World”. Using the * operator The asterisk (*) operator is used when you want to concatenate the same string repeatedly. For example, if you have a string “red” and you want the same string to be concatenated three times, you use the * operator. The result will be “redredred”.  An example to illustrate concatenation of string using “*” operator: a = "Python"  print(a * 3) PythonPythonPython Here, we have declared a single string variable “a” with a string value. Then, we concatenate the string with the help of the “*” operator and display the output using the print statement. The output combines the string with the same string three times repeatedly. Using the join() method The join() method is the most flexible way of concatenating strings in Python. If you have many strings and you want to combine them together, use thejoin() method. It is a string method and the most interesting thing about join() is that you can combine strings using a separator. It works on iterators like lists, tuples, string, dictionaries, etc.  An example to illustrate concatenation of string using “*” operator: a = "Welcome"  b = "to"  c = "Python"  print(“-”.join([a,b,c])) Welcome-to-Python Here, we have declared three string variables “a”, “b” and “c” with three different string values. Then, we concatenate the three strings with the help of the join() method with “-” as a separator and display the output using the print statement. The output is the combination of the three strings together with dash (“-”) operator in between the strings. Using the % operator The modulus operator (“%”) can be used for both string formatting and string concatenation. It is useful for cases in which you need to combine strings and also perform basic formatting. An example to illustrate concatenation of string using “%” operator: a = "Apple"  b = "Shake"  print(“% s % s” % (a, b)) Apple Shake Here, we have declared two string variables “a”, and “b”with two different string values. Then, we concatenate the two strings with the help of the (“%”) and display the output using the print statement.  The “% s” denotes the string data type in Python and the modulus (“%”) operator combines the string stored in the two variables “a” and “b”. The string value in the variables is passed to the string data type and the output is displayed as the combination of two strings. Using the format() function The str.format() function is a powerful function in Python which is also used for both String formatting and String Concatenation. This function combines different elements within a string through positional formatting.     An example to illustrate concatenation of string using format() function: a = "Virgin"  b = "Mojito"  print(“{} {}”.format(a, b)) Virgin Mojito Here, we have declared two string variables “a” and “b”with two different string values. Then, we concatenate the two strings with the help of the format() function and display the output using the print statement.  The curly braces (“{}”) used here are used to fix the string position. The first variable is stored in the first curly braces and the second one in the second curly braces. The job of format() function is to concatenate the strings stored in variables “a” and “b” and display the combined string. Using the f-string  Formatted string literals or f-strings, in short, are string literals in Python. They contain an f at the beginning and curly braces that contain the expressions. It calls the str() method when an object argument is used as field replacement. Let us see an example to illustrate the concatenation of string using f-string: a = "Moscow"  b = "Mule"  print(f’{a} {b}‘) Moscow Mule Here, we have declared two string variables “a” and “b”with two different string values. Then, we concatenate the two strings with the help of the f-string and display the output using the print statement.  The f-string expressions are evaluated at runtime and they are being formatted using the __format__ protocol in Python. It is considered to be a cleaner and easier way of concatenating strings in Python when compared to the format() function.Using StringIO String concatenation using StringIO is also a very flexible way for combining different strings in Python. In this method, we have to import the StringIO() function from the IO module.  An example to illustrate the concatenation of string using StringIO: from io import StringIO  a = StringIO()  a.write(“Machine ”)  a.write(“Learning”)  print(a.getvalue()) Machine Learning Here, we have declared two string variables “a” and “b”with two different string values. Then, we concatenate the two strings with the help of the StringIO() imported from the IO module and display the output using the print statement.  Here, the variable “a”acts as a file object in Python. The write() function is used here to write the string to the file and the getvalue() function returns the entire content of the file. Miscellaneous concatenations in Python We have covered all the ways by which we can concatenate different strings in Python. Let us see some few more miscellaneous examples to understand String Concatenation better. Concatenate multiple strings There are various ways by which you can concatenate multiple strings in Python. The most common among them is using the plus (“+”) operator. You can combine both string variables and string literals using the “+” operator. However, there’s another method that allows an easy way of concatenating multiple strings. It is using the in-place (+=) operator. The in-place operator concatenates the sequence with the right operand and the result gets assigned to that sequence. Let us see an example of string concatenation using the (“+=”) operator: a = "Artificial "  b = "Intelligence"  a += b  print(a) Artificial Intelligence Here, two string variables “a” and “b” are declared with two different string values. The string on the right side of the “+=” operator is combined with the string variable on the left side. Then, the output is displayed using the print statement.  You can also add a string to the end of a string variable using the “+=” operator: a = "Basket"  a += "ball"  print(a) Basketball Another way of concatenating multiple strings in Python is just by writing string literals consecutively: a = "Red""Green""Blue"  print(a) RedGreenBlueConcatenate strings and numbers There are numerous ways of concatenating strings in Python. However, not all methods can concatenate strings and numbers. If you use the “+” operator to combine strings and numbers, it will raise errors. This is because strings can hold any recorded characters but numbers like  integers or floats are recorded number value. a = "Rolls Royce "  b = 1948  print(a + b) Traceback (most recent call last):   File "", line 6, in   TypeError: can only concatenate str (not "int") to str The error shows that the interpreter can concatenate a string value with another string value but cannot concatenate a string value with an integer. Although, you can overcome this problem with the help of the str() function in Python. It converts any integer or floating-point number into a string.  Let us see the same example with the str() function: a = "Rolls Royce "  b = str(1948)  print(a + b) Rolls Royce 1948 The str() function converts the integer value 1948 into a string and then it is concatenated with variable “a” and the output is displayed using the print statement. You can also use the format() function when you need to convert a number with decimal places or zero padding. Concatenate a list of strings into one string You can concatenate a list of strings into one string using the join() method. It takes a character as a delimiter string. If you use an empty string as the delimiter, the list of strings will be simply concatenated without any separator.  Let us see an example to concatenate a list of strings using the join() function: a = ["Apple", "Orange", “Banana”, “Mango”]  print(“\n”.join(a)) Apple  Orange  Banana  Mango Here, the variable “a” is a list declaredwith four different string values. We have used newline (“\n”) as the delimiter in the join() method which inserts a newline for each of the strings. The output is the four strings with each string in a newline. You can use any other delimiter like comma (,) or hyphen (-) in the join() method and then perform concatenation. Also, note that thejoin() method can also concatenate other iterators like tuples, sets, dictionaries, etcConcatenate a list of numbers into one string Python does not allow the concatenation of strings with numbers or numbers with numbers. However, you can convert a numeric value into a string using the str() method and then perform concatenation. If you want to combine a list of numbers into one string, the first thing you need to do is convert each integer in a list to a string using the str() function. Then, combine all the converted strings into a single string with the join() method. Let us see an example to understand it better: a = [1, 2, 3, 4, 5]  b = [str(a) for a in a]  print(“;”.join(b)) 1;2;3;4;5 Here, the variable “a” is a list declared with five integer values. We convert each of the integers into a string using the str() function and store it in variable “b”. Then, we combine them together using the join() method with a colon (;) as the delimiter.Here, the variable “a” is a list declared with five integer values. We convert each of the integers into a string using the str() function and store it in variable “b”. Then, we combine them together using the join() method with a colon (;) as the delimiter. Some useful tips on concatenation Now let me give you some useful tips on String concatenation in Python: The string-formatting operator “%” is a potentially fast and suitable operator when you need to concatenate a few pieces of string. Also, you don’t need to call the str() function when combining numbers because this operator does it implicitly. It also enhances the readability of the code. The join() method is the fastest, cleanest, and most elegant and readable method when you need to concatenate many small pieces of string into a larger string. When you have many small pieces of strings that come either from input or computation and are not in a sequence, always use a list to contain the strings. You can use list comprehension or append method in Python to arrange your list in a sequence.  Conclusion Let us summarize what we have learned in this article so far –  Concatenation and its importance. Different ways of concatenating strings. Some miscellaneous concatenation methods. Important tips on concatenating strings. Concatenation is a crucial part of String manipulation in Python. There are numerous ways to perform concatenation. However, some are more useful than others in some cases.  Now that you have quite an experience in concatenating strings, you can look out for other string formatting methods that Python provides or you can check out the PEP article on Advanced String Formatting on Python.org for more information. 
Rated 4.0/5 based on 14 customer reviews
9832
How to concatenate strings using Python

The string data type in Python is a very important... Read More

How to use sys.argv in Python

The sys module is one of the common and frequently used modules in Python. In this article, we will walk you through how to use the sys module. We will learn about what argv[0] and sys.argv[1] are and how they work. We will then go into how to parse Command Line options and arguments, the various ways to use argv and how to pass command line arguments in Python 3.x In simple terms,Command Line arguments are a way of managing the script or program externally by providing the script name and the input parameters from command line options while executing the script. Command line arguments are not specific just to Python. These can be found in other programming languages like C, C# , C++, PHP, Java, Perl, Ruby and Shell scripting. Understanding sys.argv with examples  sys.argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments. Let us take a closer look with a few examples. With the len(sys.argv) function, you can count the number of arguments. import sys print ("Number of arguments:", len(sys.argv), "arguments") print ("Argument List:", str(sys.argv)) $ python test.py arg1 arg2 arg3 Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3']Module name to be used while using sys.argv To use sys.argv, you will first need to the sys module. What is argv[0]? Remember that sys.argv[0] is the name of the script. Here – Script name is sysargv.py import sys print ("This is the name of the script: ", sys.argv[0]) print ("Number of arguments: ", len(sys.argv)) print ("The arguments are: " , str(sys.argv))Output:This is the name of the script:  sysargv.py                                                                               Number of arguments:  1                                                                                                 The arguments are:  ['sysargv.py']What is "sys. argv [1]"? How does it work? When a python script is executed with arguments, it is captured by Python and stored in a list called sys.argv. So, if the below script is executed: python sample.py Hello Python Then inside sample.py, arguments are stored as: sys.argv[0] == ‘sample.py’ sys.argv[1] == ‘Hello’ sys.argv[2] == ‘Python’Here,sys.argv[0] is always the filename/script executed and sys.argv[1] is the first command line argument passed to the script . Parsing Command Line options and arguments  Python provides a module named as getopt which helps to parse command line options and arguments. Itprovides a function – getopt, whichis used for parsing the argument sequence:sys.argv. Below is the syntax: getopt.getopt(argv, shortopts, longopts=[]) argv: argument list to be passed.shortopts: String of short options as list . Options in the arguments should be followed by a colon (:).longopts: String of long options as list. Options in the arguments should be followed by an equal sign (=). import getopt import sys   first ="" last ="" argv = sys.argv[1:] try:     options, args = getopt.getopt(argv, "f:l:",                                ["first =",                                 "last ="]) except:     print("Error Message ")   for name, value in options:     if name in ['-f', '--first']:         first = value     elif name in ['-l', '--last']:         last = value   print(first + " " + last)Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py -f Knowledge -l Hut Knowledge Hut (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py --first Knowledge –last Hut Knowledge HutWhat are command line arguments? Why do we use them? Command line arguments are parameters passed to a program/script at runtime. They provide additional information to the program so that it can execute. It allows us to provide different inputs at the runtime without changing the code. Here is a script named as argparse_ex.py: import argparse parser = argparse.ArgumentParser() parser.add_argument("-n", "--name", required=True) args = parser.parse_args() print(f'Hi {args.name} , Welcome ')Here we need to import argparse package Then we need to instantiate the ArgumentParser object as parser. Then in the next line , we add the only argument, --name . We must specify either shorthand (-n) or longhand versions (--name)  where either flag could be used in the command line as shown above . This is a required argument as mentioned by required=True Output:  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name Nandan  Hi Nandan , Welcome  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py -n Nandan  Hi Nandan , Welcome The example above must have the --name or –n option, or else it will fail.(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name   usage: argparse_ex.py [-h] --name NAME argparse_ex.py: error: the following arguments are required: --namePassing command line arguments in Python 3.x argv represents an array having the command line arguments of thescript . Remember that here, counting starts fromzero [0], not one (1). To use it, we first need to import sys module (import sys). The first argument, sys.argv[0], is always the name of the script and sys.argv[1] is the first argument passed to the script. Here, we need to slice the list to access all the actual command line arguments. import sys if __name__ == '__main__':     for idx, arg in enumerate(sys.argv):        print("Argument #{} is {}".format(idx, arg))     print ("No. of arguments passed is ", len(sys.argv))Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python argv_count.py Knowledge Hut 21 Argument #0 is argv_count.py Argument #1 is Knowledge Argument #2 is Hut Argument #3 is 21 No. of arguments passed is  4Below script - password_gen.py is used to generate a secret password by taking password length as command line argument.import secrets , sys, os , string ''' This script generates a secret password using possible key combinations''' ''' Length of the password is passed as Command line argument as sys.argv[1]''' char = string.ascii_letters+string.punctuation+string.digits length_pwd = int(sys.argv[1])   result = "" for i in range(length_pwd):     next= secrets.SystemRandom().randrange(len(char))     result = result + char[next] print("Secret Password ==" ,result,"\n")Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python password_gen.py 12 Secret Password == E!MV|,M][i*[Key takeaways Let us summarize what we've learnt so far. We have seen how to use the sys module in Python, we have looked at what areargv[0] and sys.argv[1] are and how they work, what Command Line arguments are and why we use them and how to parse Command Line options and arguments. We also dived into multiple ways to use argv and how to pass command line arguments in Python 3.xHope this mini tutorial has been helpful in explaining the usage of sys.argv and how it works in Python. Be sure to check out the rest of the tutorials on KnowledgeHut’s website and don't forget to practice with your code! 
Rated 4.0/5 based on 14 customer reviews
5933
How to use sys.argv in Python

The sys module is one of the common and frequently... Read More

The self variable in Python explained with Python tips

If you have been working on Python, you might have across the self variable. You can find it in method definitions and in initializing variables. However, before coming to the self variable, let us have an idea about classes and instances in Python.  What are Instance methods and Class methods in Python? You might have heard of instances and classes while working on Python. Class variables are defined within a class and they are shared with all the instances (objects) of the class whereas instance variables are owned by the instances of a class. For different instances, the instance variables are different. Likewise, Python also contains class methods and instance methods. The class methods inform about the status of the class. On the other hand, instance methods are to set or get details about instances or objects.   If you want to define an instance method, the foremost parameter of the method should always have to be self. Let us understand this with the help of example code – class myClass:      def instance_method(self):          return “Instance method is called”, self The method “instance_method” is a regular instance method. The method accepts one single parameter – self. The self variable points to an instance of the class myClass when the method is revoked. Though the method takes only one parameter here, it can also accept more than one parameter. The instance methods can easily access different attributes and other methods on the same object with the help of the self variable. The self variable also has the power to modify the state of an object and using the self.__class__  attribute, instance methods can also access the class. Thus, the instance methods are also able to modify the class state. Now, let us see what happens when we call “instance_method”: >>>obj = myClass()  >>>obj.instance_method()  ('Instance method is called', ) This shows that “instance_method” can access the object instance (printed as ) through the self parameter. What happens is that the self parameter is replaced with the instance object obj when the method is called. However, if you pass the instance object manually, you will get the same result as before: >>>myClass.instance_method(obj)  ('Instance method is called', ) Note that self is actually not a defined keyword in Python but a convention.What is Self in Python? Unlike this variable in C++, self is not a keyword rather it is more of a coding convention. It represents the instance or objects of a class and binds the attributes of a class with specific arguments. The use of self variable in Python helps to differentiate between the instance attributes (and methods) and local variables. If you do not want the variables of your class to be shared by all instances of the class, you can declare variables within your class without self. Let us understand this with an example: class Car:      def __init__(self, model):  self.model = model      def Car_info(self):  print("Model : ", self.model) Here, we have declared a class Car with one instance variable self.model = model. The value of the instance variable will be unique to the instance objects of the class that might be declared. However, if you want the variables to be shared by all instances of the class, you need to declare the instance variables without self. Otherwise, it would be ambiguous since all cars will have the same model. Need for Self in Python The self variable is used to represent the instance of the class which is often used in object-oriented programming. It works as a reference to the object. Python uses the self parameter to refer to instance attributes and methods of the class.  Unlike other programming languages, Python does not use the “@” syntax to access the instance attributes. This is the sole reason why you need to use the self variable in Python. The language contains methods that allow the instance to be passed automatically but not received automatically. Explicit definition of self The Zen of Python says “Explicit is better than Implicit”. Programmers of other languages often ask why self is passed as an explicit parameter every time to define a method. There are a few reasons for this. Firstly, since Python uses a method or instance attribute instead of a local variable when we read self.name or self.age, it makes it absolutely clear you are using an instance variable or method even if you have no knowledge about the class definition. Secondly, if you explicitly refer or call a method from a particular class in Python, you do not need to use any special syntax for that.  Finally, the third reason is that the explicit definition of self helps Python understand whether to assign to an instance variable or to a local variable. In simpler terms, local variables and instances exist in two separate namespaces and we need to inform Python which namespace should be used. What is a Python class self constructor? The self variable in Python can also be used to access a variable field within the class definition. Let us understand this with the help of example code: class Student:     def __init__(self, Alex):          self.name = Alex    #name created in constructor      def get_student_name(self):          return self.name In the example above, self refers to the variable age of the class Student. The variable age is local to the method. While the method is running, the variable age exists within the class. If there is a variable within a method, the self variable will not work. If you wish to define global fields, you need to define variables outside the class methods.   Is self a keyword in Python? There is a question that always hovers among Python programmers. Is self actually a keyword in Python? Unlike other programming languages like C++, where self is considered to be a keyword, in Python it is a convention that programmers tend to follow. It is basically a parameter in a method definition. However, you can use any other name in place of self like another or me or anything else for the first parameter of a method. Another reason why it is suggested by most people is that it enhances the readability of your code. Let us see an example to understand it: class myClass:   def show(another):   print(“another is used in place of self”)  If you compare this code with the code for the Python class self constructor, you will notice that here we have used the name another in place of self. Now let us create an object of this class and see the output: object = myClass()   object.show()another is used in place of selfYou can see that the program works even if we use some other name in place of the self variable. It works exactly the same way as the self variable does. Why "self" should be used as the first parameter of instance methods in python  This can be understood by the below example. We have a Rectangle class which defines a method area to calculate the area : class Rectangle ():      def __init__(self,x = 0,y = 0):          self.x = x          self.y = y      def area (self):          """Find area of rectangle"""          return (self.x * self.y)  rec1=Rectangle(6,10)  print ("Area is:", rec1.area()) Output:  Area is: 60    In the above example, __init__() defines three parameters but only 2 arguments are passed (6 and 10). Similarly, area () requires one but no arguments are passed.  Rectangle.area and rec1.area in the above example are different and not exactly the same. >>> type(Rectangle.area )    >>> type(rec1.area)  Here, the first one is a function and the second one is a method. A unique feature of Python is that the object itself is passed as the first argument to the corresponding function. In the above example, the method call:  rec1.area()is equivalent to:  Rectangle.area(rec1). Generally, when the method is called with some arguments, the corresponding class function is called by placing the method's object before the first argument.  Therefore: obj.method(args) becomes Class.method(obj, args). This is the reason the first parameter of a function in a class must be the object itself. Writing this parameter as self is merely a convention and not a keyword so it has no special meaning in Python. We could use other names (like this, that) but it is not preferred as it degrades code readability.Should we pass self to a method? Since we can use any other name instead of using the self variable, then what will happen if we just pass self to a method definition. Let us consider the class myClass we have used earlier.  A method named something is defined within the class with a parameter another and two arguments: class myClass:   def something(another, argument1, argument2):   pass Now, let us declare an instance obj of myClass and call the method something with the help of the instance object: obj = myClass()  obj.something(argument1, argument2) Python performs an internal work on the method call and converts it into something like this: myClass.something(obj, argument1, argument2)  This shows that another variable (used in place of self) refers to the instance object of the class. Note that the pass keyword used in the method something does nothing. It is used as a dummy in situations where you do not want any operation to be performed but there is a syntax requirement of a certain programming element. How can we skip self in Python? Consider a situation where the instance method does not need to have access to the instance variables. In such cases, we can consider skipping the self variable in defining methods. Let us have a clear understanding of the fact with example code: class Vehicle:  def Car():  print(“Rolls Royce 1948”)  obj = Vehicle()  print(“Complete”) If you run the following code, the output will be as follows: Complete We have not declared the self variable here but there is still no error in the program and the output comes out fine. However, what will be the case if we call the Car() method: obj = Vehicle()  obj.Car() When we compile the code after calling the Car() method, it shows an error like this: Traceback (most recent call last):   File "", line 11, in   TypeError: Car() takes 0 positional arguments but 1 was given The output shows an error since the method Car() takes 0 positional arguments but we have given 1 positional argument to it. This is because when the instance obj is created, it is automatically passed as the first argument to the method Car() even if we have not declared the self variable. However, if you try to access the instance method Car() with the help of the class reference, there will be no errors and the program will work fine: class Vehicle:  def Car():  print("Rolls Royce 1948")  obj = Vehicle()  Vehicle.Car()  Rolls Royce 1948 Difference between self and __init__  self : self represents the instance of the class. By using the "self" keyword all the attributes and methods of the python class can be accessed. __init__ : "__init__" is a reserved method in python classes. It is known as a constructor in object oriented concepts. This method is called when an object is created from the class and allows the class to initialize class attributes .. Usage of "self" in class to access the methods and attributes: class Rectangle:     def __init__(self, length, breadth, cost_per_unit =0):         self.length = length         self.breadth = breadth         self.cost_per_unit = cost_per_unit     def perimeter(self):         return 2 * (self.length + self.breadth)     def area(self):         return self.length * self.breadth     def calculate_cost(self):         area = self.area()         return area * self.cost_per_unit  # length = 40 cm, breadth = 30 cm and 1 cm^2 = Rs 100  r = Rectangle(40, 30, 100)  print("Area of Rectangle:",r.area())  print("Cost of rectangular field is : Rs ",r.calculate_cost()) Output:  Area of Rectangle: 1200  Cost of rectangular field is : Rs  120000 We have created an object of Rectangle class. While creating the Rectangle object, we passed 3 arguments – 40,30,100; all these arguments are passed to "__init__"method to initialize the object. Here, the keyword "self” represents the instance of the class. It binds the attributes with the given arguments. Self represents the same object or instance of the class. If you see, inside the method "area” , self.length" is used to get the value of the attribute "length".  attribute "length" is bind to the object (instance of the class) at the time of object creation. "self" represents the object inside the class. "self" works just like "r" in the statement “r = Rectangle(40,30, 100)".  If you see the method definition "def area(self): ” , here "self" is used as a parameter in the method because whenever we call the method,  the object (instance of class) is automatically passed as a first argument along with other arguments of the method. If no other arguments are provided only "self" is passed to the method. That's the reason "self" is used to call the method inside the class("self.area()").  We used object (instance of class) to call the method outside of the class definition("r.area()").  "r" is the instance of the class when the method "r.area()” is called; the instance "r" is passed as first argument in the place of self. Miscellaneous Implementations of self Let us now discuss some of the miscellaneous implementations of the self variable. Similar variables for Class Method and Static Method A class method is a method that is bound to the class. Let us understand a class method with an example – class myClass:  @classmethod  def classmethod(cls):  return “Class Method is called”  obj.classmethod() The same behavior of the self variable is present with the Class methods too but the only difference is that for class methods, the convention is to use cls as the variable name instead of self. The class methods take a cls parameter instead of the self parameter. When the method is called, it points to the class. The class method cannot modify the object state but it can modify the class state of all the class instances. On the other hand, static methods are self-sufficient functions and this type of method takes neither a self nor a cls parameter. Let us see an example of a static method – class myClass:  @staticmethod  def staticmethod():  return “Static Method is called”  obj.staticmethod() Since a static method does not accept any parameter, they cannot modify object state or even class state. They are primarily used to namespace different methods and Python restricts them in the data they can access. Note that both the methods here are marked with @classmethod and @staticmethod decorators to flag it as a class method and static method respectively. The self variable is bound to the current instance The self variable allows us to access the properties of the current instance. Let us understand this with an example – class Person:  def __init__(self, n):  self.name = n  def walk(self):  print(f“{self.name} is walking”)  obj1 = Person(“Alex”)  obj2 = Person(“Charles”)  obj1.walk()  obj2.walk()  Alex is walking Charles is walking Here, we have a class Person with two methods __init__ and walk declared with the self parameter. We have created two different instances of the class – obj1 and obj2. When the first instance is revoked, “Alex” is printed with the method walk() whereas when the second instance is revoked, “Charles” gets printed with the properties of the instance method walk(). Tips about the Python self variable Since we have now reached the end of the article, let me give you some tips about when to use and when not to use the self variable in Python. Use self when:you define an instance method, since it is passed automatically as the first parameter when the method is called;you reference a class or an instance attribute from inside an instance method;you want to refer to instance variables and methods from other instance methods. Don’t use self when: you want to call an instance method normally;referencing a class attribute inside the class definition but outside an instance method;you are inside a static method.  Conclusion Let us recap the key points we have covered in this article, namely:Instances and Classes in Python. Self variable and its importance. The explicitness of the self variable. Python class self constructor. Passing self as a method. Skipping self in Python. Variables used for Class methods and Static methods. Bounding of self to the current instance. When to use and when not to use self in Python. With good knowledge about the self variable in Python and its internal working in Python, it is now time for some practice. If you, however, wish to know more about Python self, you can head right on to the official documentation of Python.Happy coding! 
Rated 4.0/5 based on 10 customer reviews
12381
The self variable in Python explained with Python ...

If you have been working on Python, you might have... Read More