How to end program in python – Python Program for How To End Program

Program for How To End Program

How to end program in python: In the previous article, we have discussed Python Program To Write Inline If Statement
In Python, we can use one of the following methods to exit the program.

  1. sys.exit()
  2. quit()
  3. exit()

All of these functions have nearly identical functionality because they raise the SystemExit exception, which is the reason the Python interpreter exists, and no stack traceback is printed.

When we run a program in Python, we execute every line of code in the file, from top to bottom. Scripts normally terminate when the interpreter reaches the end of the file, but the execution can also be terminated programmatically.

Program for How To End Program in Python

1. sys.exit() Method:

Python how to end program: In Python, use the sys. exit() function to exit the program. To exit the program, use the sys module’s built-in function sys. exit(). The sys. exit() function can be called at any time without fear of causing code corruption.

Syntax:

sys.exit([arg])

The sys. exit() function accepts an optional argument arg, which can be an integer representing the exit or another type of object.

Examples:

Example1:

import sys
gvn_numb = 10
if gvn_numb != 15:
    sys.exit("Number mismatch.Exiting from program")
else:
    print("The given numbers are matched")

Output:

Number mismatch.Exiting from program

Example2:

Input:

import sys
gvn_numb = 15
if gvn_numb != 15:
    sys.exit("Number mismatch.Exiting from program")
else:
    print("The given numbers are matched")

Output:

The given numbers are matched

2.quit() Method:

How to end a program python: Use the quit() function to exit the Python program. quit() is a built-in Python function that raises the SystemExit exception and displays a message.

Syntax:

quit()

Examples:

Example1:

for itr in range(2, 6):
    print(itr*5)
    quit()

Output:

10

Example2:

Input:

for itr in range(1, 12):
    if(itr % 2 == 0):
        print(itr, end=" ")
        quit()

Output:

2

3.exit() Method:

How to end the program in python: In Python, use the exit() function to exit the program. The exit() function in Python is a built-in function that exits the program’s execution loop.

Syntax:

exit()

The exit() function is an alternative to the quit() function, which terminates the program’s execution.

That is for terminating a Python program.

Example1:

for itor in range(10):
    if itor == 5:
        exit()
    print(itor)

Output:

0
1
2
3
4

Example2:

for itor in range(20):
    if itor % 2 != 0 and itor > 8:
        exit()
    print(itor)

Output:

0
1
2
3
4
5
6
7
8

Timedelta seconds – Python Pandas Timedelta.seconds Attribute

Python Pandas Timedelta.seconds Attribute

Timedelta seconds: Timedelta is a subclass of datetime.timedelta, and it performs similarly. It’s Pandas’ version of Python’s datetime.timedelta. In most circumstances, it is interchangeable with it.

Pandas Timedelta.seconds Attribute:

In pandas.Timedelta, the Timedelta.seconds attribute gives the number of seconds.

Syntax:

Timedelta.seconds

Parameters: It has no arguments

Return Value:

The number of seconds value is returned by the Timedelta.seconds attribute.

Pandas Timedelta.seconds Attribute in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random Timestamp in the format(days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) to the Timedelta() function of the pandas module to get the Timedelta object.
  • Store it in a variable
  • Print the above obtained Timedelta object
  • Apply seconds attribute on the above Timedelta object to get the number of seconds in the above Timedelta object.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random Timestamp in the format(days, hours, minutes, seconds,
# milliseconds, microseconds, nanoseconds) to the Timedelta() function of 
# the pandas module to get the Timedelta object.
# Store it in a variable
timedelta_obj = pd.Timedelta('7 days 10:15:08.00000090') 
# Print the above obtained Timedelta object
print("The above obtained Timedelta object:", timedelta_obj) 

# Apply seconds attribute on the above Timedelta object to get the 
# number of seconds in the above Timedelta object
print("The number of seconds in the above Timedelta object:")
print(timedelta_obj.seconds)

Output:

The above obtained Timedelta object: 7 days 10:15:08.000000900
The number of seconds in the above Timedelta object:
36908

Example2

Approach:

  • Import pandas module using the import keyword.
  • Pass some random Timestamp in the format(days, minutes, seconds) to the Timedelta() function of the pandas module to get the Timedelta object.
  • Store it in a variable
  • Print the above obtained Timedelta object.
  • Apply seconds attribute on the above Timedelta object to get the number of seconds in the above Timedelta object.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random Timestamp in the format(days, minutes, seconds) to the Timedelta() 
# function of the pandas module to get the Timedelta object.
# Store it in a variable
timedelta_obj = pd.Timedelta('6 days 30 minutes 15s') 
# Print the above obtained Timedelta object
print("The above obtained Timedelta object:", timedelta_obj) 
print()
# Apply seconds attribute on the above Timedelta object to get the 
# number of seconds in the above Timedelta object
print("The number of seconds in the above Timedelta object:")
print(timedelta_obj.seconds)

Output:

The above obtained Timedelta object: 6 days 00:30:15

The number of seconds in the above Timedelta object:
1815

Example3

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random number and unit as argument to the Timedelta() 
# function of the pandas module to get the Timedelta object.
# Store it in a variable
timedelta_obj = pd.Timedelta(50, unit='s') 
# Print the above obtained Timedelta object
print("The above obtained Timedelta object:", timedelta_obj) 
print()
# Apply seconds attribute on the above Timedelta object to get the 
# number of seconds in the above Timedelta object
print("The number of seconds in the above Timedelta object:")
print(timedelta_obj.seconds)

Output:

The above obtained Timedelta object: 0 days 00:00:50

The number of seconds in the above Timedelta object:
50

Python file writelines – Python File writelines() Method with Examples

file-writelines()-method-with-examples

Files In Python:

Python writelines to file: A file is a piece of data or information stored on a computer’s hard drive. You’re already familiar with a variety of file kinds, including music, video, and text files. Manipulation of these files is trivial with Python. Text files and binary files are the two types of files that are commonly used. Binary files contain binary data that can only be read by a computer, whereas text files include plain text.

For programmers and automation testers, Python file handling (also known as File I/O) is a crucial topic. Working with files is required in order to write to or read data from them.

In addition, if you didn’t know, I/O activities are the most expensive techniques via which software might fail. As a result, when implementing file processing for reporting or any other reason, you should proceed with caution. The construction of a high-performance application or a robust solution for automated software testing can benefit from optimizing a single file activity.

File writelines() Method in Python:

Python file writelines: The writelines() function in Python is used to write a list of strings (multiple strings or items of a list) to a file.

In which the texts will be inserted depending on the file mode and stream position.

“a”: The texts will be added at the current file stream position, which is often at the end of the file by default.

“w”: The file will be emptied before the texts are inserted at the current file stream position, which is 0 by default.

Syntax:

file.writelines(list)

Parameters

list: This is the list of texts or byte objects to be inserted.

Return Value:

This method doesn’t return anything.

File writelines() Method with Examples in Python

Example1

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in append mode. In this case, we’re simply appending/adding the contents into the file.
  • Write some random lines to the file by passing lines in the form of a list as an argument to the writelines() function.
  • Close the given file using the close function.
  • Open the file in read mode. In this case, we’re simply reading the contents of the file.
  • Read the contents of the file using the read() function.
  • The Exit of Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in append mode. In this case, we're simply appending/adding the contents into the file.
gvn_file = open(givenFilename, 'a') 
# Write some random lines to the file by passing lines in the form of list as an
# argument to the writelines() function.
gvn_file.writelines(["good morning btechgeeks\n", "welcome to python coding platform\n"])
# Close the given file using the close function
gvn_file.close()

# Open the file in read mode. In this case, we're simply reading the contents of the file.
gvn_file = open(givenFilename, 'r') 
# Read the contents of the file using the read() function
print(gvn_file.read())

Output:

Hello this is btechgeeks 
good morning btechgeeks
welcome to python coding platform

Original File Content:

Hello this is btechgeeks

File Content after adding two more lines:

Hello this is btechgeeks 
good morning btechgeeks
welcome to python coding platform

Example2: without giving line breaks(\n)

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in append mode. In this case, we're simply appending/adding the contents into the file.
gvn_file = open(givenFilename, 'a') 
# Write some random lines to the file by passing lines in the form of list as an
# argument to the writelines() function.
gvn_file.writelines(["good morning btechgeeks", "welcome to python coding platform"])
# Close the given file using the close function
gvn_file.close()

# Open the file in read mode. In this case, we're simply reading the contents of the file.
gvn_file = open(givenFilename, 'r') 
# Read the contents of the file using the read() function
print(gvn_file.read())

Output:

Hello this is btechgeeks 
good morning btechgeekswelcome to python coding platform

Google Colab Images:

Files and Code:

Python Program to Find Indices of the Non-Zero Elements in the Python list

Program to Find Indices of the Non-Zero Elements in the Python list

nwlist: We’ll look at how to determine the indices of non-zero entries in a Python list. There may be times when we simply need to access the list’s non-zero elements. In such instances, we can apply the following techniques.

Lists:

nwlist: A list is an ordered grouping of values. It can hold a variety of values. A list is a container that may be changed. This means that we can add new values, delete old ones, or change current ones.

A Python list is a mathematical concept that describes a finite sequence. Items or elements in a list are the values in a list. A list can have multiple instances of the same value. Each occurrence is treated as a separate item.

Given a list, the task is to find the indices of non-zero elements in the given list.

Examples:

Example1:

Input:

Given list = [11, 19, 0, 8, 45, 0, 29, 0, 19, 0, 26, 0, 33]

Output:

The non zero elements indices in the given list are =  [0, 1, 3, 4, 6, 8, 10, 12]

Example2:

Input:

Given list = 25 0 7 0 0 0 9 5

Output:

The non zero elements indices in the given list are = [0, 2, 6, 7]

Program to Find Indices of the Non-Zero Elements in the Python list in Python

Below are the ways to find the indices of non-zero elements in the given list.

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Take an empty list and initialize it’s with an empty list using list() and [].
  • Calculate the length of the given list using the len() function.
  • Loop till the length of the given list using the For loop.
  • Check if the element in the given list is equal to 0 or not using the If conditional statement.
  • If it is a non-zero element then append the index to the new list using the append() function.
  • Print the index list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlst = [11, 19, 0, 8, 45, 0, 29, 0, 19, 0, 26, 0, 33]
# Take an empty list and initialize it’s with an empty list using list() and [].
nwlist = []
# Calculate the length of the given list using the len() function.
gvnlstlen = len(gvnlst)
# Loop till the length of the given list using the For loop.
for m in range(gvnlstlen):
    # Check if the element in the given list is equal to 0 or not
    # using the If conditional statement.
    if(gvnlst[m] != 0):
        # If it is non-zero element then append the index to the new list
        # using the append() function.
        nwlist.append(m)
# Print the index list.
print('The non zero elements indices in the given list are = ', nwlist)

Output:

The non zero elements indices in the given list are =  [0, 1, 3, 4, 6, 8, 10, 12]

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take an empty list and initialize it’s with an empty list using list() and [].
  • Calculate the length of the given list using the len() function.
  • Loop till the length of the given list using the For loop.
  • Check if the element in the given list is equal to 0 or not using the If conditional statement.
  • If it is a non-zero element then append the index to the new list using the append() function.
  • Print the index list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Take an empty list and initialize it’s with an empty list using list() and [].
nwlist = []
# Calculate the length of the given list using the len() function.
gvnlstlen = len(gvnlst)
# Loop till the length of the given list using the For loop.
for m in range(gvnlstlen):
    # Check if the element in the given list is equal to 0 or not
    # using the If conditional statement.
    if(gvnlst[m] != 0):
        # If it is non-zero element then append the index to the new list
        # using the append() function.
        nwlist.append(m)
# Print the index list.
print('The non zero elements indices in the given list are = ', nwlist)

Output:

Enter some random List Elements separated by spaces = 25 0 7 0 0 0 9 5
The non zero elements indices in the given list are = [0, 2, 6, 7]

Method #3: Using List Comprehension (Static Input)

The method used in the sample program is another way to find the indices of non-zero elements. This is a concise summary implementation of the preceding algorithm. To transform the list into an iterable, we use the enumerate() method in this method.

Approach:

  • Give the list as static input and store it in a variable.
  • Use the list comprehension and enumerate to find all non-zero elements indices in the given list.
  • Print this indices list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlst = [11, 19, 0, 8, 45, 0, 29, 0, 19, 0, 26, 0, 33]
# Use the list comprehension and enumerate to find all non-zero elements
# indices in the given list.
nwlist = [index for index, listelement in enumerate(
    gvnlst) if listelement != 0]
# Print the index list.
print('The non zero elements indices in the given list are = ', nwlist)

Output:

The non zero elements indices in the given list are =  [0, 1, 3, 4, 6, 8, 10, 12]

Method #4: Using List Comprehension (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Use the list comprehension and enumerate to find all non-zero elements indices in the given list.
  • Print this indices list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Use the list comprehension and enumerate to find all non-zero elements
# indices in the given list.
nwlist = [index for index, listelement in enumerate(
    gvnlst) if listelement != 0]
# Print the index list.
print('The non zero elements indices in the given list are = ', nwlist)

Output:

Enter some random List Elements separated by spaces = 7 9 0 0 6 3 0 0
The non zero elements indices in the given list are = [0, 1, 4, 5]

Related Programs:

Decimal to hex python – Python Program to Convert Decimal to Hexadecimal

Program to Convert Decimal to Hexadecimal

Decimal to hex python: In the previous article, we have discussed Python Program to Convert Hexadecimal To Octal
Given a decimal number and the task is to get the respective hexadecimal number using the while loop.

Examples:

Example1:

Input:

Given decimal number = 30

Output:

The Hexadecimal value of the given decimal number { 30 } is: 
1E

Example2:

Input:

Given decimal number = 60

Output:

The Hexadecimal value of the given decimal number { 60 } is: 
3C

Program to Convert Decimal to Hexadecimal in Python

Below are the ways to convert the given decimal number into hexadecimal :

Method #1: Using While Loop (Static Input)

Approach:

  • Give the decimal number as static input and store it in a variable.
  • Take a variable say ‘k‘ and initialize its value with 0.
  • Take a list of length 50 and initialize all the values to zero using the multiplication operator.
  • Store it in another variable.
  • Loop till the given decimal number is not equal to zero using the while loop.
  • Inside the loop, calculate the value of decimal number modulus 16 to get the remainder and store it in another variable.
  • Check if the above remainder value is less than 10 using the if conditional statement.
  • If the statement is true, then get the character with the ASCII value remainder+48 using the if conditional statement and store it in a variable
  • Initialize the hexadecimal list at the index ‘k’ with the above-calculated character.
  • Increment the value of k by 1 and store it in the same variable k.
  • Else if the statement is false, get the character with the ASCII value remainder+55.
  • Store it in another variable.
  • Increment the value of k by 1 and store it in the same variable k.
  • Divide the given decimal number by 16 and store it in the same variable.
  • Loop in decreasing order from k-1 to 0 with the stepsize of -1 using the for loop.
  • Print the element present at the iterator of the hexadecimal list to get the hexadecimal value of the given decimal number.
  • The Exit of the Program.

Below is the implementation:

# Give the decimal number as static input and store it in a variable.
deciml_num = 30
# Take a variable say 'k' and initialize its value with 0.
k = 0
# Take a list of length 50 and initialize all the values to zero using the multiplication operator. 
# Store it in another variable.
Hexa_deciml = ['0']*50

print(
    "The Hexadecimal value of the given decimal number {", deciml_num, "} is: ")
# Loop till the given decimal number is not equal to zero using the while loop.
while deciml_num != 0:
 # Inside the loop, calculate the value of decimal number modulus 16 to get the remainder
    # and store it in another variable.
    remndr = deciml_num % 16
  # Check if the above remainder value is less than 10 using the if conditional statement.
    if remndr < 10:
       # If the statement is true, then get the character with the ASCII value remainder+48 using
        # the if conditional statement and store it in a variable
        chrvalue = chr(remndr+48)
  # Initialize the hexadecimal list at the index 'k' with the above-calculated character.
        Hexa_deciml[k] = chrvalue
    # Increment the value of k by 1 and store it in the same variable k.
        k += 1

    else:
      # Else if the statement is false, get the character with the ASCII value remainder+55.
        # Store it in another variable.
        Hexa_deciml[k] = chr(remndr+55)
  # Increment the value of k by 1 and store it in the same variable k.
        k += 1
  # Divide the given decimal number by 16 and store it in the same variable.
    deciml_num //= 16
# Loop in decreasing order from k-1 to 0 with the stepsize of -1 using the for loop.
for itr in range(k-1, -1, -1):
  # Print the element present at the iterator value of the hexadecimal list to get the
    # hexadecimal value of the given decimal number.
    print(Hexa_deciml[itr], end="")

Output:

The Hexadecimal value of the given decimal number { 30 } is: 
1E

Method #2: Using While loop (User Input)

Approach:

  • Give the decimal number as user input using the int(input()) function input and store it in a variable.
  • Take a variable say ‘k‘ and initialize its value with 0.
  • Take a list of length 50 and initialize all the values to zero using the multiplication operator.
  • Store it in another variable.
  • Loop till the given decimal number is not equal to zero using the while loop.
  • Inside the loop, calculate the value of decimal number modulus 16 to get the remainder and store it in another variable.
  • Check if the above remainder value is less than 10 using the if conditional statement.
  • If the statement is true, then get the character with the ASCII value remainder+48 using the if conditional statement and store it in a variable
  • Initialize the hexadecimal list at the index ‘k’ with the above-calculated character.
  • Increment the value of k by 1 and store it in the same variable k.
  • Else if the statement is false, get the character with the ASCII value remainder+55.
  • Store it in another variable.
  • Increment the value of k by 1 and store it in the same variable k.
  • Divide the given decimal number by 16 and store it in the same variable.
  • Loop in decreasing order from k-1 to 0 with the stepsize of -1 using the for loop.
  • Print the element present at the iterator of the hexadecimal list to get the hexadecimal value of the given decimal number.
  • The Exit of the Program.

Below is the implementation:

# Give the decimal number as user input using the int(input()) function input and
# store it in a variable.
deciml_num = int(input("Enter some random Number = "))
# Take a variable say 'k' and initialize its value with 0.
k = 0
# Take a list of length 50 and initialize all the values to zero using the multiplication operator. 
# Store it in another variable.
Hexa_deciml = ['0']*50

print(
    "The Hexadecimal value of the given decimal number {", deciml_num, "} is: ")
# Loop till the given decimal number is not equal to zero using the while loop.
while deciml_num != 0:
 # Inside the loop, calculate the value of decimal number modulus 16 to get the remainder
    # and store it in another variable.
    remndr = deciml_num % 16
  # Check if the above remainder value is less than 10 using the if conditional statement.
    if remndr < 10:
       # If the statement is true, then get the character with the ASCII value remainder+48 using
        # the if conditional statement and store it in a variable
        chrvalue = chr(remndr+48)
  # Initialize the hexadecimal list at the index 'k' with the above-calculated character.
        Hexa_deciml[k] = chrvalue
    # Increment the value of k by 1 and store it in the same variable k.
        k += 1

    else:
      # Else if the statement is false, get the character with the ASCII value remainder+55.
        # Store it in another variable.
        Hexa_deciml[k] = chr(remndr+55)
  # Increment the value of k by 1 and store it in the same variable k.
        k += 1
  # Divide the given decimal number by 16 and store it in the same variable.
    deciml_num //= 16
# Loop in decreasing order from k-1 to 0 with the stepsize of -1 using the for loop.
for itr in range(k-1, -1, -1):
  # Print the element present at the iterator value of the hexadecimal list to get the
    # hexadecimal value of the given decimal number.
    print(Hexa_deciml[itr], end="")

Output:

Enter some random Number = 60
The Hexadecimal value of the given decimal number { 60 } is: 
3C

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Linear search algorithm python – Linear Search in Python

Linear Search in Python

Linear search algorithm python: Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Linear Search works in much the same way as we search for a random list of objects.

If we need to find a word on a specific page, we will begin at the top and go through each word one by one before we find the word we are searching for.

Linear Search:

Linear search in python: Linear search is a method for locating elements in a sequence. It’s also known as a sequential scan. It is the most basic searching algorithm since it searches for the desired element sequentially.

It compares each element to the value that we are looking for. If both match, the element is found, and the algorithm returns the index position of the key.

Examples:

Input:

given_elements =[2, 7, 3, 4, 9, 15]   key= 9

Output:

Element 9 is found at index 4

Linear Search in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Algorithm

  • Begin with the leftmost element of the given list and compare element “key” with each element of the list one by one.
  • Return the index value if “key” matches any of the elements.
  • If “key” does not match any of the elements in list [], return -1 or the element was not found.

2)Implementation

Below is the implementation of linear search:

# function which return index if element is present else return -1
def linearSearch(given_list, key):
    # Traverse the list
    for index in range(len(given_list)):
        # if the element is equal to key then return index
        if(given_list[index] == key):
            return index
    # if no index is returned then the element is not found in list
    # return -1
    return -1


# given_list
given_list = [2, 7, 3, 4, 9, 15]
# given key
key = 9
# passing the given_list and key to linearSearch function
res = linearSearch(given_list, key)
# if result is equal to -1 then element is not present in list
if(res == -1):
    print("Given element(key) is not found in list")
else:
    print("Element", key, "is found at index", res)

Output:

Element 9 is found at index 4

3)Time Complexity

Python linear search: Linear Search is not an efficient algorithm since it goes through each item in the list, so the number of items in the list has a direct effect on the algorithm.

To put it another way, the algorithm has a time complexity of O. (n). This means that if the number of items in the list is increased by a certain amount, the time required to complete the algorithm will also be multiplied by the same amount.
Related Programs:

Python count occurrences of character in string – Count Occurrences of a Single or Multiple Characters in String and Find their Index Positions

Count Occurrences of a Single or Multiple Characters in String and Find their Index Positions

Count occurrences of character in list python: A Python string is a collection of characters surrounded by single, double, or triple quotes. The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.

In this article we are going to count single characters /multiple characters in a given string.

Examples:

1)Count occurrences of single characters in a given string

Input: 

given_string="btechgeeks" character ='e'

Output:

count of  e is : 3

2)Count occurrences of multiple characters in a  given string

Input:

given_string="btechgeeks" character =['e' , 'c' , 's' ]

Output:

count of  e is : 3
count of  c is : 1
count of  s is : 1

Count occurrences of single/multiple characters in a given string and indices of them

Python count occurrences of character in string: There are several methods  some of them are:

Method #1:Using count() function

Find all occurrences of a character in a string python: The count() method in the string class returns the number of times a substring appears in the string. In simple terms, the count() method looks for a substring in a string and returns the number of times it appears.

1)Count occurrence of single character using count() function

Count occurrences of character in string python: We can count the occurrence of single character using count() as given below.

Below is the implementation:

# given string
string = "btechgeeks"
# given character which should be counted
character = 'e'
# counting the number of occurences of given character in the string
charcount = string.count(character)
print("count of ", character, "is :", charcount)

Output:

count of  e is : 3

2)Count occurrence of multiple characters using count() function

  • Traverse the list of characters whose frequency is to be calculated.
  • Using count function print the frequency of respective characters.

Below is the implementation:

# given string
string = "btechgeeks"
# given characters list which should be counted
charlist = ['e', 'c', 's']
# traverse the charlist
for char in charlist:
    # counting the number of occurences of given character in the string
    charcount = string.count(char)
    print("count of ", char, "is :", charcount)

Output:

count of  e is : 3
count of  c is : 1
count of  s is : 1

Method #2:Using Counter() function which is in collections module

Find number of occurrences of a character in a string python: Counter is a set and dict subset. Counter() takes an iterable entity as an argument and stores the elements as keys and the frequency of the elements as a value. So, in collections, if we transfer a string. When you call Counter(), you’ll get a Counter class object with characters as keys and their frequency in a string as values.

Counter() returns a Counter type object (a subclass of dict) with all characters in the string as keys and their occurrence count as values. We’ll use the [] operator to get the occurrence count of the character’s’ from it.

1)Count occurrence of single character using Counter() function

Python count how many times a character appears in a string: Counting the frequency of character using Counter() function

Below is the implementation:

from collections import Counter
# given string
string = "btechgeeks"
# given character which should be counted
character = 'e'
# counting the frequency of all characters using counter() function
freq = Counter(string)
# counting the number of occurences of given character in the string using [] operator
charcount = freq[character]
print("count of ", character, "is :", charcount)

Output:

count of  e is : 3

2)Count occurrence of multiple characters using Counter() function

  • Traverse the list of characters whose frequency is to be calculated.
  • We can count their frequency using [] operator

Below is the implementation:

from collections import Counter
# given string
string = "btechgeeks"
# given characters list which should be counted
charlist = ['e', 'c', 's']
# counting the frequency of all characters using counter() function
freq = Counter(string)
# traverse the charlist
for char in charlist:
    # counting the number of occurences of given character in the string using [] operator
    charcount = freq[char]
    print("count of ", char, "is :", charcount)

Output:

count of  e is : 3
count of  c is : 1
count of  s is : 1

Finding single character index positions in a string

Method #3:Using regex to count and print indices of occurrences of a string

Python count occurrences in string: Build a regex pattern that matches the character to find the index positions of that character in a string. Then iterate through all of the pattern matches in the string, adding their index positions to a list.

Below is the implementation:

import re
# given main string
string = 'Hello this is BTechGeeks'
# given character
char = 'e'
# Make a regex pattern that matches the given character
pattern = re.compile(char)
# Iterate over all the matches of regex pattern
matchiterator = pattern.finditer(string)
# taking empty list
indexlist = []
# initializing count to 0
charcount = 0
for matchobject in matchiterator:
    indexlist.append(matchobject.start())
    charcount = charcount + 1
print("Count of given character ", char, "is :", charcount)
print("indices of given characters :", indexlist)

Output:

Count of given character  e is : 4
indices of given characters : [1, 16, 20, 21]

Related Programs:

Numpy ceil – Python NumPy ceil() Function

Python NumPy ceil() Function

NumPy ceil() Function:

Numpy ceil: The ceil() function of the NumPy module returns the ceiling value of the given input array or data. The ceiling of the scalar x is the smallest integer “i”, such that i >= x.

Syntax:

numpy.ceil(x, out=None)

Parameters

x: This is required. It is an array (array-like) having elements for which the ceiling values are calculated.

out: This is optional. It is the location where the result will be saved. It must have a shape that the inputs broadcast to if it is provided. If None or not given, a newly allocated array is returned.

Return Value: 

NP ceil: The ceiling value of each element of x is returned.

NumPy ceil() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the above given array as an argument to the ceil() function of the numpy module to get the ceiling values of the given array elements
  • Store it in another variable.
  • Print the ceiling values of the given array elements.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([20.3, 5.5, 8.8, 30.076, 12.123])           
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the above given array as an argument to the ceil() function of the 
# numpy module to get the ceiling values of the given array elements
# Store it in another variable.
ceil_vals = np.ceil(gvn_arry)
# Print the ceiling values of the given array elements
print("The ceiling values of the given array elements:")
print(ceil_vals)

Output:

The above given array is:
[20.3  5.5  8.8  30.076  12.123]
The ceiling values of the given array elements:
[21.  6.  9.  31.  13.]

Example2: Negative values are given for the Array

np.ceil: Here, we give the array which includes the elements with negative values.

For example, Let the number given = -1.7

The ceiling value for -1.7 = -1

When we calculate the ceiling value for a given negative number, the larger integer number, like -1.7, will be -1 rather than -2. Because -1 is a higher number than -1.7, and -2 is a smaller number than -1.7

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list of negative values as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the above-given array as an argument to the ceil() function of the numpy module to get the ceiling values of the given array elements with negative values.
  • Store it in another variable.
  • Print the ceiling values of the given array elements.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list of negative values as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([-20.3, -1.5, -2.8, -3, -12.6])           
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the above given array as an argument to the ceil() function of the 
# numpy module to get the ceiling values of the given array elements
# Store it in another variable.
ceil_vals = np.ceil(gvn_arry)
# Print the ceiling values of the given array elements
print("The ceiling values of the given array elements:")
print(ceil_vals)

Output:

The above given array is:
[-20.3 -1.5 -2.8 -3. -12.6]
The ceiling values of the given array elements:
[-20. -1. -2. -3. -12.]

 

Numpy tolist – Python NumPy ndarray.tolist() Function

Python NumPy ndarray.tolist() Function

NumPy ndarray.tolist() Function:

Numpy tolist: The ndarray.tolist() function of the NumPy module converts the ndarray(n-Dimensional arary) to python list(nested).

That means it returns a python list that contains a copy of the array contents.

The data is transformed to the closest built-in Python type that is compatible.

If the array’s dimension is 0, the nested list will not be a list at all, but a normal Python scalar, because the depth of the nested list is 0.

Syntax:

numpy.ndarray.tolist()

Parameters

This function doesn’t accept any parameters

Return value

A Python list containing array elements, which may be nested is returned.

NumPy ndarray.tolist() Function in Python

Example1

Here, the Numpy arrays are transformed to Python lists.

Approach:

  • Import numpy module using the import keyword
  • Pass some random number to the array() function of the Numpy module to create a 0-Dimensional array.
  • Store it in a variable.
  • Create an array(1-Dimensional) of some random range using the arange() function of the numpy module.
  • Store it in another variable.
  • Create an array of some random range and reshape it to some random rows and columns using the reshape() function.
  • Store it in another variable.
  • Here it creates a 2-Dimensional array.
  • Convert the above given 0-Dimensional array to list using the tolist() function
  • Convert the above given 1-Dimensional array to list using the tolist() function
  • Convert the above given 2-Dimensional array to list using the tolist() function
  • Print the above obtained 0-Dimensional list.
  • Print the above obtained 1-Dimensional list.
  • Print the above obtained 2-Dimensional list.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np

# Pass some random number to the array() function of the Numpy module
# to create a 0-Dimensional array.
# Store it in a variable.
gvn_arry0D = np.array(40)
# Create an array(1-Dimensional) of some random range using the arange()
# function of the numpy module.
# Store it in another variable.
gvn_arry1D = np.arange(2, 7)
# Create an array of some random range and reshape it to some random rows 
# and columns using the reshape() function.
# Store it in another variable.
# Here it creates a 2-Dimensional array.
gvn_arry2D = np.arange(1, 5).reshape(2,2)

# Convert the above given 0-Dimensional array to list using the tolist() function 
Lst_0D = gvn_arry0D.tolist()
# Convert the above given 1-Dimensional array to list using the tolist() function
Lst_1D = gvn_arry1D.tolist()
# Convert the above given 2-Dimensional array to list using the tolist() function
Lst_2D = gvn_arry2D.tolist()

# Print the above obtained 0-Dimensional list
print("The above obtained 0-Dimensional list is: ", Lst_0D)
# Print the above obtained 1-Dimensional list
print("The above obtained 1-Dimensional list is:", Lst_1D)
# Print the above obtained 2-Dimensional list
print("The above obtained 2-Dimensional list is: ", Lst_2D)

Output:

The above obtained 0-Dimensional list is: 40
The above obtained 1-Dimensional list is: [2, 3, 4, 5, 6]
The above obtained 2-Dimensional list is: [[1, 2], [3, 4]]

Example2

Approach:

  • Import numpy module using the import keyword
  • Create an array of some random range using the arange() function of the numpy module.
  • Store it in a variable.
  • Here it creates a 1-Dimensional array.
  • Print the given array
  • Print the type of the given array using the type() function
  • Print the type of random element from the given array using the type() function
  • Convert the above given 1-Dimensional array to list using the tolist() function
  • Store it in another variable.
  • Print the above obtained 1-Dimensional list
  • Print the type of the above obtained 1-Dimensional list using the type() function
  • Print the type of random element from the obtained 1-Dimensional list using the type() function.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Create an array of some random range using the arange()
# function of the numpy module.
# Store it in a variable.
# Here it creates a 1-Dimensional array.
gvn_arry1D = np.arange(2, 7)

# Print the given array
print("The given array is:\n", gvn_arry1D)
# Print the type of the given array using the type() function
print("The type of the given array is:\n", type(gvn_arry1D))
# Print the type of random element from the given array using the type() function
print("The type of random element from the given array is:")
print(type(gvn_arry1D[2]))
print()

# Convert the above given 1-Dimensional array to list using the tolist() function
# Store it in another variable.
Lst_1D = gvn_arry1D.tolist()

# Print the above obtained 1-Dimensional list
print("The above obtained 1-Dimensional list is:\n", Lst_1D)
# Print the type of the above obtained 1-Dimensional list using the type() function
print("The type of the above obtained 1-Dimensional list is:")
print(type(Lst_1D))
# Print the type of random element from the obtained 1-Dimensional list
# using the type() function
print("The type of random element from the obtained 1-Dimensional list is:")
print(type(Lst_1D[2]))

Output:

The given array is:
[2 3 4 5 6]
The type of the given array is:
<class 'numpy.ndarray'>
The type of random element from the given array is:
<class 'numpy.int64'>

The above obtained 1-Dimensional list is:
[2, 3, 4, 5, 6]
The type of the above obtained 1-Dimensional list is:
<class 'list'>
The type of random element from the obtained 1-Dimensional list is:
<class 'int'>

Numpy tan – Python NumPy tan() Function

numpy-tan()-function

Numpy Module:

Numpy tan: NumPy is a Python module that is used to work with arrays.

It also has functions for working with linear algebra, the Fourier transform, and matrices.

Travis Oliphant designed NumPy in 2005. It is an open-source project that you are free to use.

NumPy is an abbreviation for Numerical Python.

Uses of NumPy Module:

Numpy tangent: Lists in Python serve the same purpose as arrays, although they are slower to process.

NumPy’s goal is to provide array objects that are up to 50 times faster than ordinary Python lists.

The array object in NumPy is named ndarray, and it comes with a slew of helper methods that make working with ndarray a breeze.

Arrays are often utilized in data science, where speed and resources are critical.

NumPy tan() Function:

np.tan: The NumPy tan() function computes the trigonometric tangent of an angle in radians.

Syntax:

numpy.tan(array, out=None)

Parameters

array: This is required.The items of the array whose tangent values are to be calculated.
out: This is optional. The output array’s shape. It specifies the location where the result will be saved. If given, it must have a shape to which the inputs are broadcast to. If not given or None, a freshly-allocated array is returned.

NumPy tan() Function in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list of angles as an argument to the array() function to create an array. Store it in a variable.
  • Convert the above-given array angles to radians using numpy.pi/180.
  • Store it in another variable.
  • Get the tangent values of the above array angles using the tan() function of numpy module and store it in another variable.
  • Print the tangent values of the above-given array angles.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list of angles as an argument to the array() function to 
# create an array. Store it in a variable.
gvn_arry = np.array([180, 45, 0, 90])
# Convert the above given array angles to radians using numpy.pi/180
# Store it in another variable.
gvn_arry = gvn_arry*np.pi/180
# Get the tangent values of the above array angles using the tan() function of 
# numpy module and store it in another variable.
rslt= np.tan(gvn_arry)
# Print the tangent values of the above given array angles
print("The tangent value of above given array angles = \n", rslt)

Output:

The tangent value of above given array angles = 
[-1.22464680e-16 1.00000000e+00 0.00000000e+00 1.63312394e+16]

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import numpy module using the import keyword.
  • Give the list as user input using the list(),map(),split(),int functions and store it in a variable.
  • Pass the above list as an argument to the array() function to create an array. Store it in a variable.
  • Convert the above-given array angles to radians using numpy.pi/180.
  • Store it in another variable.
  • Get the tangent values of the above array angles using the tan() function of numpy module and store it in another variable.
  • Print the tangent values of the above-given array angles.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Give the list as user input using the list(),map(),split(),int 
# functions and store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Pass the above list as an argument to the array() function to create an array.
# Store it in a variable.
gvn_arr = np.array(gvn_lst)
# Convert the above given array angles to radians using numpy.pi/180
# Store it in another variable.
gvn_arry = gvn_arry*np.pi/180
# Get the tangent values of the above array angles using the tan() function of 
# numpy module and store it in another variable.
rslt= np.tan(gvn_arry)
# Print the tangent values of the above given array angles
print("The tangent value of above given array angles = \n", rslt)

Output:

Enter some random List Elements separated by spaces = 45 120 0 30
The tangent value of above given array angles = 
[0.05488615 0.01370864 0. 0.02742244]