Author name: Vikram Chiluka

Python round() Function with Examples

In the previous article, we have discussed Python Program for reversed() Function
round() Function in Python:

The round() function returns a floating-point number with the specified number of decimals that is a rounded version of the specified number.

The function will return the nearest integer if the number of decimals is set to 0.

Syntax:

round(number, digits)

Parameters

number: This is required. It is the number that should be rounded.

digits: This is Optional. When rounding a number, the number of decimals to use(up to how many digits to be rounded after decimal) The default value is 0.

Return Value:

The function round() returns the

If digits is not provided, the nearest integer to the given number is used; otherwise, the number is rounded off to digits.

Examples:

Example1:

Input:

Given number = 10.5678
Given no of digits = 2

Output:

The rounded value of the given number 10.5678 upto 2 digits =  10.57

Example2:

Input:

Given number = 7.8

Output:

The rounded value of the given number 7.8 = 8

Program for round() Function in Python

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

Approach:

  • Give the number as static input and store it in a variable.
  • Give the digits (up to how many digits to be rounded after the decimal)as static input and store it in another variable.
  • Get the rounded value of the given number by passing the given number and given digits as arguments to the round() function.
  • Store it in another variable.
  • Print the rounded value of the given number.
  • The Exit of Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 10.5678
# Give the digits (up to how many digits to be rounded after the decimal)as
# static input and store it in another variable.
gvn_digitss = 2
# Get the rounded value of the given number by passing the given number
# and given digits as arguments to the round() function.
# Store it in another variable.
numbraftr_round = round(gvn_numb, gvn_digitss)
# Print the rounded value of the given number.
print("The rounded value of the given number", gvn_numb,
      "upto", gvn_digitss, "digits = ", numbraftr_round)

Output:

The rounded value of the given number 10.5678 upto 2 digits =  10.57

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

Approach:

  • Give the number as user input using the float(input()) function and store it in a variable.
  • Get the rounded value of the given number by passing the given number as an argument to the round() function.
  • Store it in another variable.
  • Print the rounded value of the given number.
  • The Exit of Program.

Below is the implementation:

# Give the number as user input using the float(input()) function and store it in a variable.
gvn_numb = float(input("Enter some random number = "))
# Get the rounded value of the given number by passing the given number
# as an argument to the round() function.
# Store it in another variable.
numbraftr_round = round(gvn_numb)
# Print the rounded value of the given number.
print("The rounded value of the given number", gvn_numb, "= ", numbraftr_round)

Output:

Enter some random number = 7.8
The rounded value of the given number 7.8 = 8

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python round() Function with Examples Read More »

Python all() Function with Examples

In the previous article, we have discussed Program for Python String swapcase() Function
all() Function in Python:

The function all() returns If all of the items in an iterable are true, it returns True; otherwise, it returns False.

The all() function returns True if the iterable object is empty.

Syntax:

all(iterable)

Parameters

iterable: It may be any iterable object like list, tuple, dictionary, set, etc.

Note: When applied to a dictionary, the all() function determines whether all of the keys are true, rather than the values.

Return value:

The function all() returns:

  • True if all of the elements in an iterable are true.
  • If any element in an iterable is false, then it returns false.

Note:

when 0 is given in the form as string, then it returns true
0 = False
'0' = True
for example: number = '00000'
# output = True

Examples:

Example1:

Input:

Given list =  [0, 1, 2, 3]
Given tuple = (10, 30, -10)
Given dictionary = {0: 'good', 1: 'morning'}

Output:

The result after applying all() function on the given list =  False
The result after applying all() function on the given tuple =  True
The result after applying all() function on the given dictionary =  False

Example2:

Input:

Given list =  ['True', 'True', 'True']
Given tuple = ()
Given dictionary = {3: 'welcome', 2: 'to', 1: 'Python-programs'}

Output:

The result after applying all() function on the given list =  True
The result after applying all() function on the given tuple =  True
The result after applying all() function on the given dictionary =  True

Program for all() Function in Python

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

Approach:

  • Give the list as static input and store it in a variable.
  • Give the tuple as static input and store it in another variable.
  • Give the dictionary as static input and store it in another variable.
  • Apply all() function on the given list that returns true if all of the items in an iterable are true, otherwise, it returns False.
  • Store it in another variable.
  • Apply all() function on the given tuple and store it in another variable.
  • Apply the all() function on the given dictionary and store it in another variable.
  • Print the result after applying all() the function on the given list.
  • Print the result after applying all() the function on the given tuple.
  • Print the result after applying all() the function on the given dictionary.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [0, 1, 2, 3]
# Give the tuple as static input and store it in another variable.
gvn_tupl = (10, 30, -10)
# Give the dictionary as static input and store it in another variable.
gvn_dictnry = {0: 'good', 1: 'morning'}
# Apply all() function on the given list that returns true if all of the
# items in an iterable are true, otherwise, it returns False.
# Store it in another variable.
rslt_lst = all(gvn_lst)
# Apply all() function on the given tuple and store it in another variable.
rslt_tupl = all(gvn_tupl)
# Apply all() function on the given dictionary and store it in another variable.
rslt_dictnry = all(gvn_dictnry)
# Print the result after applying all() function on the given list.
print("The result after applying all() function on the given list = ", rslt_lst)
# Print the result after applying all() function on the given tuple.
print("The result after applying all() function on the given tuple = ", rslt_tupl)
# Print the result after applying all() function on the given dictionary.
print("The result after applying all() function on the given dictionary = ", rslt_dictnry)

Output:

The result after applying all() function on the given list =  False
The result after applying all() function on the given tuple =  True
The result after applying all() function on the given dictionary =  False

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

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the tuple user input using list(),map(),input(),and split() functions and store it in another variable.
  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Apply all() function on the given list that returns true if all of the items in an iterable are true, otherwise, it returns False.
  • Store it in another variable.
  • Apply all() function on the given tuple and store it in another variable.
  • Apply the all() function on the given dictionary and store it in another variable.
  • Print the result after applying all() the function on the given list.
  • Print the result after applying all() the function on the given tuple.
  • Print the result after applying all() the function on the given dictionary.
  • The Exit of the Program.

Below is the implementation:

# Give the list as User input using list(),map(),input(),and split() functions
# and store it in a variable.
gvn_lst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the tuple as User input using list(),map(),input(),and split() functions
# and store it in another variable.
gvn_tupl = tuple(map(int, input(
    'Enter some random Tuple Elements separated by spaces = ').split()))
# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[int(keyy)] = valuee

# Apply all() function on the given list that returns true if all of the
# items in an iterable are true, otherwise, it returns False.
# Store it in another variable.
rslt_lst = all(gvn_lst)
# Apply all() function on the given tuple and store it in another variable.
rslt_tupl = all(gvn_tupl)
# Apply all() function on the given dictionary and store it in another variable.
rslt_dictnry = all(gvn_dict)
# Print the result after applying all() function on the given list.
print("The result after applying all() function on the given list = ", rslt_lst)
# Print the result after applying all() function on the given tuple.
print("The result after applying all() function on the given tuple = ", rslt_tupl)
# Print the result after applying all() function on the given dictionary.
print("The result after applying all() function on the given dictionary = ", rslt_dictnry)

Output:

Enter some random List Elements separated by spaces = 10 25 35 0
Enter some random Tuple Elements separated by spaces = 1 1 1 1
Enter some random number of keys of the dictionary = 3
Enter key and value separated by spaces = 3 welcome
Enter key and value separated by spaces = 2 to
Enter key and value separated by spaces = 1 Python-programs
The result after applying all() function on the given list = False
The result after applying all() function on the given tuple = True
The result after applying all() function on the given dictionary = True

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python all() Function with Examples Read More »

Python ascii() Method with Examples

In the previous article, we have discussed Python Program for all() Function
ascii() Function in Python:

The ascii() function returns an object’s readable version (Strings, Tuples, Lists, etc).

Any non-ascii characters will be replaced with escape characters by the ascii() function.

It uses the \x, \u, or \U escapes to escape non-ASCII characters in the string.

For Example:

ö has been replaced with \xf6n.

Ã¥ has been replaced with \xe5.

Syntax:

ascii(object)

Parameters

object: An object, such as a String, List, Tuple, Dictionary, and so on.

Return Value:

It returns a string containing an object’s printable representation.

For instance, ö is changed to \xf6n and √ is changed to \u221a.

The string’s non-ASCII characters are escaped with \x, \u, or \U.

Examples:

Example1:

Input:

Given first string = "welcome to Pythön-Prögrams"
Given second string = "hello this is btechgeeks"

Output:

The given first string after applying ascii() function =  'welcome to Pyth\xf6n-Pr\xf6grams'
The given second string after applying ascii() function =  'hello this is btechgeeks'

Example2:

Input:

Given first string =  "gööd morning all"
Given second string = "hello this is vikråm chiluka"

Output:

The given first string after applying ascii() function =  'g\xf6\xf6d morning all'
The given second string after applying ascii() function =  'hello this is vikr\xe5m chiluka'

Program for ascii() Function in Python

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

Approach:

  • Give the first string as static input and store it in a variable.
  • Apply ascii() function on the given string that returns an object’s readable version. Any non-ascii characters will be replaced with escape characters by the ascii() function.
  • Store it in another variable.
  • Print the string after applying ascii() function on the given first string .
  • Similarly, do the same for the other string and print the result string.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
gvn_str = "welcome to Pythön-Prögrams"
# Apply ascii() function on the given string that returns an object's
# readable version.Any non-ascii characters will be replaced with escape
# characters by the ascii() function.
# Store it in another variable.
rslt_str1 = ascii(gvn_str)
# Print the string after applying ascii() function on the given first string .
print("The given first string after applying ascii() function = ", rslt_str1)
# similarly do the same for the other string and print the result string.
gvn_str2 = "hello this is btechgeeks"
rslt_str2 = ascii(gvn_str2)
print("The given second string after applying ascii() function = ", rslt_str2)

Output:

The given first string after applying ascii() function =  'welcome to Pyth\xf6n-Pr\xf6grams'
The given second string after applying ascii() function =  'hello this is btechgeeks'

For List

Example:

gvn_lst = ["pythön", "vikråm", "welcome"]
rslt_lst = ascii(gvn_lst)
print(rslt_lst)

Output:

['pyth\xf6n', 'vikr\xe5m', 'welcome']

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python ascii() Method with Examples Read More »

Python any() Function with Examples

In the previous article, we have discussed Python Program for ascii() Function
any() Function in Python:

The function any() returns True if any of the items in an iterable are true; otherwise, False.

The any() function returns False if the iterable object is empty.

Syntax:

any(iterable)

Parameters

iterable: It may be any iterable object like list, tuple, dictionary, etc.

Note: When applied to a dictionary, the any() function determines whether any of the keys are true, rather than the values.

Examples:

Example1:

Input:

Given list = []
Given tuple = (1, 2, 0, 0)
Given dictionary = {1: 'hello', 2: 'this is', 0: 'btechgeeks'}

 

Output:

The result after applying any() function on the given list =  False
The result after applying any() function on the given tuple =  True
The result after applying any() function on the given dictionary =  True

Example2:

Input:

Given list =  [0, 1, 0, 1]
Given tuple = (0, 0, 0)
Given dictionary = {0: 'good', 0: 'morning'}

Output:

The result after applying any() function on the given list =  True
The result after applying any() function on the given tuple =  False
The result after applying any() function on the given dictionary =  False

Program for any() Function in Python

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

Approach:

  • Give the list as static input and store it in a variable.
  • Give the tuple as static input and store it in another variable.
  • Give the dictionary as static input and store it in another variable.
  • Apply any() function on the given list that returns True if any of the items in an iterable are true; otherwise, False.
  • Store it in another variable.
  • Apply any() function on the given tuple and store it in another variable.
  • Apply any() function on the given dictionary and store it in another variable.
  • Print the result after applying any() function on the given list.
  • Print the result after applying any() function on the given tuple.
  • Print the result after applying any() function on the given dictionary.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = []
# Give the tuple as static input and store it in another variable.
gvn_tupl = (1, 2, 0, 0)
# Give the dictionary as static input and store it in another variable.
gvn_dictnry = {1: 'hello', 2: 'this is', 0: 'btechgeeks'}
# Apply any() function on the given list that returns True if any of the items
# in an iterable are true; otherwise, False.
# Store it in another variable.
rslt_lst = any(gvn_lst)
# Apply any() function on the given tuple and store it in another variable.
rslt_tupl = any(gvn_tupl)
# Apply any() function on the given dictionary and store it in another variable.
rslt_dictnry = any(gvn_dictnry)
# Print the result after applying any() function on the given list.
print("The result after applying any() function on the given list = ", rslt_lst)
# Print the result after applying any() function on the given tuple.
print("The result after applying any() function on the given tuple = ", rslt_tupl)
# Print the result after applying any() function on the given dictionary.
print("The result after applying any() function on the given dictionary = ", rslt_dictnry)

Output:

The result after applying any() function on the given list =  False
The result after applying any() function on the given tuple =  True
The result after applying any() function on the given dictionary =  True

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

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the tuple user input using list(),map(),input(),and split() functions and store it in another variable.
  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Apply any() function on the given list that returns True if any of the items in an iterable are true; otherwise, False.
  • Store it in another variable.
  • Apply any() function on the given tuple and store it in another variable.
  • Apply any() function on the given dictionary and store it in another variable.
  • Print the result after applying any() function on the given list.
  • Print the result after applying any() function on the given tuple.
  • Print the result after applying any() function on the given dictionary.
  • The Exit of the Program.

Below is the implementation:

# Give the list as User input using list(),map(),input(),and split() functions
# and store it in a variable.
gvn_lst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the tuple as User input using list(),map(),input(),and split() functions
# and store it in another variable.
gvn_tupl = tuple(map(int, input(
    'Enter some random Tuple Elements separated by spaces = ').split()))
# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[int(keyy)] = valuee

# Apply any() function on the given list that returns True if any of the items
# in an iterable are true; otherwise, False.
# Store it in another variable.
rslt_lst = any(gvn_lst)
# Apply any() function on the given tuple and store it in another variable.
rslt_tupl = any(gvn_tupl)
# Apply any() function on the given dictionary and store it in another variable.
rslt_dictnry = any(gvn_dict)
# Print the result after applying any() function on the given list.
print("The result after applying any() function on the given list = ", rslt_lst)
# Print the result after applying any() function on the given tuple.
print("The result after applying any() function on the given tuple = ", rslt_tupl)
# Print the result after applying any() function on the given dictionary.
print("The result after applying any() function on the given dictionary = ", rslt_dictnry)

Output:

Enter some random List Elements separated by spaces = 0 1 0 1
Enter some random Tuple Elements separated by spaces = 0 0 0
Enter some random number of keys of the dictionary = 2
Enter key and value separated by spaces = 0 good
Enter key and value separated by spaces = 0 value
The result after applying any() function on the given list = True
The result after applying any() function on the given tuple = False
The result after applying any() function on the given dictionary = False

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python any() Function with Examples Read More »

Python abs() Function with Examples

In the previous article, we have discussed Python Program for any() Function
abs() Function in Python:

The abs() function calculates the absolute value of the given number.

If the number is a complex number, the abs() function returns the magnitude of the number.

Syntax:

abs(n)

Parameters

n: This is required. It is a number. It can be an integer, floating number, or complex number.

Return value:

The abs() method returns the absolute value of a number.

  • For integers, the absolute value of the integer is returned.
  • The floating absolute value is returned for floating numbers.
  • The magnitude of the number is returned for complex numbers.

Examples:

Example1:

Input:

Given first number = -10
Given second number = 2+6j

Output:

The absolute value of the given number -10 = 10
The absolute value of the given number (2+6j) = 6.324555320336759

Example2:

Input:

Given first number = -12.55
Given second number = 30

Output:

The absolute value of the given number -12.55 = 12.55
The absolute value of the given number 30 = 30

Program for abs() Function in Python

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

Approach:

  • Give the number as static input and store it in a variable.
  • Apply abs() function to the given number to get the absolute value of the given number.
  • Store it in another variable.
  • Print the absolute value of the given number.
  • Similarly, do the same for the other number and print the result.
  • The Exit of Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb1 = -10
# Apply abs() function to the given number to get the absolute value of
# the given number and store it in another variable.
rslt_charctr1 = abs(gvn_numb1)
# Print the absolute value of the given number.
print("The absolute value of the given number",
      gvn_numb1, "=", rslt_charctr1)
# Similarly, do the same for the other number and print the result.
gvn_numb2 = 2+6j
rslt_charctr2 = abs(gvn_numb2)
print("The absolute value of the given number",
      gvn_numb2, "=", rslt_charctr2)

Output:

The absolute value of the given number -10 = 10
The absolute value of the given number (2+6j) = 6.324555320336759

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

Approach:

  • Give the number as user input using the float(input()) function and store it in a variable.
  • Apply abs() function to the given number to get the absolute value of the given number.
  • Store it in another variable.
  • Print the absolute value of the given number.
  • Similarly, do the same for the other number and print the result.
  • The Exit of Program.

Below is the implementation:

# Give the number as user input using the float(input()) function and store it in a variable.
gvn_numb1 = float(input("Enter some random number = "))
# Apply abs() function to the given number to get the absolute value of
# the given number.
# store it in another variable.
rslt_charctr1 = abs(gvn_numb1)
# Print the absolute value of the given number.
print("The absolute value of the given number",
      gvn_numb1, "=", rslt_charctr1)
# Similarly, do the same for the other number and print the result.
gvn_numb2 = int(input("Enter some random number = "))
rslt_charctr2 = abs(gvn_numb2)
print("The absolute value of the given number",
      gvn_numb2, "=", rslt_charctr2)

Output:

Enter some random number = -12.55
The absolute value of the given number -12.55 = 12.55
Enter some random number = 30
The absolute value of the given number 30 = 30

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python abs() Function with Examples Read More »

Python bool() Function with Examples

In the previous article, we have discussed Python Program for abs() Function
bool() Function in Python:

Using the standard truth testing procedure, the Python bool() function returns or converts a value to a Boolean value, i.e., True or False.

Syntax:

bool([value])

Parameters

In general, the bool() method takes only one parameter (value), to which the standard truth testing procedure can be applied. If no parameters are passed, it returns False by default. As a result, passing a parameter is optional.

Return Value:

bool() function can only return one of two values.

  • If the parameter or value passed is True, it returns True.
  • If the parameter or value passed is False, it returns False.

Here are some examples of when Python’s bool() method returns false. Except for these, all other values are True.

  1. If the value False is passed.
  2. If the value None is used.
  3. If an empty sequence, such as (), [], “, etc., is passed
  4. If any numeric type, such as 0, 0.0, etc., is passed as Zero,
  5. If an empty mapping, such as, is passed.
  6. Objects of Classes with __bool__() or __len()__ methods that return 0 or False

Examples:

Example1:

Input:

Given value = False

Output:

False

Example2:

Input:

Given value = 'btechgeeks'

Output:

True

Program for bool() Function in Python

Using Built-in Functions (Static Input)

Approach:

  • Give the value as False and store it in a variable.
  • Get the Boolean value of the given value using the bool() function and print the result.
  • Give the value as True and store it in another variable.
  • Get the Boolean value of the given value using the bool() function and print the result.
  • Give the two numbers as static input and store them in two separate variables.
  • Check if the given two numbers are equal using the bool() function and print the result.
  • Give the value as None and store it in another variable.
  • Get the Boolean value of the given value using the bool() function and print the result.
  • Take an empty tuple and store it in another variable.
  • Get the Boolean value of the given empty tuple using the bool() function and print the result.
  • Take an empty set and store it in another variable.
  • Get the Boolean value of the given empty set using the bool() function and print the result.
  • Give the floating value as static input and store it in another variable.
  • Get the Boolean value of the given value using the bool() function and print the result.
  • Give the string as static input and store it in another variable.
  • Get the Boolean value of the given string using the bool() function and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the value as False and store it in a variable.
p = False
# Get the Boolean value of the given value using the bool() function
# and print the result.
print(bool(p))
# Give the value as True and store it in another variable.
q = True
# Get the Boolean value of the given value using the bool() function
# and print the result.
print(bool(q))
# Give the two numbers as static input and store them in two separate variables.
a = 4
b = 4
# Check if the given two numbers are equal using the bool() function
# and print the result.
print(bool(a == b))
# Give the value as None and store it in another variable.
s = None
# Get the Boolean value of the given value using the bool() function and
# print the result.
print(bool(s))
# Take an empty tuple and store it in another variable.
t = ()
# Get the Boolean value of the given empty tuple using the bool() function
# and print the result.
print(bool(t))
# Take an empty set and store it in another variable.
v = {}
# Get the Boolean value of the given empty set using the bool() function
# and print the result.
print(bool(v))
# Give the floating value as static input and store it in another variable.
g = 0.0
# Get the Boolean value of the given value using the bool() function
# and print the result.
print(bool(g))
# Give the string as static input and store it in another variable.
d = 'btechgeeks'
# Get the Boolean value of the given string using the bool() function
# and print the result.
print(bool(d))

Output:

False
True
True
False
False
False
False
True

Example for Even or Odd Program using bool() Function

Below is the implementation:

def Even_or_odd(gvn_numb):
    return(bool(gvn_numb % 2 == 0))


gvn_numb = 9
if(Even_or_odd(gvn_numb)):
    print("The given number is Even")
else:
    print("The given number is Odd")

Output:

The given number is Odd

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python bool() Function with Examples Read More »

Python bytes() Function with Examples

In the previous article, we have discussed Python Program for bool() Function
bytes() Function in Python:

The bytes() function returns an object of type bytes.

The bytes() method returns a bytes object, which is an immutable (cannot be changed) sequence of integers ranging from 0 to 256.

It can either convert objects to bytes objects or create an empty bytes object of the specified size.

The distinction between bytes() and bytearray() is that bytes() return an object that cannot be modified, whereas bytearray() returns a modifiable object.

Syntax:

bytes(x, encoding, error)

Parameters

x: When creating the bytes object, this is the source that will be used.

If it is an integer, it will generate an empty bytes object of the specified size.

If it’s a String, make sure to specify the source’s encoding.

encoding(optional): The string’s encoding.

error(optional): Specifies what should happen if the encoding fails.

Return Value:

The bytes() method returns bytes object with the specified size and initialization parameters.

Examples:

Example1:

Input:

Given number = 6

Output:

The result after applying the bytes() method to the given number 6 = b'\x00\x00\x00\x00\x00\x00'

Example2:

Input:

Given string =  "welcome to Python-programs"

Output:

The result after applying the bytes() method to the given string = b'welcome to Python-programs'

Program for bytes() Function in Python

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

1) For Numbers

Approach:

  • Give the number as static input and store it in a variable.
  • Apply bytes() method to the given number that returns a bytes object, which is an immutable (cannot be changed) sequence of integers ranging from 0 to 256.
  • Store it in another variable.
  • Print the result after applying the bytes() method to the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 6
# Apply bytes() method to the given number that returns a bytes object,
# which is an immutable (cannot be changed) sequence of integers ranging
# from 0 to 256.
# Store it in another variable.
rslt = bytes(gvn_numb)
# Print the result after applying the bytes() method to the given number.
print("The result after applying the bytes() method to the given number",
      gvn_numb, "= ", rslt)

Output:

The result after applying the bytes() method to the given number 6 = b'\x00\x00\x00\x00\x00\x00'

2) For Strings

Approach:

  • Give the string as static input and store it in a variable.
  • Apply bytes() method to the given string that returns an immutable bytes object with the specified size and data.
  • Store it in another variable.
  • Print the result after applying the bytes() method to the given string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "welcome to Python-programs"
# Apply bytes() method to the given string that returns an immutable bytes
# object with the specified size and data.
# Store it in another variable.
rslt = bytes(gvn_str, 'utf-8')
# Print the result after applying the bytes() method to the given number.
print("The result after applying the bytes() method to the given string = ", rslt)

Output:

The result after applying the bytes() method to the given string = b'welcome to Python-programs'

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

1) For Numbers

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Apply bytes() method to the given number that returns a bytes object, which is an immutable (cannot be changed) sequence of integers ranging from 0 to 256.
  • Store it in another variable.
  • Print the result after applying the bytes() method to the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Apply bytes() method to the given number that returns a bytes object,
# which is an immutable (cannot be changed) sequence of integers ranging
# from 0 to 256.
# Store it in another variable.
rslt = bytes(gvn_numb)
# Print the result after applying the bytes() method to the given number.
print("The result after applying the bytes() method to the given number",
      gvn_numb, "= ", rslt)

Output:

Enter some random number = 3
The result after applying the bytes() method to the given number 3 = b'\x00\x00\x00'

2) For Strings

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Apply bytes() method to the given string that returns an immutable bytes object with the specified size and data.
  • Store it in another variable.
  • Print the result after applying the bytes() method to the given string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Apply bytes() method to the given string that returns an immutable bytes
# object with the specified size and data.
# Store it in another variable.
rslt = bytes(gvn_str, 'utf-8')
# Print the result after applying the bytes() method to the given number.
print("The result after applying the bytes() method to the given string = ", rslt)

Output:

Enter some random string = hello this is btechgeeks
The result after applying the bytes() method to the given string = b'hello this is btechgeeks'

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python bytes() Function with Examples Read More »

Python compile() Function with Examples

In the previous article, we have discussed Python Program for bytes() Function
compile() Function in Python:

The compile() function returns the specified source as a ready-to-execute code object.

Syntax:

compile(source, filename, mode, flag, dont_inherit, optimize)

Parameters:

source: This is Required. A String, a Bytes object, or an AST object can be used as the source to compile.

filename: Required. The name of the file from which the source was obtained. If the source is not a file, you can type whatever you want.

mode: This is Required. Legal principles:

  • If the source is a single expression, use eval.
  • If the source is a set of statements, use exec.
  • If the source is a single interactive statement, use single

flag: This is Optional. The process of compiling the source code. 0 is the default.

dont_inherit: This is Optional. The process of compiling the source code. False by default

optimize: This is Optional. Defines the compiler’s optimization level. -1 is the default.

Return value:

Python code object is returned by the compile() function.

Examples:

Example1:

Input:

Given code in string = 'p = 4\nq=7\nmult=p*q\nprint("The multiplication result =",mult)'

Output:

The multiplication result = 28

Example2:

Input:

Given code in string = 'p = 25\nq=5\ndivisn=p/q\nprint("The division result =",divisn)'

Output:

The division result = 5.0

Program for compile() Function in Python

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

Approach:

  • Give the Python code as a string that multiplies the given two numbers and store it in a variable.
  • Compile the given code using the compile() function with the parameters as the above string code, codename, and mode of compilation.
  • Print the above result which is the code after compilation.
  • The Exit of the Program.

Below is the implementation:

# Give the Python code as a string that multiplies the given two numbers
# and store it in a variable.
codeIn_gvnstring = 'p = 4\nq=7\nmult=p*q\nprint("The multiplication result =",mult)'
# Compile the given code using the compile() function with the parameters
# as the above string code, codename, and mode of compilation.
code_obejct = compile(codeIn_gvnstring, 'multstring', 'exec')
# Print the above result which is the code after compilation.
exec(code_obejct)

Output:

The multiplication result = 28

Explanation:

In this case, the source is a regular string. multstring is the filename. Furthermore, the exec mode later allows the use of the exec() method.

The compile() method transforms a string into a Python code object. The exec() method is then used to execute the code object.

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python compile() Function with Examples Read More »

Python chr() function with Examples

In the previous article, we have discussed Python Program for compile() Function
chr() Function in Python:

The character that represents the specified unicode is returned by the chr() function.

Syntax:

chr(number)

Parameters

number: It is an integer. A valid Unicode code point is represented by an integer.

The integer has a valid range of 0 to 1,114,111.

Return value:

Returns a character (string) with the integer as its Unicode code point.

If the integer falls outside of the range, a ValueError will be thrown.

Examples:

Example1:

Input:

Given first number = 68
Given second number = 101

Output:

The character that represents the given unicode 68 = D
The character that represents the given unicode 101 = e

Example2:

Input:

Given first number = 99
Given second number = 75

Output:

The character that represents the given unicode 99 = c
The character that represents the given unicode 75 = K

Program for chr() Function in Python

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

Approach:

  • Give the number as static input and store it in a variable.
  • Apply chr() function to the given number and store it in another variable.
  • Print the character that represents the given Unicode.
  • Similarly, do the same for the other number and print the result.
  • The Exit of Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb1 = 68
# Apply chr() function to the given number and store it in another variable.
rslt_charctr1 = chr(gvn_numb1)
# Print the character that represents the given Unicode.
print("The character that represents the given unicode",
      gvn_numb1, "=", rslt_charctr1)
# Similarly, do the same for the other number and print the result.
gvn_numb2 = 101
rslt_charctr2 = chr(gvn_numb2)
print("The character that represents the given unicode",
      gvn_numb2, "=", rslt_charctr2)

Output:

The character that represents the given unicode 68 = D
The character that represents the given unicode 101 = e

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

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Apply chr() function to the given number and store it in another variable.
  • Print the character that represents the given Unicode.
  • Similarly, do the same for the other number and print the result.
  • The Exit of Program.

Below is the implementation:

# Give the number as user input using the int(input()) function 
# and store it in a variable.
gvn_numb1 = int(input("Enter some random number = "))
# Apply chr() function to the given number and store it in another variable.
rslt_charctr1 = chr(gvn_numb1)
# Print the character that represents the given Unicode.
print("The character that represents the given unicode",
      gvn_numb1, "=", rslt_charctr1)
# Similarly, do the same for the other number and print the result.
gvn_numb2 = int(input("Enter some random number = "))
rslt_charctr2 = chr(gvn_numb2)
print("The character that represents the given unicode",
      gvn_numb2, "=", rslt_charctr2)

Output:

Enter some random number = 500
The character that represents the given unicode 500 = Ç´
Enter some random number = 75
The character that represents the given unicode 75 = K

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python chr() function with Examples Read More »

Python String strip() Method Examples

In the previous article, we have discussed Python String rstrip() Method Examples
strip() Method in Python:

The strip() method removes any leading (at the start) and trailing (at the end) characters (space is the default leading character to remove)

Syntax:

string.strip(characters)

Parameters

characters: This is optional. A set of characters that should be removed as leading/trailing characters.

Examples:

Example1:

Input:

Given first string = "!!!!!!!_python-programs_!!!!!"
Given characters = "!"

Output:

The above given first string is : !!!!!!!_python-programs_!!!!!
The given first string after applying strip() function: _python-programs_

Example2:

Input:

Given second string = "^^^^***btechgeeks^^^***"
Given characters = "^*"

Output:

The above given second string is : ^^^^***btechgeeks^^^***
The given second string after applying strip() function: btechgeeks

String strip() Method Examples in Python

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

Approach:

  • Give the first string as static input and store it in a variable.
  • Give the character as static input and store it in another variable.
  • Apply strip() method to the given string for the given character to remove any leading (at the start) and trailing (at the end) characters (space is the default leading character to remove)
  • Store it in another variable.
  • Print the above-given string
  • Print the above-given string after applying the strip() function.
  • Similarly, do the same for other the string without giving the character and print the result string.
  • The Exit of Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
gvn_fststr = "!!!!!!!_python-programs_!!!!!"
# Give the characters as static input and store it in another variable.
gvn_chrctr = "!"
# Apply strip() method to the given string for the given character to remove
# any leading (at the start) and trailing (at the end) characters
# (space is the default leading character to remove)
# Store it in another variable.
rslt_str1 = gvn_fststr.strip(gvn_chrctr)
# Print the above given string
print("The above given first string is :", gvn_fststr)
# Print the above given string after applying strip() function.
print("The given first string after applying strip() function:", rslt_str1)
# Similarly do the same for other string without giving the characters
# and print the result string.
gvn_scndstr = "       good morning      "
rslt_str2 = gvn_scndstr.strip()
print("The above given second string is :", gvn_scndstr)
print("The given second string after applying strip() function:", rslt_str2)

Output:

The above given first string is : !!!!!!!_python-programs_!!!!!
The given first string after applying strip() function: _python-programs_
The above given second string is :        good morning      
The given second string after applying strip() function: good morning

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

Approach:

  • Give the first string as user input using the input() function and store it in a variable.
  • Give the character as user input using the input() function and store it in another variable.
  • Apply strip() method to the given string for the given character to remove any leading (at the start) and trailing (at the end) characters (space is the default leading character to remove)
  • Store it in another variable.
  • Print the above-given string
  • Print the above-given string after applying the strip() function.
  • Similarly, do the same for other the string and print the result string.
  • The Exit of Program.

Below is the implementation:

# Give the first string as user input using the input() function and store it in a variable.
gvn_fststr = input("Enter some random string = ")
# Give the characters as user input using the input() function and store it in another variable.
gvn_chrctr = input("Enter some random characters = ")
# Apply strip() method to the given string for the given character to remove
# any leading (at the start) and trailing (at the end) characters
# (space is the default leading character to remove)
# Store it in another variable.
rslt_str1 = gvn_fststr.strip(gvn_chrctr)
# Print the above given string
print("The above given first string is :", gvn_fststr)
# Print the above given string after applying strip() function.
print("The given first string after applying strip() function:", rslt_str1)
# Similarly do the same for other string and print the result string.
gvn_scndstr = input("Enter some random string = ")
gvn_chrctr2 = input("Enter some random characters = ")
rslt_str2 = gvn_scndstr.strip(gvn_chrctr2)
print("The above given second string is :", gvn_scndstr)
print("The given second string after applying strip() function:", rslt_str2)

Output:

Enter some random string = ^^^^***btechgeeks^^^***
Enter some random characters = ^*
The above given first string is : ^^^^***btechgeeks^^^***
The given first string after applying strip() function: btechgeeks
Enter some random string = hello all ####
Enter some random characters = #
The above given second string is : hello all ####
The given second string after applying strip() function: hello all

Are you facing difficulties in finding all the methods that a string object can call in python? Have a glance at this Python String Method Examples Tutorial & meet such challenges with ease.

Python String strip() Method Examples Read More »