Python

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 »

Python subprocess Module with Examples

subprocess Module:

Generally, we develop Python code to automate a process or to obtain results without requiring manual intervention via a UI form or any data-related form. But what if we need system-level information for a specific task or functionality? How do we handle system-level scripts in Python?

This is where the Python subprocess module comes into play.

The subprocess module implements several functions for running system-level scripts within the Python environment:

  • subprocess.call()
  • subprocess.run()
  • subprocess.check_output()
  • subprocess.Popen() and communicate() functions

1)subprocess.call():

To use the functions associated with the subprocess module, we must first import it into the Python environment.

The subprocess.call() function executes the command specified as arguments and returns whether the code was successfully performed or not.

Syntax:

subprocess.call(arguments , shell= True)

Example1:

In the following example, we attempt to run “echo btechgeeks” using Python scripting.

Similarly, with the call() function, the first parameter (echo) is treated as the executable command, and the arguments following the first are treated as command-line arguments.

Also, we must provide shell = True in order for the parameters to be interpreted as strings. When False is set, the arguments are interpreted as a path or file paths.

Approach:

  • Import subprocess module using the import keyword.
  • Pass “echo”, some random string, shell = True/False as the arguments to the call() function and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import subprocess module using the import keyword
import subprocess
# Pass "echo", some random string, shell = True/False as the arguments to the call()
# function and store it in a variable.
rslt = subprocess.call(["echo", "btechgeeks"], shell=True)
# Print the above result
print(rslt)

Output:

It returns 0 as the return code, as shown below. Any other value returned by the code indicates that the command execution was unsuccessful.

"btechgeeks" 
0

Example2:

In this example, we used the Python script to run the command “ls -l.”

# Import subprocess module using the import keyword
import subprocess
rslt = subprocess.call(["ls","-l"],shell=True)
print(rslt)

Output:

0
-rw-r--r-- 1 smulani 1049033 Feb 27 10:40 check.py

2)subprocess.run():

As seen above, the call() function simply returns the code of the command executed. It does not enable us in performing a check on the input and check parameters.

For this, we have the subprocess.run() function, which allows us to execute the bash or system script within the python code and returns the command’s return code.

Additionally, it returns the arguments supplied to the function. This allows us to check the inputs to the system scripts.

For Example:

# Import subprocess module using the import keyword
import subprocess
# Pass a "echo", some random string, shell = True/False as the arguments to the run()
# function and store it in a variable.
rslt = subprocess.run(["echo", "btechgeeks"], shell=True)
# Print the above result
print(rslt)

Output:

'btechgeeks'
CompletedProcess(args=['echo', 'btechgeeks'], returncode=0)

3)subprocess.Popen() function:

The subprocess.Popen() function allows us to run child programs as a new process internally. This can also be used to run shell commands from within Python.

Syntax:

subprocess.Popen(arguments, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

stdout: The output returned from the command
stderr: The error returned from the command

Example:

# Import subprocess module using the import keyword
import subprocess
process = subprocess.Popen(
    ['echo', 'btechgeeks'],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print(stdout)

Output:

b'"btechgeeks"\r\n'

We’ve also used the communicate() method here. This function allows us to read and retrieve the input, output, and error data of the script that was executed directly from the process, as shown above.

Python subprocess Module with Examples Read More »

Python Bit Functions on Integer

Bit Functions in Python:

Before we begin with Python bit functions for integers, let us first understand their interconversion.

Conversion of data values enters the picture when we are either automating a manual procedure or working with system-level information.

While dealing with data in various numeric forms such as hexadecimal, numeric, octal, and so on, bit functions play a crucial part in analyzing the bit level data of integers.

Python provides the following collection of bit level methods to assist us evaluate integer data in terms of bit level information and representation:

  • bit_length() function
  • to_bytes() function
  • int.from_bytes() function

Bit Functions on Integer in Python

1)bit_length() function:

int.bit_length() returns the number of bits needed to represent an integer in binary, ignoring the sign and leading zeros.

For example:

Let the Number = 2 

Its binary representation = 0010.

The actual length of its binary representation  = 4

But the int.bit_length() function returns the output = 2

It excludes or ignores the two leading zeroes, it only counts the non-zero places and returns the length as 2.

Hence the output = 2

2) Number = -7

However, because the function ignores the sign value, it handles it as if it were any other positive integer.

Output = 3

1)For Example

Approach:

  • Give the number as static input and store it in a variable.
  • Apply bit_length() function on the given number that returns the number of bits needed to represent an integer in binary, ignoring the sign and leading zeros.
  • Store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 2
# Apply bit_length() function on the given number that returns the number
# of bits needed to represent an integer in binary, ignoring the sign and
# leading zeros.
# Store it in another variable.
rslt_len = gvn_numb.bit_length()
# Print the above result.
print("The result length for given number{", gvn_numb, "} =", rslt_len)

Output:

The result length for given number{ 2 } = 2
# Similarly, do for the other numbers and print the result
gvn_numb = 5
print(gvn_numb.bit_length())

gvn_numb = -7
print(gvn_numb.bit_length())

Output:

3
3

2)to_bytes() function:

Return a byte array representing an integer.

  • When byteorder is set to “big,” the most significant byte is at the start of the byte array.
  • The most important byte is at the end of the byte array if byteorder is set to “little.”

The signed argument checks if the two’s complement is used to represent the integer.

Syntax:

int.to_bytes(length, byteorder, signedorder = False)

Parameter values

length: It is the length of the resulting array.

byteorder: It may be “big” or “little”.

signedorder: When set to True, it uses two’s complement to represent the number as a bytes array.

1)For Example

# This function returns the byte representation of 1024 in big endian machine
# Here, we have expressed the integer value 1024 as a 4-byte array (length)
# with the most significant byte at the beginning of the array.
print((1024).to_bytes(4, byteorder='big'))

Output:

b'\x00\x00\x04\x00'

3)int.from_bytes() function:

This function returns the integer represented by the specified array of bytes.

In other words, the from_bytes() method accepts an array of bytes as an argument, along with the byteorder parameter, and returns the integer value corresponding to it.

Syntax:

int.from_bytes(bytes, byteorder, signed=False)

For Example:

# from_bytes() function Returns a big endian integer value of 'x00x10'.
print(int.from_bytes(b'\x00\x00\x04\x00', byteorder='big'))

Output:

1024

 

Python Bit Functions on Integer Read More »