Author name: Vikram Chiluka

If-Statement

Python: If-Statement

In real life, there are times when we must make choices and decide what to do next based on those decisions. Similar scenarios occur in programming where we must make decisions and then execute the next block of code based on those decisions.

If Statement in Python

1)If statement

The if statement is the simplest decision-making statement. It is used to determine whether or not a specific statement or block of statements will be executed, i.e. if a certain condition is valid, then a block of statements is executed, otherwise not.

Syntax:

if condition:
    statement 1
    statement 2
    statement 3

We don’t have the definition of brackets in Python to indicate the beginning and end of a block. Instead, it represents a block of indentation. After the “if statement,” for example, there are two other sentences with one degree of indent. It denotes the “if” statement’s block field. In Python, this set of statements in a block is known as a suite.

The keyword “if” is often followed by a conditional expression that should evaluate to a bool value, i.e., True or False. If the condition is True, the interpreter executes the statements in the “if” suite, which are the code statements in the if-block.

Python, as we know, uses indentation to define a block. As a result, the block inside an if statement will be found, as seen in the example below.

if condition:
   statement1
statement2

#If the condition is valid, the if block will only consider
# statement1 to be within its block.

2)Examples of if statement

Example -1:

IF statement is true

Below is the implementation:

height = 70
# checking if the height is greater than 100 or not
if (height < 100):
    print("height is less than 100")
else:
    print("height is greater than 100")

Output:

height is less than 100

Example -2:

IF statement is false

Below is the implementation:

height = 120
# checking if the height is greater than 100 or not
if (height < 100):
    print("height is less than 100")
else:
    print("height is greater than 100")

Output:

height is greater than 100

3)If statement with multiple conditions

In all of the preceding instances, we provide a single condition with the if-statement, but we can also provide multiple conditions.

Example -1:

If statement is true

Below is the implementation:

height = 50
# checking if the height is between 10 to 100
if (height > 10 and height < 100):
    print("height is between 10 to 100")
else:
    print("height is greater than 100 or less than 10")

Output:

height is between 10 to 100

Explanation:

The if-statement in this case checks several conditions, and if all of them satisfy and evaluate to True, the interpreter executes the code in the if-block.

Example -2:

IF statement is false

Below is the implementation:

height = 120
# checking if the height is between 10 to 100
if (height > 10 and height < 100):
    print("height is between 10 to 100")
else:
    print("height is greater than 100 or less than 10")

Output:

height is greater than 100 or less than 10

Related Programs:

Python: If-Statement Read More »

How to Find an Element in Tuple by Value

Python : How to Find an Element in Tuple by Value

Tuples are variable types that allow you to store multiple items in a single variable. Tuple is one of Python’s four built-in data types for storing data collections. The other three are List, Set, and Dictionary, each with unique properties and applications. Tuples are collections that are both ordered and immutable.

Given a tuple, the task is to determine whether or not a given element is present in the tuple.

Examples:

Input:

given_tuple =( 3,4,5,6,2) element =2

Output:

The item is found in the tuple

Search an element in Tuple by value

There are several ways to search an element in tuple some of them are:

Method #1:Using for loop

This is a brute force method for completing this task. We iterate through the tuple and check each element to see if it is given element. If the element matches then written true else return false.

Below is the implementation:

# function which returns true if given element is found in tuple
def searchElement(given_tuple, element):
    # using for loop to traverse the tuple
    for value in given_tuple:
        # if the given element is equal to the value then return true
        if(value == element):
            return True
    # if the element is not found in tuple then return False
    return False


# given tuple
given_tuple = (3, 4, 5, 6, 2)
# given element
element = 2
# passing tuple and element to searchElement function
if(searchElement(given_tuple, element)):
    print("The item is found in the tuple")
else:
    print("The specified element does not exist in the tuple")

Output:

The item is found in the tuple

Method #2:Using in operator

Using the in operator is the most Pythonic way to accomplish this task. It is a one-liner that is recommended for this task.

Below is the implementation:

# function which returns true if given element is found in tuple
def searchElement(given_tuple, element):
    #using in operator
    # if the given eleement is present then return true
    if element in given_tuple:
        return True
    else:
        return False


# given tuple
given_tuple = (3, 4, 5, 6, 2)
# given element
element = 2
# passing tuple and element to searchElement function
if(searchElement(given_tuple, element)):
    print("The item is found in the tuple")
else:
    print("The specified element does not exist in the tuple")

Output:

The item is found in the tuple

Method #3:Using not in operator

Another method for searching for an element in a tuple is to use the not in operator.

If the element is not present in the tuple, it returns True otherwise, it returns False.

Below is the implementation:

# function which returns true if given element is found in tuple
def searchElement(given_tuple, element):
    #using in operator
    # if the given eleement is not present then return false
    if element not in given_tuple:
        return False
    else:
        return True


# given tuple
given_tuple = (3, 4, 5, 6, 2)
# given element
element = 2
# passing tuple and element to searchElement function
if(searchElement(given_tuple, element)):
    print("The item is found in the tuple")
else:
    print("The specified element does not exist in the tuple")

Output:

The item is found in the tuple

Method #4:Using count() function

Tuple has another member function count(),

given_tuple.count(element)

It returns the number of occurrences of element in the tuple.

If the count of an element is greater than zero, the element is present in the tuple .otherwise, the element is not present in the tuple.

Below is the implementation:

# function which returns true if given element is found in tuple
def searchElement(given_tuple, element):
    # using count() function to count the element in tuple
    element_count = given_tuple.count(element)
    # if the count is greater than 0 then return True
    if element_count > 0:
        return True
    else:
        return False


# given tuple
given_tuple = (3, 4, 5, 6, 2)
# given element
element = 2
# passing tuple and element to searchElement function
if(searchElement(given_tuple, element)):
    print("The item is found in the tuple")
else:
    print("The specified element does not exist in the tuple")

Output:

The item is found in the tuple

Method #5:Using index function

Sometimes just checking if an element exists in a tuple isn’t enough ,we want to know where it appears for the first time in the tuple. A member function index is provided by Tuple ()
It returns the index of the first occurrence of x in the tuple. In addition, if an element is not found in a tuple, an exception ValueError is thrown.

Below is the implementation:

# given tuple
given_tuple = (3, 4, 5, 6, 2)
# given element
element = 2
try:
    # calculating the element's index
    elem_index = given_tuple.index(element)
    # printing the position
    print("The given element is found at the index", elem_index)
except:
    print("The specified element does not exist in the tuple")

Output:

The item is found in the tuple

Related Programs:

Python : How to Find an Element in Tuple by Value Read More »

How to Create a List of all the Values in a Dictionary

Python : How to Create a List of all the Values in a Dictionary ?

List:

A collection is a set of values that are arranged in a specific order. There could be different kinds of values. A list is a container that can be changed. Existing ones can be added to, deleted from, or changed as a result.

The Python list is a mathematical representation of the concept of a finite sequence. List items or list elements are the names given to the values in a list. A list may contain multiple instances of the same value. Each event is treated as a separate element.

Dictionary:

Dictionaries are Python’s implementation of an associative list, which can be a collection. A dictionary can be defined as a collection of key-value pairs that are kept together. Each key-value pair represents a key and its value.

Given a dictionary, the task is to convert the values of dictionary to list.

Examples:

Input:

dictionary = {'Hello': 400, 'BtechGeeks': 900, 'Platform': 200}

Output:

[400, 900, 200]

Create a List of all the Values in a Dictionary

1)Using list() and values() function

A dictionary class in Python has a function values() that returns an iterable sequence of all dictionary values. The list() function will return a list containing all of the dictionary’s values if we transfer this iterable sequence(dict values) to it.

Below is the implementation:

# given_dictionary 
dictionary = {'Hello': 400, 'BtechGeeks': 900, 'Platform': 200} 
# creating a list from dictionary values 
list_of_values = list(dictionary.values()) 
# print the newly created list 
print(list_of_values)

Output:

[400,900,200]

2)Making a list of duplicate dictionary values

Approach:

  1. Take a two empty lists named dup_values and uniq_values
  2. Traverse the values of the dictionary
  3. If the value is not in uniq_values then append the element to it.
  4. Else append that element to dup_values.
  5. Print the dup_values list

Below is the implementation:

# given_dictionary
dictionary = {'Hello': 200, 'BtechGeeks': 900,
              'Platform': 200, 'online': 400, 'python': 400}
# taking two empty list
uniq_values = []
dup_values = []
# Traverse the values of the dictionary
for value in dictionary.values():
    if value not in uniq_values:
        uniq_values.append(value)
    else:
        dup_values.append(value)

# print the duplicate values
print(dup_values)

Output:

[200, 400]

Related Programs:

Python : How to Create a List of all the Values in a Dictionary ? Read More »

Iterate over Dictionary and Remove items

Python: Iterate over Dictionary and Remove items

Dictionary:

Dictionary is a mutable built-in Python Data Structure. It is conceptually similar to List, Set, and Tuples. It is, however, indexed by keys rather than a sequence of numbers and can be thought of as associative arrays. On a high level, it consists of a key and its associated value. The Dictionary class in Python describes a hash-table implementation.

Given a dictionary , the task is to iterate over the dictionary and remove items based on the given condition.

Examples:

Input:

Condition: Remove all the elements whose value is divisible by 3

dictionary = {'hello': 89, 'this': 51, 'is': 100, 'BTechGeeks': 201}

Output:

{'hello': 89, 'is': 100}

Traverse the Dictionary and Remove items

There are several ways to remove items from the dictionary some of them are:

Method #1:Using del Keyword

We may make a copy of the dictionary and iterate through it, deleting elements from the original dictionary as we go. For example, we have a string and integer dictionary. We want to iterate through this dictionary and delete items whose value is divisible by 3.

Below is the implementation:

# Given dictionary
dictionary = {'hello': 89, 'this': 51, 'is': 100, 'BTechGeeks': 201}
# Traverse the dictionary by making copy of it
for key, value in dict(dictionary).items():
    # if the value of key is divisible by 3 then remove it from original dictionary
    if(value % 3 == 0):
        # if the value is divisible by 3 the remove it from dictionary using del keyword
        del dictionary[key]
# print the dictionary after removing all the elements which satisfies the condition
print(dictionary)

Output:

{'hello': 89, 'is': 100}

Method #2:Using pop()

Similarly to the del keyword, we can make a copy of the original dictionary and iterate through it. We can add a condition to each pair during iteration, and if the condition is met, we can remove the element from the original dictionary. However, instead of using the del keyword, we will use the pop() function to delete elements during iteration.

Below is the implementation:

# Given dictionary
dictionary = {'hello': 89, 'this': 51, 'is': 100, 'BTechGeeks': 201}
# Traverse the dictionary by making copy of it
for key, value in dict(dictionary).items():
    # if the value of key is divisible by 3 then remove it from original dictionary
    if(value % 3 == 0):
        # if the value is divisible by 3 the remove it from dictionary using pop()
        dictionary.pop(key)
# print the dictionary after removing all the elements which satisfies the condition
print(dictionary)

Output:

{'hello': 89, 'is': 100}

Method #3:Using List Comprehension

We may use dictionary comprehension to filter dictionary items based on condition and return the new dictionary to the original reference variable.

Below is the implementation:

# Given dictionary
dictionary = {'hello': 89, 'this': 51, 'is': 100, 'BTechGeeks': 201}
# using list comprehension
dictionary = {key: value for key, value in dictionary.items()
              if value % 3 != 0}
# print the dictionary after removing all the elements which satisfies the condition
print(dictionary)

Output:

{'hello': 89, 'is': 100}

Explanation:

We iterated over all key-value pairs in the dictionary and generated a new dictionary that only included objects whose values were not divisible by 3. The new dictionary was then assigned to the initial reference variable. It gave the impression that we had removed objects from the dictionary whose values were divisible by 3.

 
Related Programs:

Python: Iterate over Dictionary and Remove items Read More »

Find Frequency of Each Character in String and their Indices and Finding Duplicate Characters in a String

Find Frequency of Each Character in String and their Indices and Finding Duplicate Characters in a String

String:

A string is a group of alphabets, words, or other characters. It is a primitive data structure that serves as the foundation for data manipulation. Python has a string class called str. Strings in Python are “immutable,” which means they can’t be modified once they’re formed. Because of the immutability of strings, we generate new strings as we go to represent computed values.

Given  a string, the task is to find frequency of each character in a string .

Examples:

Input:

string = "hello this is btech geeks online learning platform for underguate students"

Output:

Frequency of each character of the string is :
The frequency of character h is = 3
The frequency of character e is = 9
The frequency of character l is = 5
The frequency of character o is = 4
The frequency of character   is = 10
The frequency of character t is = 6
The frequency of character i is = 4
The frequency of character s is = 5
The frequency of character b is = 1
The frequency of character c is = 1
The frequency of character g is = 3
The frequency of character k is = 1
The frequency of character n is = 6
The frequency of character a is = 3
The frequency of character r is = 4
The frequency of character p is = 1
The frequency of character f is = 2
The frequency of character m is = 1
The frequency of character u is = 3
The frequency of character d is = 2

Finding count of Each Character in a String and their Indices and Finding Duplicate Characters in a given String

There are several ways to find frequency of each character in a string some of them are:

1)Using Counter() function  to print frequency of each character in given string

Counter is a subclass of dict and a set. Counter() takes an iterable object as an argument and stores its elements as keys and their frequencies as values. As a result, if we transfer a string in collections. Counter() will then return a Counter class object with all characters in the string as keys and their frequency in the string as values.

Below is the implementation:

# importing Counter function from collections
from collections import Counter
# Given string
string = "hello this is btech geeks online learning platform for underguate students"
# Using counter() function to calculate frequency of each character of the string
freq = Counter(string)
print("Frequency of each character of the string is :")
# Traverse the freq dictionary and print their respective count
for key in freq:
    print("The frequency of character", key, "is =", freq[key])

Output:

Frequency of each character of the string is :
The frequency of character h is = 3
The frequency of character e is = 9
The frequency of character l is = 5
The frequency of character o is = 4
The frequency of character   is = 10
The frequency of character t is = 6
The frequency of character i is = 4
The frequency of character s is = 5
The frequency of character b is = 1
The frequency of character c is = 1
The frequency of character g is = 3
The frequency of character k is = 1
The frequency of character n is = 6
The frequency of character a is = 3
The frequency of character r is = 4
The frequency of character p is = 1
The frequency of character f is = 2
The frequency of character m is = 1
The frequency of character u is = 3
The frequency of character d is = 2

2)Using regex to find frequency and indices of all characters in a string

We will construct a regex pattern to fit all of the alphanumeric characters in the string,

Make a Regex pattern that matches alphanumeric characters.

regex_Pattern = re.compile('[a-zA-Z0-9]')

Iterate over all of the above-mentioned pattern matches in the string using pattern.

finditer() and generate dictionaries of each character’s frequency count and index position in the string.

Below is the implementation:

import re
# Given string
string = "hello this is btech geeks online learning platform for underguate students"
# regex pattern
regex_Pattern = re.compile('[a-zA-Z0-9]')
# Iterate through the string's alphanumeric characters which matches the regex pattern
# While iterating, keep the frequency count of each character in a dictionary updated.
matchiterator = regex_Pattern.finditer(string)
charfrequency = {}
indices = {}
for matchchar in matchiterator:
    charfrequency[matchchar.group()] = charfrequency.get(
        matchchar.group(), 0) + 1
    indices[matchchar.group()] = indices.get(
        matchchar.group(), []) + [matchchar.start()]
print("Frequency and indices of each character in the string is :")
# Traverse the charfrquency dictionary and print their respective count and indices
for key in charfrequency:
    print("The frequency of character", key, "is =",
          charfrequency[key], " ; Indices of occurrence = ", indices[key])

Output:

Frequency and indices of each character in the string is :
The frequency of character h is = 3  ; Indices of occurrence =  [0, 7, 18]
The frequency of character e is = 9  ; Indices of occurrence =  [1, 16, 21, 22, 31, 34, 58, 64, 70]
The frequency of character l is = 5  ; Indices of occurrence =  [2, 3, 28, 33, 43]
The frequency of character o is = 4  ; Indices of occurrence =  [4, 26, 47, 52]
The frequency of character t is = 6  ; Indices of occurrence =  [6, 15, 45, 63, 67, 72]
The frequency of character i is = 4  ; Indices of occurrence =  [8, 11, 29, 38]
The frequency of character s is = 5  ; Indices of occurrence =  [9, 12, 24, 66, 73]
The frequency of character b is = 1  ; Indices of occurrence =  [14]
The frequency of character c is = 1  ; Indices of occurrence =  [17]
The frequency of character g is = 3  ; Indices of occurrence =  [20, 40, 60]
The frequency of character k is = 1  ; Indices of occurrence =  [23]
The frequency of character n is = 6  ; Indices of occurrence =  [27, 30, 37, 39, 56, 71]
The frequency of character a is = 3  ; Indices of occurrence =  [35, 44, 62]
The frequency of character r is = 4  ; Indices of occurrence =  [36, 48, 53, 59]
The frequency of character p is = 1  ; Indices of occurrence =  [42]
The frequency of character f is = 2  ; Indices of occurrence =  [46, 51]
The frequency of character m is = 1  ; Indices of occurrence =  [49]
The frequency of character u is = 3  ; Indices of occurrence =  [55, 61, 68]
The frequency of character d is = 2  ; Indices of occurrence =  [57, 69]

3)Using Counter to find Duplicate characters in the given string

Now, use collections to find all of the duplicate characters in this string. Counter() is used to determine the frequency of of character in a string, and characters with a frequency greater than 1 are considered duplicates.

Below is the implementation:

# importing Counter function from collections
from collections import Counter
# Given string
string = "hello this is btech geeks online learning platform for underguate students"
# Using counter() function to calculate frequency of each character of the string
freq = Counter(string)
print("Printing duplicate characters in the given string :")
# Traverse the freq dictionary and print the duplicate characters
for key in freq:
    # if the freq of character is greater than 1 then it is duplicate character so we print it
    if(freq[key] > 1):
        print(key)

Output:

Printing duplicate characters in the given string :
h
e
l
o
 
t
i
s
g
n
a
r
f
u
d

 
Related Programs:

Find Frequency of Each Character in String and their Indices and Finding Duplicate Characters in a String Read More »

Python Variables

Python – Variables

Python is not a “statically typed” language. We do not need to declare variables or their types before using them. When we first assign a value to a variable, it is generated. A variable is a name that is assigned to a memory location. It is the fundamental storage unit in a program.

In this post, we’ll go over what you need to know about variables in Python.

Variables in Python Language

1)Variable

Variables are simply reserved memory locations for storing values. This means that when you construct a variable, you reserve memory space.

The interpreter allocates memory and specifies what can be stored in reserved memory based on the data type of a variable. As a result, you can store integers, decimals, or characters in variables by assigning various data types to them.

2)Important points about variables

  • In Python we don’t have to give the type of information when defining a variable, unlike the other programming languages (C++ or Java). The variable form is assumed by Python implicitly on the basis of a variable value.
  • During program execution, the value stored in a variable may be modified.
  • A variable is simply the name given to a memory location, all operations performed on the variable have an impact on that memory location.

3)Initializing the value of the variable

There is no clear statement to reserve the memory space for Python variables. When you assign a value to a variable, the declaration occurs automatically. To allocate values to the variables, the same sign (=) is used.

The = operator’s left operand is the variable name and the operand’s right is the value in the variable. The = operator is the variable value.

Examples:

A=100
b="Hello"
c=4.5

4)Memory and reference

A variable in Python resembles a tag or a reference that points to a memory object.

As an example,

k=”BTechGeeks”

‘BTechGeeks’ is an string object in the memory, and k is a reference or tag the indicates that memory object.

5)Modifying the variable value

Let us try this:

p=4.5
p="Cirus"

Initially, p pointed to a float object, but now it points to a string object in memory. The variable’s type also changed; originally, it was a decimal (float), but when we assigned a string object to it, the type of p changed to str, i.e., a string.

If there is an object in memory but no vector pointing to it, the garbage collector can automatically free it. We forced the variable p to point to a string object, as in the preceding example, and then float 4.5 was left in memory with no variable pointing to it. The object was then immediately released by the garbage collector.

6)Assigning one variable with another variable

We can assign the value of one variable with another variable like

p="BtechGeeks"
q=p

Both the p and q variables now point to the same string object, namely, ‘BTechGeeks.’

Below is the implementation:

p = "BTechGeeks"
# assign variable q with p
q = p
# print the values
print("The value of p :", p)
print("The value of q :", q)

Output:

The value of p : BTechGeeks
The value of q : BTechGeeks

7)The following are the rules for creating variables in Python

  • A variable name must begin with a letter or an underscore.
  • A number cannot be the first character in a variable name.
  • Variable names can only contain alphanumeric characters and underscores (A-z, 0-9, and _ ).
  • Case matters when it comes to variable names (flag, Flag and FLAG Aare three different variables).
  • The reserved terms (keywords) are not permitted to be used in naming the variable.

Related Programs:

Python – Variables Read More »

List Comprehension vs Generator Expression Explained with Examples

Python : List Comprehension vs Generator Expression Explained with Examples

Generator Expression:

To build iterators in Python, we can use both standard functions and generators. Generators are written in the same way as regular functions, except we use yield() instead of return() to return a value. It is more effective as an iterator implementation tool. It is simpler and more convenient to implement since it provides element evaluation on demand. Unlike normal functions, which stop when they experience a return statement, generators use a yield statement, which saves the state of the function from the previous call and can be picked up or resumed the next time we call a generator function. Another significant benefit of the generator over a list is that it consumes much less memory.

List Comprehension:

When you want to generate a new list based on the values of an existing list, list comprehension provides a shorter syntax.

List Comprehension vs Generator Expression

1)Use of Generator Expression

Often we only want to work on a few elements, and we only want to work on them one at a time. In such cases, we can avoid storing unnecessary elements in memory by using lists, sets, or tuples.

As an example, suppose we want to measure the sum of all the numbers in the range 1 to 10000 that are divisible by 2 and 3.

i)Using List Comprehension

Below is the implementation:

# Create a list of numbers in the range 1 to 10000 that are divisible by 2 and 3.
numslist = [n for n in range(10000) if n % 2 == 0 and n % 3 == 0]
# Calculate the sum of the list
list_sum = 0
for element in numslist:
    list_sum += element
print('Sum of list elements = ', list_sum)

Output:

Sum of list elements =  8331666

We made a list of numbers, numslist, and then iterated over each variable in the list to compute the count. Creating a list of too many elements and keeping them in memory was wasteful in this case, and it could have been prevented by using Generators.

ii)Using Generator Expression to calculate the sum

Since we just needed the sum, there is no need to make a long list of these numbers and then calculate the sum. The most effective method is to create a Generator for these selected numbers and then iterate over them one by one using the generator object to obtain the sum. This way, we won’t have to hold all of the elements that aren’t required in memory.

Below is the implementation:

def checkNumber():
    # A generator that produces multiples of 2 and 3 in the range 0 to 10000.
    for number in range(10000):
        if number % 2 == 0 and number % 3 == 0:
            yield number


# initializing the numbobj with  the value returned by checkNumber
numObj = checkNumber()
# Calculate the sum of the list
list_sum = 0
for element in numObj:
    list_sum += element
print('Sum using generator expression = ', list_sum)

Output:

Sum using generator expression =  8331666

2)Generator Expression

A generator expression is used in Python to create Generators. In syntax, it appears to be List comprehension, however ( ) are used instead of [].
Let’s use Generator Expression to find the sum of numbers divisible by 2 and 3 in the range 1 to 10000.

Make a Generator expression that yields a Generator entity.

Below is the implementation:

# initializing the numbobj using generator expression
numObj = (n for n in range(10000) if n % 2 == 0 and n % 3 == 0)
# Calculate the sum of the list
list_sum = 0
for element in numObj:
    list_sum += element
print('Sum using generator expression = ', list_sum)

Output:

Sum using generator expression =  8331666

3)Generator Expression vs List Comprehension

Except for the brackets, the syntax of a Generator expression is identical to that of a List Comprehension, but the key distinction between the two is that the latter returns a Generator object rather than a list. We should use Generators when we just want to loop over the items one at a time and avoid having redundant elements in memory, as shown in the preceding examples.
Related Programs:

Python : List Comprehension vs Generator Expression Explained with Examples Read More »

How to use Global Variables in a Function

Python : How to use Global Variables in a Function ?

In this article, we’ll look at the differences between local and global variables, as well as how to access and change both global and local variables with the same name within a function.

Global variables and local variables are the two types of variables.
Global variables have a scope that spans the entire program, while local variables have a scope that is restricted to the role in which they are specified.

Use of Global Variables in a Function

1)Global Variable

In a program, a global variable is a variable specified outside of the subroutine or function. It has a global reach, which means it would be useful for the duration of the program. As a result, unless it is shadowed, it can be accessed within the program by any feature specified within the program.

2)Advantages of Global Variable

  • The global variable can be accessed from any function or module in a program.
  • You only need to declare global variables once outside of the modules.
  • It is suitable for storing “constants” because it lets you maintain continuity.
  • When multiple functions need to access the same data, a global variable comes in handy.

3)Disadvantages of Global Variable

  • If there are so many global variables declared, they will remain in memory until the program is finished. This can result in an Out of Memory error.
  • Any feature has the ability to change data. The value of the global variable can be changed by any expression in the program. In multi-tasking situations, this may lead to unexpected outcomes.
  • If global variables are no longer used as a result of code refactoring, you’ll need to update all of the modules that use them.

4)Local Variable vs Global Variable

A local variable is defined within a function, while a global variable is defined outside of any function or class, i.e. in global space. A global variable may be used in any function, while a local variable has only the scope of the function in which it is specified.

Example:

# declaring global variable
weight = 60

def test():
    # declaring  local variable
    age = 19
    print('weight = ', weight)
    print('age = ', age)

test()

Output:

weight =  60
age =  19

Here, ‘weight’ is a global variable that can be accessed from within function test() too, while ‘age’ is a local variable that can only be accessed from within function test().

5)Global Variables and Local Variables with same name

# declaring global variable
weight = 60

def test():
    # declaring  local variable with same name
    weight = 19

# printing the weight before calling test()
print('weight = ', weight)
test()
# printing the weight after calling test()
print('weight = ', weight)

Output:

weight =  60
weight =  60

Explanation:

In this case, ‘weight’ is a global variable, and the test() function has a local variable of the same name. If both variables have the same name, a function would prefer the local variable over the global variable. As a result, in the preceding code, when we changed the ‘weight’ variable within the function, the change was not reflected outside the function. Since total variable is treated as a local variable within feature test().

6)Use of global Keyword

If your function has a local variable with the same name as a global variable and you want to change the global variable within the function, use the ‘global’ keyword before the variable name at the start of the function.

It will cause the function to refer to the global variable total whenever it is called.

Below is the implementation:

# declaring global variable
weight = 60

def test():
    # within function, refer to global variable 'weight'
    global weight
    if(weight > 50):
        weight = 70

# printing the weight before calling test()
print('weight = ', weight)
test()
# printing the weight after calling test()
print('weight = ', weight)

Output:

weight =  60
weight =  70

As you can see, the changes you made to the global variable total are now noticeable outside of the feature as well.

When the global keyword is used with a variable inside a function, the local variable is hidden.

7)Using globals()

Since the ‘global’ keywords hide the local variable of the same name, there is another way to access both the local and global variables within a function, which is the global() function.
globals() returns a dictionary of elements in the current module, which we can use to access and change global variables without using the ‘global’ keyword.

# declaring global variable
weight = 60

def test():
    # golbal list
    global_list = globals()
    global_list['weight'] = 20
    weight = 30
    print('Local weight = ', weight)

# printing the weight before calling test()
print('weight = ', weight)
test()
# printing the weight after calling test()
print('weight = ', weight)

Output:

weight =  60
Local weight =  30
weight =  20

Explanation:

As you can see, we have a local variable and a global variable with the same name, complete, and we changed both within the feature. Instead of using the keyword ‘global,’ use the dictionary returned by globals() to refer to a global variable. It will not conceal a local variable within the feature.
Related Programs:

Python : How to use Global Variables in a Function ? Read More »

What is a Dictionary in Python and why do we need it

What is a Dictionary in Python and why do we need it

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Dictionary in Python and why do we need it

1)Dictionary in Python

This is a dictionary example that contains cricket names as keys and the highest score as values. Elements are stored as key-value pairs in the dictionary, where each value is mapped to one key. It is also called a hash table or an associative array.

dictionary

There are four elements in the above dictionary, i.e. four key-value pairs.

  1. Devilliers & 176
  2. Virat Kohli & 183
  3. Dhoni & 183
  4. Gayle & 237

2)Use of Dictionary

As a dictionary, it holds the elements in key-value mapping format and uses hashing internally; as a result, we can easily retrieve a value from the dictionary by its key. In the best-case scenario, its complexity is O(1), while in the worst-case scenario, it can be O(n).

3)Creating a new Dictionary

We can create dictionary by two ways i.e two types of syntaxes.

  1. dict()
  2. {}

It will generate an empty dictionary.
Transfer the key-value pairs in curly braces to build a dictionary of objects. A colon will also be used to divide the key and value in each pair (:).

Let us create a sample dictionary and print the key value pairs in it

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# printing the dictionary
print(dictionary)

Output:

{'This': 100, 'is': 200, 'BTechGeeks': 300}

4)The most important things to know about keys in the dictionary

Keys in the dictionary are always unique, and they must be of an immutable data type, such as strings, numbers, or tuples.
This means that once a key-value pair is added to the dictionary, we cannot change the key itself, but we can change the value associated with it.

For example, suppose we make a dictionary with duplicate keys and print its contents.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'This': 300}
# printing the dictionary
print(dictionary)

Output:

{'This': 300, 'is': 200}

5)The most important things to know about values in the dictionary

A dictionary’s values can be of any type.

Let’s make a dictionary where the key is an integer and the value is a list of strings.

Below is the implementation:

# given dictionary
dictionary = {1: ["HELLO", "THIS", 453], 
              2: ["BTECHGEEKS", 345, 87, 4.5], 
              3: ["PYTHON", True, 3.2, 100]}
# printing the dictionary
print(dictionary)

Output:

{1: ['HELLO', 'THIS', 453], 2: ['BTECHGEEKS', 345, 87, 4.5], 3: ['PYTHON', True, 3.2, 100]}

6)Accessing an element in dictionary

Using the [] operator on the dictionary object, we can access a specific item/pair in a dictionary. If we use the dictionary object’s operator [] and pass a key, it will return its value as shown below.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'This': 300}
# printing the element value in dictionary
print(dictionary['is'])

Output:

200

Now when we pass a key which does not exist in the dictionary, a KeyError is returned

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# printing the element value in dictionary
print(dictionary['python'])

Output:

Traceback (most recent call last):
  File "/home/eb2788937138651d15b1bf1915ff16a5.py", line 4, in <module>
    print(dictionary['python'])
KeyError: 'python'

Related Programs:

What is a Dictionary in Python and why do we need it Read More »

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

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

There are several methods  some of them are:

Method #1:Using count() function

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

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

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

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

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:

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