Author name: Vikram Chiluka

Python Program for collections.UserDict() Function

Dictionary in Python:

A Python dictionary is a list of objects that are not in any particular order i.e Unordered.

A dictionary is made up of a collection of key-value pairs. Each key-value pair corresponds to a specific value.

Curly braces { } can be used to describe a dictionary by enclosing a comma-separated list of key-value pairs.

Every key is separated from its associated value by a colon “:”

collections.UserDict() Function:

Python has a dictionary-like container called UserDict, which is available in the collections module. This class serves as a container for dictionary objects. This class is useful when one wants to create their own dictionary, either with modified or new functionality. It can be thought of as a method of adding new behaviors to the dictionary. This class takes a dictionary instance as an argument and simulates the contents of a regular dictionary. This class’s data attribute provides access to the dictionary.

Syntax:

collections.UserDict([initial data])

Python Program for collections.UserDict() Function

Method #1: Using collections Module (Static Input)

Approach:

  • Import UserDict() function from the collections module using the import keyword.
  • Give the dictionary as static input and store it in a variable.
  • Pass the given dictionary as an argument to the UserDict() function to create a user dictionary for the given dictionary.
  • Store it in another variable.
  • Print the above result.
  • Create an empty user dictionary using the UserDict() function and store it in another variable.
  • Print the above obtained empty user dictionary.
  • The Exit of the Program.

Below is the implementation:

# Import UserDict() function from the collections module using the import keyword.
from collections import UserDict
# Give the dictionary as static input and store it in a variable.
gvn_dict = {'p': 180, 'q': 190, 'r': 200}
# Pass the given dictionary as an argument to the UserDict() function to
# create a user dictionary for the given dictionary.
# Store it in another variable.
rsltuesr_dicnry = UserDict(gvn_dict)
# Print the above result.
print("The user dictionary for the given dictionary is :")
print(rsltuesr_dicnry.data)
# Create an empty user dictionary using the UserDict() function and store
# it in another variable.
emty_userdictry = UserDict()
# Print the above obtained empty user dictionary.
print("The Empty user dictionary is :")
print(emty_userdictry.data)

Output:

The user dictionary for the given dictionary is :
{'p': 180, 'q': 190, 'r': 200}
The Empty user dictionary is :
{}

Example2:

Approach:

  • Import UserDict() function from the collections module using the import keyword.
  • Create a class by passing the UserDict function as an argument.
  • Inside the class, create a function for stopping the deletion of items from a given dictionary.
  • Inside the function raise some random RuntimeError.
  • Create another function by passing the parameter as none for stopping the poping of items from a given dictionary.
  • Inside the function raise some random RuntimeError.
  • Create another function by passing the parameter as none for stopping the popitem from a given dictionary.
  • Inside the function raise some random RuntimeError.
  • Inside the main function,
  • Give the dictionary as static input and store it in a variable.
  • Create an object for the above class by passing the given dictionary as an argument and store it in another variable.
  • Print the given dictionary.
  • Delete an item from the dictionary using the pop() function.
  • The Exit of the Program.

Below is the implementation:

# Import UserDict() function from the collections module using the import keyword.
from collections import UserDict
  
 
# Create a class by passing the UserDict function as an argument.
class GivenDictionary(UserDict):
     
    # Inside the class, create a function for stopping
    # the deletion of items from a given dictionary.
    def delete(self):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given dictionary")
         
    # Create another function by passing the parameter as none for stopping the
    # poping of items from a given dictionary.
    def pop(self, a = None):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given dictionary")
         
    # Create another function by passing the parameter as none for stopping the
    # popitem from a given dictionary.
    def popitem(self, a = None):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given dictionary")
     
# Inside the main function
# Give the dictionary as static input and store it in a variable.
gvn_dict = {'p':4,'q':9 ,'z': 13}
# Create an object for the above class by passing the given dictionary as an argument 
# and store it in another variable.
rslt_dictry = GivenDictionary(gvn_dict)
# Print the given dictionary. 
print("The given dictionary = ")
print(rslt_dictry)
# Delete an item from the dictionary using the pop() function.
rslt_dictry.pop(1)

Output:

The given dictionary = 
{'p': 4, 'q': 9, 'z': 13}
Traceback (most recent call last):
File "jdoodle.py", line 36, in <module>
rslt_dictry.pop(1)
File "jdoodle.py", line 18, in pop
raise RuntimeError("You Cannot delete an element from the given dictionary")
RuntimeError: You Cannot delete an element from the given dictionary

Method #2: Using collections Module (User Input)

Approach:

  • Import UserDict() function from the collections module using the import keyword.
  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Pass the given dictionary as an argument to the UserDict() function to create a user dictionary for the given dictionary.
  • Store it in another variable.
  • Print the above result.
  • Create an empty user dictionary using the UserDict() function and store it in another variable.
  • Print the above obtained empty user dictionary.
  • The Exit of the Program.

Below is the implementation:

# Import UserDict() function from the collections module using the import keyword.
from collections import UserDict
# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = dict()
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee =  input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Pass the given dictionary as an argument to the UserDict() function to
# create a user dictionary for the given dictionary.
# Store it in another variable.
rsltuesr_dicnry = UserDict(gvn_dict)
# Print the above result.
print("The user dictionary for the given dictionary is :")
print(rsltuesr_dicnry.data)
# Create an empty user dictionary using the UserDict() function and store
# it in another variable.
emty_userdictry = UserDict()
# Print the above obtained empty user dictionary.
print("The Empty user dictionary is :")
print(emty_userdictry.data)

Output:

Enter some random number of keys of the dictionary = 3
Enter key and value separated by spaces = x welcome
Enter key and value separated by spaces = y to
Enter key and value separated by spaces = z Python-Programs
The user dictionary for the given dictionary is :
{'x': 'welcome', 'y': 'to', 'z': 'Python-Programs'}
The Empty user dictionary is :
{}

Example2:

Approach:

  • Import UserDict() function from the collections module using the import keyword.
  • Create a class by passing the UserDict function as an argument.
  • Inside the class, create a function for stopping the deletion of items from a given dictionary.
  • Inside the function raise some random RuntimeError.
  • Create another function by passing the parameter as none for stopping the poping of items from a given dictionary.
  • Inside the function raise some random RuntimeError.
  • Create another function by passing the parameter as none for stopping the popitem from a given dictionary.
  • Inside the function raise some random RuntimeError.
  • Inside the main function,
  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Create an object for the above class by passing the given dictionary as an argument and store it in another variable.
  • Print the given dictionary.
  • Delete an item from the dictionary using the pop() function.
  • The Exit of the Program.

Below is the implementation:

# Import UserDict() function from the collections module using the import keyword.
from collections import UserDict
  
 
# Create a class by passing the UserDict function as an argument.
class GivenDictionary(UserDict):
     
    # Inside the class, create a function for stopping
    # the deletion of items from a given dictionary.
    def delete(self):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given dictionary")
         
    # Create another function by passing the parameter as none for stopping the
    # poping of items from a given dictionary.
    def pop(self, a = None):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given dictionary")
         
    # Create another function by passing the parameter as none for stopping the
    # popitem from a given dictionary.
    def popitem(self, a = None):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given dictionary")
     
# Inside the main function
# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = dict()
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee =  input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee
    
# Create an object for the above class by passing the given dictionary as an argument 
# and store it in another variable.
rslt_dictry = GivenDictionary(gvn_dict)
# Print the given dictionary. 
print("The given dictionary = ")
print(rslt_dictry)
# Delete an item from the dictionary using the pop() function.
rslt_dictry.pop(1)

Output:

Enter some random number of keys of the dictionary = 2
Enter key and value separated by spaces = welcometo 12
Enter key and value separated by spaces = Python-Programs 13
The given dictionary = 
{'welcometo': '12', 'Python-Programs': '13'}
Traceback (most recent call last):
File "jdoodle.py", line 49, in <module>
rslt_dictry.pop(1)
File "jdoodle.py", line 18, in pop
raise RuntimeError("You Cannot delete an element from the given dictionary")
RuntimeError: You Cannot delete an element from the given dictionary

Python Program for collections.UserDict() Function Read More »

Programming Languages: Python vs R

Python:

Guido van Rossum developed Python in 1991 as a multi-paradigm language.

Python is a high-level object-oriented programming language that is interpreted. It is a language that is dynamically typed. It supports multiple programming models, including object-oriented, imperative, functional, and procedural paradigms, and has an interface to many OS system calls.

R Programming Language:

R is a statistical programming language. It is used in the creation of statistical software and data analysis. R has grown in popularity as data mining and data analysis has grown in popularity. R provides a wide range of libraries for graphical techniques in addition to statistical techniques. It can generate static graphs, which are used to create graphs suitable for publication. There are also dynamic and interactive graphs available. For all of the packages that it supports, R has a package archive network (CRAN- Comprehensive R Archive Network). It has over 10,000 packages in it. R is a command-line language, but several interfaces offer interactive graphical user interfaces to help developers with their work.

The primary distinction between R and Python is in the goals of data analysis.

The main difference between the two languages is how they approach data science. Both open-source programming languages have large communities that are constantly expanding their libraries and tools. However, while R is primarily used for statistical analysis, Python offers a more general approach to data manipulation.

R vs Python

                                       R                            PYTHON
R codes require more upkeep/maintenancePython code is more robust and simpler to maintain.
The R programming language is primarily used by scholars and researchers.

 

Python is the programming language of choice for the majority of programmers and developers.
R is more suitable for data visualization.Python is preferable for deep learning.
R is primarily a statistical language, but it is also used for graphical techniques.Python is a general-purpose programming language used for development and deployment.
R has hundreds of packages or methods for performing the same task. It has several packages for a single task.Python was created with the idea that “there should be one, and preferably only one obvious way to do it.” As a result, it has a few main packages to complete the task.
R is a simple language to learn. It has less complicated libraries and plots.Learning Python libraries can be difficult.
For some functions, R only supports procedural programming, while for others, it supports object-oriented programming.Python is a multi-paradigm programming language. Python supports a variety of paradigms, including object-oriented, structured, functional, and aspect-oriented programming.
This is a command-line interpretive programming language.Python strives for simplification in its syntax. It is related to the English language.
R is slightly slower than Python, but only marginally.It is faster and more efficient
R makes it simple to perform complex mathematical calculations and statistical tests.Python is ideal for creating something new from the ground up. It is also used in application development.
Because R was created for data analysis, it includes more powerful statistical packages.The statistical packages in Python are less powerful.

Let’s take a look at some more significant differences.

1. Collection of Data:

Python supports a wide range of data formats, from comma-separated value (CSV) files to JSON retrieved from the web. SQL tables can also be directly imported into Python code. The Python requests library for web development makes it simple to retrieve data from the web and use it to build datasets. R, on the other hand, is intended for data analysts who want to import data from Excel, CSV, or text files.

R dataframes can be created from Minitab or SPSS files. While Python is more versatile for retrieving data from the web, modern R packages such as Rvest are designed for basic web scraping.

2. Exploration of Data:

Pandas, Python’s data analysis library, can be used to explore data in Python. In a matter of seconds, you can filter, sort, and display data. R, on the other hand, is designed for the statistical analysis of large datasets and provides a variety of data exploration options.

R allows you to create probability distributions, perform various statistical tests, and employ standard machine learning and data mining techniques.

3.Visualisation of Data:

Visualization is not one of Python’s strong suits, you can use the Matplotlib library to create basic graphs and charts. Furthermore, the Seaborn library enables you to create more appealing and informative statistical graphics in Python.

R, on the other hand, was designed to display the results of statistical analysis, with the base graphics module allowing you to quickly create basic charts and plots. ggplot2 can also be used to create more complex plots, such as complex scatter plots with regression lines.

4. Community Support:

Both R and Python have a robust community. Both languages have a mailing list for users, StackOverflow groups, user-contributed documents, and code. As a result, there is a tie between the two languages. However, neither language has customer service. As a result, users are limited to online communities and developer documentation for assistance.

5.Unstructured Data:

Unstructured data accounts for 80% of the world’s data. The majority of the data generated by social media is unstructured. To analyze unstructured data, Python provides packages such as NLTK, scikit-image, and PyPI. R has libraries for analyzing unstructured data, but the support isn’t as good as it is in Python. Nonetheless, both languages can be used to analyze unstructured data.

 

 

 

 

 

 

 

 

Programming Languages: Python vs R Read More »

What Do You Need to Know About Competitive Python Programming?

Hello there, programmer! I’m sure you’re aware of what Competitive Programming is. However, there are a few things to keep in mind when coding in Python. These minor changes can make a significant difference in your code.

Python Competitive Programming:

1. Using Generators in Python

Python includes a generator that allows you to write your own iterator function. A generator is a type of function that returns an iterator object with a sequence of values rather than a single value. A yield statement, rather than a return statement, is used in a generator function.

For Example:

def Python_generators():
    yield 15
    yield 20
    yield 30


for itr in Python_generators():
    print(itr)

It is also useful for returning multiple values sequentially at the same time.

2. Using built-in Functions in Python

Python includes a number of functions that are readily available for use. Using built-in functions and libraries is preferable to the traditional method.

Some of the built-in Function Examples are:

1.len(): The length of an object is returned by this method.

gvn_lst = [10, 20, 30, 40, 50]
lst_len = len(gvn_lst)
print("The length of the given list = ", lst_len)

Output:

The length of the given list =  5

2. min(): Returns the minimum element in the given list.

gvn_lst = [90, 20, 30, 40, 50]
minmum_ele = min(gvn_lst)
print("The minimum element in the given list = ", minmum_ele)

Output:

The minimum element in the given list =  20

3. max(): Returns the maximum element in the given list.

gvn_lst = [90, 20, 30, 40, 50]
maxmum_ele = max(gvn_lst)
print("The maximum element in the given list = ", maxmum_ele)

Output:

The maximum element in the given list = 90

4. lower(): Converts the given string into lowercase.

gvn_str = "HELLO BTECHgeeks"
lwr_str = gvn_str.lower()
print("The given string after converting into lowercase = ", lwr_str)

Output:

The given string after converting into lowercase =  hello btechgeeks

5. upper(): Converts the given string into uppercase.

gvn_str = "welcome all"
upr_str = gvn_str.upper()
print("The given string after converting into uppercase = ", upr_str)

Output:

The given string after converting into uppercase =  WELCOME ALL

Similarly, we have many built-in functions which make code easier.

3.itertools in Python:

The itertools module can be extremely useful in solving some complex problems.

itertools.permutations() method: This method returns all the possible permutations of a given list.

for example:

import itertools
gvn_lst = ['a', 'b', 'c']
rslt = itertools.permutations(gvn_lst)
rslt_lst = list(rslt)
print("The all permutations of the given list are :")
print(rslt_lst)

Output:

The all permutations of the given list are :
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

The same thing can be done by writing your own logic and functions, but it will be far more complex and time-consuming.

4.map() Function in Python:

When we need to take input from all the elements of an integer array in a single line separated by white spaces, the map function is our best.

Using the map function reduces the complexity of dealing with multiple values entered on a single line.

For example:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
givn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
print("The given list = ",givn_lst)

Output:

Enter some random List Elements separated by spaces = 20 46 72 35
The given list = [20, 46, 72, 35]
5. Python String Concatenation:

In Python, To concatenate multiple strings, we have two options:

  • adding strings to strings using the ‘+’ operator.
  • using the join function.

adding strings to strings using the ‘+’ operator:

gvn_str1 = "hello"
gvn_str2 = "btechgeeks"
rslt_str = gvn_str1+gvn_str2
print("The concatenated string is :", rslt_str)

Output:

The concatenated string is : hellobtechgeeks

using the join function:

gvn_lst = ["hello", "this", "is", "Python-Programs"]
rslt_str = ''.join(gvn_lst)
print("The Concatenated string is : ", rslt_str)

Output:

The Concatenated string is :  hellothisisPython-Programs

 

 

 

What Do You Need to Know About Competitive Python Programming? Read More »

The 6 Most Important Programming Languages to Learn

Computer scientists and software developers are in high demand. New employees are being hired, and developers all over the world are being asked to reskill.

A solid understanding of the top programming languages is required for careers in computer science. So, if you’re looking to reskill, change careers, or simply learn something new, a new programming language is a good place to start.

When deciding on a language to learn, several factors must be considered, including the difficulty level, the average salary for that language, and how that language is used in the industry. With these considerations in mind, we examined the top 2021 tech trends and predictions to determine which programming languages are the best to learn in 2021.

The 6 Most Important Programming Languages

They are:

  1. Java
  2. Python
  3. Kotlin
  4. C/C++
  5. JavaScript
  6. Swift

Java:

Java is a well-known programming language that has been around for quite some time. It is still one of the most popular and widely used languages. Java is most commonly used in web development, app development, and big data, but it can be used in almost any field (especially distributed systems).

Java is required for enterprise-level web apps and microservices, which are expected to grow in popularity over the next year. Java will continue to dominate the banking sector and the Indian IT market in 2021.

Java is required for Android development because it provides efficient memory allocation and high performance. It can also be used on the backend of websites such as Google, Twitter, Amazon, and YouTube.

Almost every large organization will require Java skills, particularly in mobile development. Investment in Java frameworks such as Spring, Struts, and Hibernate increased in 2021.

The following are some reliable resources for learning Java development:

  • CodeChef
  • CodeGym
  • Pluralsight
  • Hackerrank

Python:

Python is a programming language that every programmer should be familiar with. Python’s syntax is not only intuitive and simple to learn but is also used in fields that are expected to grow in 2021, namely machine learning and artificial intelligence.

Python is the most popular language for machine learning and data science because of its popular ML libraries, such as Pandas and Scikit-learn. Anyone interested in a career in data science should be familiar with Python.

Machine learning jobs are expected to be worth $31 billion globally by 2024, with a 40 percent annual growth rate over a six-year period.

Python is also extremely adaptable. Backend development, mobile apps, software development, data science, and even system scripting are all done with it. Python for web development is expected to grow in 2021 as well.

Kotlin:

In today’s world, when it comes to Android app development, the name ‘Kotlin’ is unquestionably the first to come to mind! However, there has been a significant shift in developer preference for Kotlin since Google announced it as its preferred language for Android application development. According to the Stack Overflow survey, Kotlin is the fourth most popular programming language. In addition, the number of Kotlin users in the Github community is rapidly growing.

In a nutshell, Kotlin is a statically typed general-purpose programming language with object-oriented and functional programming features. The language’s best feature is that it is fully interoperable with Java and supports all Java libraries. Furthermore, the language is quite simple to learn, and it can be used for web development as well as desktop application development in addition to Android development. Javalin, KTor, and Vertex are some of the popular frameworks for Kotlin, and companies such as Pinterest, Uber, Netflix, and others are hiring Kotlin developers. Because it is well known that the Android market is not going away anytime soon, you can choose to learn Kotlin in 2021 for some worthwhile career opportunities in the future.

C/C++:

C/C++ are without a doubt some of the oldest programming languages available, but they have never lost their credibility or usability. In fact, both of these languages serve as the foundations for many of today’s advanced programming languages.

Both languages are necessary for any computer science or programming career. C and C++ developers can use compilers for most platforms, and because they are high-performance languages, they are used to build programs that require high performance, such as kernel development, client/server applications, and large commercial products (Adobe and Firefox).

C/C++ is also widely used in game development, computer graphics, and virtual reality, all of which are expected to grow significantly in 2021. Almost all major corporations seek C/C++ skills, so there has never been a better time to learn C.

The following are some reliable resources for learning C/C++:

  • Udemy: C and C++ Programming: Step-by-Step Tutorial
  • Udemy: C, C++, Java; A Programming MegaPrimer for Beginners
  • Udemy: Mastering C++ Programming — From Zero to Hero

JavaScript:

JavaScript is a popular programming language, particularly for web development. In fact, it is widely regarded as the Internet’s standard programming language. Almost everything you see on the Internet is built on JavaScript. With web development expected to grow in 2021, it’s a good one to learn.

JavaScript can be used in both the front-end and back-end of a website to add dynamic functionality. It also serves as the foundation for the majority of web libraries and frameworks, such as React, Vue, and Node.

You must be familiar with JavaScript if you want to work for any company that creates web design.

Swift:

Swift language graphs have skyrocketed due to a rapid increase in the demand for iOS mobile developers. It was essentially introduced by Apple, and you can learn how to use it to launch a career as an iOS developer.

Swift is also simple to learn and supports nearly everything that Objective-C does, making it an ideal language for mobile developers.

It is also used with IBM Swift Sandbox, IBM Bluemix, and the majority of popular iOS apps such as WordPress, SoundCloud, and Mozilla Firefox.

Other top languages having demand:

There are many other languages that deserve to be heard. According to our research, the following languages will be in demand in 2021 but may not be as important for your upskilling/career change.

Golang: Golang is a Google language that is used to create projects such as Kubernetes, Docker, and Blockchain.
Scala:

Scala is an acronym that stands for Scalable Language. It is a programming language with multiple paradigms. The Scala programming language combines functional and object-oriented features. It is a language that is statically typed. Its source code is compiled into bytecode, which is then executed by the Java virtual machine (JVM).

R: R is used in data science and machine learning programming language that is useful for visualization.
PHP: Used for Backend web development.

 

The 6 Most Important Programming Languages to Learn Read More »

Indentation in Python

In Python, indentation is used to create a group or set of statements. Many popular programming languages, including C and Java, use braces ( ) to define a block of code, whereas Python uses indentation.

Working of Indentation in Python:

We must define a set of statements for functions and loops when writing Python code. This is accomplished by properly indenting the statements within that block.

The leading whitespaces (spaces and tabs) at the beginning of a line are used to determine the line’s indentation level. To group the statements for that code block, you must increase the indent level. Similarly, in order to close the grouping, reduce the indentation.

To create or increase the indentation level of the code, four white spaces or a single tab character are typically used. Let’s look at an example to better understand code indentation and statement grouping.

For Example:

def number():
    print("hello btechgeeks")

    if True:
        print("It is True")
    else:
        print("This is False")


print("Task completed")

Rules of Python Indentation:

  • A backslash cannot be used to divide indentation into multiple lines.
  • The first line of Python code cannot have indentation; otherwise, an IndentationError will be thrown.
  • To create an indentation, avoid combining tabs and whitespaces. Because text editors in non-Unix systems behave differently, mixing them can result in incorrect indentation.
  • It is preferable to use whitespaces rather than the tab character for indentation.
  • The best practice is to use four whitespaces for the initial indentation and then add four more whitespaces to increase the indentation.

The Advantages of Python Indentation:

Indentation is used to properly structure code in most programming languages. It’s used for grouping in Python, which makes the code automatically beautiful.

Indentation rules in Python are extremely simple. Most Python IDEs indent the code for you, making it very simple to write properly indented code.

The Disadvantages of Python Indentation:

Because whitespaces are used for indentation, if the code is large and the indentation is corrupted, it is extremely difficult to fix. It most commonly occurs when copying code from online sources, Word documents, or PDF files.

Because most popular programming languages use braces for indentation, anyone coming from the other side of the developed world finds it difficult to adjust to the idea of using whitespaces for indentation at first.

Python Indentation

Examples:

Example1:

     gvn_str = "hello btechgeeks"

Output:

File "/home/1822dd42441310e7f90ca50f56c63b98.py", line 1
    gvn_str = "hello btechgeeks"
    ^
IndentationError: unexpected indent

Explanation:

Since there is an indentation given in the first line, it raises an error.
We should not give any spaces/indentation in the code's first line.

Example2:

gvn_num = 10
if gvn_num%2==0:
print("Even number")

Output:

 File "/home/06af42430346f69242da94a74c132502.py", line 3
    print("Even number")
        ^
IndentationError: expected an indented block

Explanation:

You should give an indentation after the if conditional statement.
Hence error has occured.

Example3:

1.gvn_num = 10
2.if gvn_num%2==0:
3.    print(gvn_num)
4.      print("Even Number")

Output:

 File "/home/4b9b157f046e5479f32e894aa9c29a40.py", line 4
    print("Even Number")
                       ^
IndentationError: unindent does not match any outer indentation level

Explanation:

The indentation level of the code lines within the if block differs,
resulting in the IndentationError.

Example4:

def number():
    print("hello btechgeeks")

    if True:
        print("It is True")
    else:
        print("This is False")


  print("Task completed")

Output:

 File "/home/443adb7a95629211bdf53e795522d50a.py", line 10
    print("Task completed")
                          ^
IndentationError: unindent does not match any outer indentation level

Explanation:

The indentation error is thrown because the last print statement has 
some indentation but no statement to attach it to.

Conclusion

Python indentation makes our code look nice. It also serves as a container(grouping) for the statements in a code block. This leads to the habit of writing beautiful code all the time because it is a Must-Have requirement of the code rather than a Nice-To-Have feature.

Indentation in Python Read More »

Python Program to Print a List in 3 Easy Ways

Python provides us with a variety of data structures for storing and processing data. One of them is a list.

A Python list is a data structure that holds a mutable sequence of data values. Furthermore, a list is an ordered collection of elements, i.e. they obey the order of the elements.

The Following are the 3 Easy Ways to print the elements of a list given:

  • Using For Loop (Naïve method)
  • Using map() Function
  • Using ‘*’ Symbol

1)Using For Loop (Naïve method)

The Nave method is usually the greatest approach to begin as a starter!

Syntax:

for i in given_list:
    print(i)

Example

Approach:

  • Give the list as static input and store it in a variable.
  • Loop in the given list using the for loop.
  • Inside the for loop, print the element present at the iterator index of the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_listt = [35, 21, 'Python', 87, 58, 'welcome']
print("The All items of the given list = ")
# Loop in the given list using the for loop
for itr in gvn_listt:
    # Inside the for loop, print the element present at the iterator index of
    # the given list.
    print(itr)

Output:

The All items of the given list = 
35
21
Python
87
58
welcome

2)Using map() Function

To quickly print a Python list, combine the map() with join() function.

If the list is not a string, use map() to convert each item to a string and then join them

Syntax:

' '.join(map(str, list))

Approach:

  • Give the list as static input and store it in a variable.
  • Pass str, given list as the arguments to the map() function and join it to an empty string using the join() function and print it.
  • Print the items in a new line by using ‘\n’.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_listt = [35, 21, 'Python', 87, 58, 'welcome']
print("The All items of the given list = ")
# Pass str, given list as the arguments to the map() function and join it to an
# empty string using the join() function and print it
print(' '.join(map(str, gvn_listt)))
print()
# Print the items in a new line
print("Printing the list items in a new line :")
print('\n'.join(map(str, gvn_listt)))

Output:

The All items of the given list = 
35 21 Python 87 58 welcome

Printing the list items in a new line :
35
21
Python
87
58
welcome

Explanation:

The map method is used to convert the values in the list to string format, i.e. we map them to string format.
The elements are then assembled using the join method.

3)Using ‘*’ Symbol

We can also use the ‘*’ symbol to print the list items.

Syntax:

*List

Approach:

  • Give the list as static input and store it in a variable.
  • Print the elements of the given list using the ‘*’ symbol.
  • Print the list items in a new line.
  • By including a sep value, we may customize the output. Set the separation value to a newline using ‘\n’.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_listt = [35, 21, 'Python', 87, 58, 'welcome']
# Print the elements of the given list using the '*' symbol
print("The All items of the given list = ")
print(*gvn_listt)
print()
# Print the list items in a new line
# By including a sep value, we may customize the output.
# Set the separation value to a newline using '\n'.
print("Printing the list items in a new line :")
print(*gvn_listt, sep="\n")

Output:

The All items of the given list = 
35 21 Python 87 58 welcome

Printing the list items in a new line :
35
21
Python
87
58
welcome

Python Program to Print a List in 3 Easy Ways Read More »

Python Pandas between() Method with Examples

Pandas between() Method:

The Python Pandas module is mostly used to deal with data values that are stored in rows and columns, i.e. in a table/matrix format. Within this, we frequently see data variables with numeric values.

Before doing any type of activity, such as modeling, data must be analyzed and transformed.

To put it simply, the Python Pandas between() function enables easy analysis in terms of comparison and last moment checks.

The between() function looks for a value that exists between the start and end values given to it.

That is, it will verify which data elements fall between the start and end values supplied within a range of values.

Syntax:

series.between(start, end, inclusive=True)

start: This is the start value at which the check begins.
end: The check is stopped at this value.

inclusive: If True, it contains both the passed’start’ and ‘end’ values that are being checked. When set to ‘False,’ it excludes the’start’ and ‘end’ values from the check.
In addition, Python Pandas’ between() function only works good with numeric values and 1-dimensional DataFrames.

1) between() function in Python with inclusive set to ‘True’:

Example:

Here we used pandas.DataFrame() function to create a 1-D Dataframe.

# Import pandas module using the import keyword
import pandas as pd
# Give some random list of data and store it in a variable
gvn_data = {"ID": [11, 12, 13, 14, 15, 16], "Name": ["peter", "irfan", "mary", "riya", "virat", "sunny"], "salary": [10000, 25000, 15000, 50000, 30000, 22000]}
# Pass the given data to the DataFrame() function and store it in another variable
block_data = pd.DataFrame(gvn_data)
# Print the above result
print("The given input Dataframe: ")
print(block_data)

Output:

The given input Dataframe: 
   ID   Name  salary
0  11  peter   10000
1  12  irfan   25000
2  13   mary   15000
3  14   riya   50000
4  15  virat   30000
5  16  sunny   22000

We’ve now used the between() method on the data frame’s ‘salary’ variable.

By setting inclusive to True, it will now include and verify what all values fall between 10000 and 25000 (including 10000 and 25000 ), and then return true for the indices whose salary falls within the specified range.

# Import pandas module using the import keyword
import pandas as pd
# Give some random list of data and store it in a variable
gvn_data = {"ID": [11, 12, 13, 14, 15, 16], "Name": ["peter", "irfan", "mary", "riya", "virat", "sunny"], "salary": [10000, 25000, 15000, 50000, 30000, 22000]}
# Pass the given data to the DataFrame() function and store it in another variable
block_data = pd.DataFrame(gvn_data)
# Print the above result
print("The given input Dataframe: ")
print(block_data)
print()
# Give the lower and upper limits range and inclusive set to True as the arguments
# to the between() function and apply it to the salary block in the given data
# Store it in another variable
rslt_data = block_data["salary"].between(10000, 25000, inclusive = True)  
# Print the salaries that falls between the given range
print("The salaries that falls between the given range:")
print(rslt_data)

Output:

The given input Dataframe: 
   ID   Name  salary
0  11  peter   10000
1  12  irfan   25000
2  13   mary   15000
3  14   riya   50000
4  15  virat   30000
5  16  sunny   22000

The salaries that falls between the given range:
0     True
1     True
2     True
3    False
4    False
5     True
Name: salary, dtype: bool

Explanation:

Hence it returns False for indexes 3 and 4 because their values are 
beyond the range of 10000 to 25000.

2) between() function in Python with Categorical variable:

Let’s check what it produces for a string or categorical data.

When we send a string or non-numeric variable to the Pandas between() function, it compares the start and end values with the data given and returns True if the data values match either of the start or end values.

# Import pandas module using the import keyword
import pandas as pd
# Give some random list of data and store it in a variable
gvn_data = {"ID": [11, 12, 13, 14, 15, 16], "Name": ["peter", "irfan", "mary", "riya", "virat", "sunny"], "salary": [10000, 25000, 15000, 50000, 30000, 22000]}
# Pass the given data to the DataFrame() function and store it in another variable
block_data = pd.DataFrame(gvn_data)
# Print the above result
print("The given input Dataframe: ")
print(block_data)
print()
# Give the two names and inclusive set to True as the arguments
# to the between() function and apply it in to the "Name" block in the given data
# Store it in another variable
rslt_data = block_data["Name"].between("peter", "riya", inclusive = True)
# Print the above result
print(rslt_data)

Output:

The given input Dataframe: 
   ID   Name  salary
0  11  peter   10000
1  12  irfan   25000
2  13   mary   15000
3  14   riya   50000
4  15  virat   30000
5  16  sunny   22000

0     True
1    False
2    False
3     True
4    False
5    False
Name: Name, dtype: bool

How to Print the values (rows) obtained from between() function?

# Import pandas module using the import keyword
import pandas as pd
# Give some random list of data and store it in a variable
gvn_data = {"ID": [11, 12, 13, 14, 15, 16], "Name": ["peter", "irfan", "mary", "riya", "virat", "sunny"], "salary": [10000, 25000, 15000, 50000, 30000, 22000]}
# Pass the given data to the DataFrame() function and store it in another variable
block_data = pd.DataFrame(gvn_data)
# Print the above result
print("The given input Dataframe: ")
print(block_data)
print()
# Give the lower and upper limits range and inclusive set to True as the arguments
# to the between() function and apply it to the salary block in the given data
# Store it in another variable
rslt_data = block_data["salary"].between(10000, 25000, inclusive = True)  
# Print the salaries that falls between the given range
print("The data of salaries that falls between the given range:")
print(block_data[rslt_data])

Output:

The given input Dataframe: 
   ID   Name  salary
0  11  peter   10000
1  12  irfan   25000
2  13   mary   15000
3  14   riya   50000
4  15  virat   30000
5  16  sunny   22000

The data of salaries that falls between the given range:
   ID   Name  salary
0  11  peter   10000
1  12  irfan   25000
2  13   mary   15000
5  16  sunny   22000

 

Python Pandas between() Method with Examples Read More »

Python resource Module With Examples

Before you begin, it is crucial to understand that the resource module is a UNIX-specific package that will not work in the POSIX, i.e. Windows Operating System.

resource Module

While working with system monitoring and resources, we began to question whether there was a better way to monitor system information than manually going through all of the system logs in the control panel.

A bit further away from developing an idea relating to that concept, we get a glimmer of hope that this is possible and entirely possible in the format of a script.

Using python-crontab, sched, and the dateutil module to automate the script would offer an automatic update log scheduled at a specific interval every day, eliminating the need to manually receive information at a specific time.

But, before we try to automate it, we’ll need something to provide you with this information, which is where the resource module comes in.

The resource module is exactly what we’re seeking for because it provides basic information about system resources as well as control functionality.

Using Python’s resource module

Because the resource module is part of Python’s standard library, it does not need to be installed separately. This implies that working with the module on a fresh new server or client with Python installed should be seamless.

However, it has been observed that some versions of Python appear to have problems with the resource module; as a result, it is advised that the resource module be installed using the pip command.

Installation:

pip install python-resources

Output:

Collecting python-resources Downloading python-resources-0.3.tar.gz (8.3 kB)
Building wheels for collected packages: python-resources Building wheel 
for python-resources (setup.py) ... done Created wheel for python-resources: 
filename=python_resources-0.3-py3-none-any.whl size=7510 sha256=4a4479fd18b
0d1
c2028d460952c65c9abd89fdd6e3b5f5563a039d8b65097af5 Stored in directory: 
/root/.
cache/pip/wheels/12/07/9a/82bc654c835cf0b2c57571b89905d9f4adca8d8b8662676419 
Successfully built python-resources Installing collected packages: python-
resources Successfully installed python-resources-0.3
How to set up the ecosystem?

Importing the module

# Import all the functions from the resource module using the import keyword
from resource import *
# Import time using the import keyword
import time
The utilization of the underlying parameter

The module’s functionality is primarily determined by the parameters passed to the function that returns the relevant information.

Here are a few instances of these parameters:

  • resource.RUSAGE_SELF: Consumed resources by the calling process.
  • resource.RUSAGE_CHILDREN: Consumed resources by the children process.
  • resource.RUSAGE_BOTH: Resources used by both the current and child processes.
  • resource.RUSAGE_THREAD: Consumed resources by the current thread.

To specify which process information was requested, all of these RUSAGE_* symbols are supplied to the getrusage() function.

Approach:

# Import all the functions from the resource module using the import keyword
from resource import *
# Import time using the import keyword
import time
# Apply sleep method for some random n milliseconds say 2.
# (Function used to get information about the current process's or its children's
# resources consumption t Task that is not CPU bound)
time.sleep(2)
# Pass RUSAGE_SELF as an argument to the getrusage() function and print it.
# (Calling the resources that the current process has consumed)
print(getrusage(RUSAGE_SELF))
# Iterate till the 10^8 using the for loop
# Inside the for loop, perform some random operation say addition, subtraction etc
# (CPU bound task)
for i in range(10**8):
    # Inside the for loop, perform some random operation say addition or
    # subtraction etc
    _ = 2+3

# Pass RUSAGE_SELF as an argument to the getrusage() function and print it.
# (Calling the resources that the current process has consumed)
print(getrusage(RUSAGE_SELF))

Output:

resource.struct_rusage(ru_utime=9.211173, ru_stime=0.35864999999999997, ru_maxrss=116308, ru_ixrss=0, ru_idrss=0, ru_isrss=0, ru_minflt=36434, ru_majflt=9, ru_nswap=0, ru_inblock=13656, ru_oublock=8, ru_msgsnd=0, ru_msgrcv=0, ru_nsignals=0, ru_nvcsw=3750, ru_nivcsw=1426) 
resource.struct_rusage(ru_utime=16.827941, ru_stime=0.37112999999999996, ru_maxrss=116308, ru_ixrss=0, ru_idrss=0, ru_isrss=0, ru_minflt=36441, ru_majflt=9, ru_nswap=0, ru_inblock=13656, ru_oublock=8, ru_msgsnd=0, ru_msgrcv=0, ru_nsignals=0, ru_nvcsw=4998, ru_nivcsw=1836)
Continuing on

Working with this module should have given you a sense of the resources that the resource module can retrieve.

This module could be extended and implemented in a script to monitor system operations and resource consumption at regular intervals.

If you want to work with such an idea, you should check at additional modules like as psutil, sys, and os to work with system processes.

You might want to look at working with the dateutil, sched, and python-crontab modules to  schedule the checks to be automatic

Conclusion

The majority of the use cases for this module involve working with the creation of scripts that tend to monitor the system’s functioning and procedures.

If you want to work with system processes, testing, and monitoring, as indicated in the previous section, check out the psutil, sys, os, and dateutil modules.

 

Python resource Module With Examples Read More »

Python classmethod() with Examples

Python classmethod() is a built-in Python standard library function.

Python methods are classified into three types:

  • Static Method
  • Instance Method
  • Class Method

Static Method vs. Class Method

  1. A class method requires class as its initial parameter, but a static method does not.
  2. A static method cannot access or modify the class state, but a class method can.
  3. In general, static methods have no knowledge of the class state. They are utility methods that take some parameters and work with them. Class methods, on the other hand, must take the class as a parameter.
  4. In Python, we use the @classmethod decorator to create a class method and the @staticmethod decorator to create a static method.

Let us explore and concentrate on Python’s class method.

classmethod() in Python:

Python’s classmethod() function returns the class method for a given function. It is a built-in method in python.

A Python classmethod() can be invoked by both a class and an object. It is a method that all things have in common. It is a built-in feature of the Python programming language.

Syntax:

classmethod(function)

Parameters: This function takes the function name as an argument.

Return Value:

The converted class method is returned by the classmethod().

Approach:

  • Create a class say, Employee.
  • Inside the class, take a variable and initialize it with some random number.
  • Create a function/method say Getsalary() which accepts the class object as an argument.
  • Print the class variables by using the class object.
  • Pass the Getsalary() method to the classmethod() function and store it as the same function(Employee.Getsalary).
  • Call the above function.
  • The Exit of the Program.

Below is the implementation:

# Create a class say Employee
class Employee:
    # Inside the class, take a variable and initialize it with some random number.
    salary = 30000
    # Create a function/method say Getsalary() which accepts the class
    # object as an argument

    def Getsalary(cls_obj):
        # Print the class variables by using the class object.
        print("The salary of an Employee = ", cls_obj.salary)


# Pass the Getsalary() method to the classmethod() function and store it as the
# same function(Employee.Getsalary).
Employee.Getsalary = classmethod(Employee.Getsalary)
# Call the above function.
Employee.Getsalary()

Output:

The salary of an Employee = 30000
@classmethod Decorator:

The @classmethod decorator is a built-in function decorator that is an expression that is evaluated after you create your function. The outcome of that evaluation shadows your function definition.

The class is sent as the implicit first argument to a class method, just as the instance is passed to an instance method.

We can invoke the class name instead of the object by utilizing the decorator method. It can be applied to any of the class’s methods.

Syntax:

class c(object):
    @classmethod
    def function(cls, argument1, argument2, ...):
    /*rest of the code*/

function: It is the function to be converted into a class method.
Return Value: A class method for the function is returned.

  • A class method is a method that is linked to the class rather than the class’s object.
  • They have access to the class’s state since it takes a class parameter that points to the class rather than the object instance.
  • It has the ability to change a class state that applies to all instances of the class. It can, for example, change a class variable that applies to all instances.

For Example:

Approach:

  • Create a class say, Employee.
  • Inside the class, take a variable and initialize it with some random number.
  • Apply the @classmethod annotation for the function to access the function outside the class instead of creating an object.
  • Create a function/method say Getsalary() which accepts the class object as an argument.
  • Print the class variables by using the class object.
  • Call the above function with the class name.
  • The Exit of the Program.

Below is the implementation:

# Create a class say Employee
class Employee:
    # Inside the class, take a variable and initialize it with some random number.
    salary = 30000

    # Apply the @classmethod annotation for the function to access the function
    # outside the class instead of creating an object.
    @classmethod
    # Create a function/method say Getsalary() which accepts the class
    # object as an argument
    def Getsalary(cls_obj):
        # Print the class variables by using the class object.
        print("The salary of an Employee = ", cls_obj.salary)


# Call the above function with the class name.
Employee.Getsalary()

Output:

The salary of an Employee =  30000

The @classmethod decorator has applied to the Getsalary() function in the above example. It has a single parameter called cls_obj. The method then selects a member variable of the class automatically rather than requiring the user to pass one to the function.

Python classmethod() with Examples Read More »

Differences: Single vs Double Quotes in Python

A String is a sequence of characters. In Python, single and double quotes can be used to begin and end a string literal. In Python programming, there are two ways to represent a string.

Strings are enclosed by single or double quotes. Depending on the situation, either method (single or double quotations) is correct. When we need to employ quotes (single or double quotes) in the same string, we use single and double quotes alternately so that they can be differentiated.

Single Quotes in Python:

Single quotes are used to indicate a quote within a quote or a direct quote in the headline of a news story.

When writing Python code, we usually use single quotes for string literals.

Note: When you know your string may contain double quotes with in, always use single quotes.

Examples:

print('It's an amazing Experiance')

Output:

 File "/home/bf98c69d152913534d5c8fc67c3f5003.py", line 1
    print('It's an amazing Experiance')
              ^
SyntaxError: invalid syntax

Explanation:

It raises an error since the single quote following "It" is treated as 
the end of the string and the rest of the section is not a string.

Hence in this case, we should use double quotes(" ").
print('welcome to Python-Programs')
print('helo123#@%')

Output:

welcome to Python-Programs
helo123#@%

Double Quotes in Python:

A double quote is to set off a direct (word-for-word) quotation.

Note: When you know there will be single quotations within your string, use double quotes to enclose it.

Examples:

# Give the string as static input and store it in a variable.
gvn_str1 = "good morning all"
# Print the given string
print(gvn_str1)

Output:

good morning all
# Give the string as static input and store it in a variable.
gvn_str = "hello this is "btechgeeks", good morning all"
# Print the given string
print(gvn_str)

Output:

 File "/home/jdoodle.py", line 2
gvn_str = "hello this is "btechgeeks", good morning all"
^
SyntaxError: invalid syntax

Explanation:

It raises an error since the double-quote before "btechgeeks" is treated 
as the end of the string

If you want to print ‘WithQuotes’ in Python, you can’t accomplish it with just single (or double) quotes; you must use both at the same time.

gvn_str = "hello this is 'btechgeeks'"
print(gvn_str)

gvn_str = 'I like "Dhoni" in Indian cricket Team'
print(gvn_str)

Output:

hello this is 'btechgeeks'
I like "Dhoni" in Indian cricket Team

Single vs Double Quotes in Python:

                    Single Quotes             Double Quotes
Single quotes are Represented with ‘ ’ Double quotes are Represented with ‘ ’
For anything that behaves like an Identifier, use single quotes.In general, we use double quotations for text.
For regular expressions, dict keys, and SQL, single quotes are utilized.The string representation is done with double quotes.
Example:  ‘I like “Dhoni” in Indian cricket Team’Example:  “hello this is ‘btechgeeks'”

In Python, the difference between single and double quotes is not big. It is entirely situational in which we employ single and double quotations.

Python Triple Quotes:

What if you need to utilize strings with both single and double quotes? Python supports the usage of triple quotes for this purpose. A simple example of this is provided below. In addition, instead of being limited to single lines, triple quotes allow you to add multi-line strings to Python variables.

Examples

gvn_str1 = '''Excuse me, "Did you see my mobile?"'''
print(gvn_str1)

gvn_str2 = '''"She look's beautiful", he said.'''
print(gvn_str2)

Output:

Excuse me, "Did you see my mobile?"
"She look's beautiful", he said.

Differences: Single vs Double Quotes in Python Read More »