Python

Python Itertools.repeat() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools.repeat() Function:

Itertools.repeat() belongs to the class of infinite iterators. In repeat(), we provide the data as well as the number of times the data will be repeated. If we don’t specify a number, it will loop indefinitely. The memory space is not created for each variable in repeat(). Rather, it creates only one variable and then repeats it.

Syntax:

repeat(value, number)

Parameters

value: It is the value that will be printed.

number: If the optional keyword number is specified, it prints the passed value number times; otherwise, it prints the passed value infinite times.

Examples:

Example1:

Input:

Given value = 60
Given number = 5

Output:

The list of given value { 60 } 5 times =  [60, 60, 60, 60, 60]

Example2:

Input:

Given string = "hello"
Given number = 3

Output:

The list of given string { hello } 3 times =  ['hello', 'hello', 'hello']

Itertools.repeat() Function with Examples in Python

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

Approach:

  • Import itertools module using the import keyword.
  • Give the value as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Pass the given value and number as the arguments to the itertools.repeat() function that gets the given value, given number of times and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the value as static input and store it in a variable.
gvn_valu = 60
# Give the number as static input and store it in another variable.
gvn_numb = 5
# Pass the given value and number as the arguments to the itertools.repeat()
# function that gets the given value, given number of times
# and store it in a variable.
rslt = itertools.repeat(gvn_valu, gvn_numb)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The list of given value {", gvn_valu, "}",
      gvn_numb, "times = ", rslt_lst)

Output:

The list of given value { 60 } 5 times =  [60, 60, 60, 60, 60]
For Strings

Approach:

  • Import itertools module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Pass the given string and number as the arguments to the itertools.repeat() function that gets the given string, given number of times and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the string as static input and store it in a variable.
gvn_str = "hello"
# Give the number as static input and store it in another variable.
gvn_numb = 3
# Pass the given string and number as the arguments to the itertools.repeat()
# function that gets the given string, given number of times
# and store it in a variable.
rslt = itertools.repeat(gvn_str, gvn_numb)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The list of given string {", gvn_str, "}",
      gvn_numb, "times = ", rslt_lst)

Output:

The list of given string { hello } 3 times =  ['hello', 'hello', 'hello']

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

Approach:

  • Import itertools module using the import keyword.
  • Give the value as user input using the int(input()) function and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Pass the given value and number as the arguments to the itertools.repeat() function that gets the given value, given number of times and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the value as user input using the int(input()) function and store it in a variable.
gvn_valu = int(input("Enter some random number = "))
# Give the number as user input using the int(input()) function and store it in another variable.
gvn_numb = int(input("Enter some random number = "))
# Pass the given value and number as the arguments to the itertools.repeat()
# function that gets the given value, given number of times
# and store it in a variable.
rslt = itertools.repeat(gvn_valu, gvn_numb)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The list of given value {", gvn_valu, "}",
      gvn_numb, "times = ", rslt_lst)

Output:

Enter some random number = 75
Enter some random number = 7
The list of given value { 75 } 7 times = [75, 75, 75, 75, 75, 75, 75]
For Strings

Approach:

  • Import itertools module using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Pass the given string and number as the arguments to the itertools.repeat() function that gets the given string, given number of times and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Give the number as user input using the int(input()) function and store it in another variable.
gvn_numb = int(input("Enter some random number = "))
# Pass the given string and number as the arguments to the itertools.repeat()
# function that gets the given string, given number of times
# and store it in a variable.
rslt = itertools.repeat(gvn_str, gvn_numb)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The list of given string {", gvn_str, "}",
      gvn_numb, "times = ", rslt_lst)

Output:

Enter some random string = btechgeeks
Enter some random number = 2
The list of given string { btechgeeks } 2 times = ['btechgeeks', 'btechgeeks']

Python Itertools.repeat() Function with Examples Read More »

A Complete Tutorial for Python’s += Operator

In this session, we’ll look at Python’s += operator. Let us see how it works with a few simple examples.

The addition assignment operator is denoted by the operator ‘+=’. It is like a short form to it. It adds two values and stores the result in a variable (left operand).

Addition of Two numbers Using += Operator:

Example1:

gvn_num = 100
print("The given number = ", gvn_num)
gvn_num += 50
print("The given number after addition with 50 = ", gvn_num)

Output:

The given number =  100
The given number after addition with 50 =  150

Example2:

a = 10
b = 20
c = 30
rslt_sum = 0
# Adding a,b,c and storing it in a variable rslt_sum
# The below indicates rslt_sum = rslt_sum+(a+b+c)
rslt_sum += a+b+c
print("The sum of a,b,c = ", rslt_sum)

Output:

The sum of a,b,c =  60

For Strings

The ‘+=’ operator concatenates the given strings. It is used for the concatenation of two or more strings.

Example1:

gvn_fststr = "hello"
gvn_scndstr = "btechgeeks"
print("The given first string = ", gvn_fststr)
print("The given second string = ", gvn_scndstr)
print()
# It concatenates the given first string with the second string and assigns the
# result to the first string
gvn_fststr += gvn_scndstr

print("The given first string after concatenation = ", gvn_fststr)

Output:

The given first string =  hello
The given second string =  btechgeeks

The given first string after concatenation =  hellobtechgeeks

Example2:

gvn_fststr = "hello"
gvn_scndstr = " this is "
gvn_thrdstr = "btechgeeks"
concat_str = ""
# concatenating the given three strings using  '+=' Operator
concat_str += (gvn_fststr+gvn_scndstr+gvn_thrdstr)
print("The concatenation of given three strings = ", concat_str)

Output:

The concatenation of given three strings =  hello this is btechgeeks

The “+=” operator’s Associativity in Python

The ‘+=’ operator’s associativity property is from right to left.

Example1:

a = 3
b = 6
a += b >> 2
print("a =", a)
print("b =", b)

Output:

a = 4
b = 6

Explanation:

We set the starting values of two variables, a and b, to 3 and 6, respectively. In the code, we right shift the value of b by two bits, add the result to variable ‘a’, and put the final result in variable ‘a’.

Therefore the final output is :

a=4 and b=6

Example2:

a = 3
b = 6
# Left shift by 1 bit
a += b << 1
print("a =", a)
print("b =", b)

Output:

a = 15
b = 6

Conclusion

This is about the Python ‘+=’ operator and its numerous implementations.

 

A Complete Tutorial for Python’s += Operator Read More »

Python String format() Method with Examples

String format() Method in Python:

The format() method formats the specified value(s) and inserts them inside the placeholder of the string.

Curly brackets{} are used to define the placeholder. In the Placeholder section, you can learn more about the placeholders.

format() returns the formatted string.

Syntax:

string.format(value1, value2, .......)

Parameters

value1, value2, ……. :

Required. One or more values to be formatted and inserted into the string

The values are either a comma-separated list of values, a key=value list, or a combination of the two.

Any data type can be used for the values.

For Example:

Approach:

  • Apply the placeholder for the cost variable and store it in a variable.
  • Apply the format() function for the above string by passing the cost as some random number and print it.
  • The Exit of the Program.

Below is the implementation:

# Apply the placeholder for the cost variable(static string)and store it in a variable.
gvn_str = "The dress cost is {cost:.2f} Rs."
# Apply the format() function for the above string by passing the cost as some
# random number and print it.
print(gvn_str.format(cost=850))

Output:

The dress cost is 850.00 Rs.

Placeholders

The placeholders can be identified using named indexes such as {cost} numbered indexes such as 0 {0}, or even empty placeholders {}.

For Example:

Approach:

  • Apply the placeholder for the ename and id (static string) and apply the format() function for the given string by passing the ename and id with some random values and print it.
  • This is in named indexes format.
  • Similarly, do the same by numbered indexes format and empty placeholders format.
  • Print the results separately.
  • The Exit of the Program.

Below is the implementation:

# Apply the placeholder for the ename and id (static string) and apply the format()
# function for the given string by passing the ename and id with some random values
# and print it.
# (This is in named indexes format)
gvn_str1 = "The Employee name is {ename}, and his id is {id}".format(
    ename="virat", id=28)
# Similarly, do the same by numbered indexes format and empty placeholders format.
# Print the results separately.
gvn_str2 = "The Employee name is {0}, and his id is {1}".format("virat", 28)
# empty placeholders format
gvn_str3 = "The Employee name is {}, and his id is {}".format("virat", 28)
print(gvn_str1)
print(gvn_str2)
print(gvn_str3)

Output:

The Employee name is virat, and his id is 28
The Employee name is virat, and his id is 28
The Employee name is virat, and his id is 28

Types of Formatting

:<        – The result is aligned left (within the available space)

:>        – The result is aligned right (within the available space)

:^        – The result is centered (within the available space)

:=        – Positions the sign to the far left.

:+        – To indicate whether the outcome is positive or negative, use a plus sign.

:-        – Only use a minus sign for negative values.

:         – Insert an extra space before positive numbers by using a space (and a minus sign before negative numbers)

:,         – As a thousand separator, use a comma.

:_       – As a thousand separator, use an underscore.

:b       –  binary format

:c        – The value is converted into the corresponding Unicode character.

:d         – decimal format

:e         – Scientific notation in lower case e

:E        – Scientific notation in upper case E

:f         – Fix point number format

:F        – Fix point number format, all uppercase (show inf and nan as INF and NAN)

:g         – General format

:G        – Format in General (using an upper case E for scientific notations)

😮        – octal format

😡         -Hexadecimal, lower case

:X          -Hexadecimal, upper case

:n          – format for numbers

:%         – Format in percentages

 

Python String format() Method with Examples Read More »

Python String format_map() Method with Examples

String format_map() Method in Python:

The format_map() method is similar to str. format(**mapping), with the difference that str. format(**mapping) creates a new dictionary, whereas str. format map(mapping) does not.

The format map(mapping) method is similar to str.format(**mapping).

The only distinction is that str.format(**mapping) copies the dict, whereas str.format map(mapping) creates a new dictionary during the method call. If you’re working with a dict subclass, this can come in handy.

Syntax:

string. format_map(mapping)

Parameters

format map() only accepts one argument, mapping (dictionary).

Return Value:

format map() formats and returns the given string.

Examples:

Example1:

Input:

Given dictionary = {'a': 7, 'b': -3}
string format = '{a} {b}'

Output:

7 -3

Example2:

Input:

Given dictionary = {'a': 7, 'b': -3, 'c': 10}
string format = '{a} {b} {c}'

Output:

7 -3 10

String format_map() Method with Examples in Python

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

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Pass the given dictionary to the format_map() method to get in the specified format and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {'a': 7, 'b': -3}
# Pass the given dictionary to the format_map() method to get in the specified
# format and store it in another variable.
rslt = '{a} {b}'.format_map(gvn_dict)
# Print the above result.
print(rslt)

Output:

7 -3

Similarly, try for the other example

gvn_dict = {'a': 7, 'b': -3, 'c': 10}
rslt = '{a} {b} {c}'.format_map(gvn_dict)
print(rslt)

Output:

7 -3 10

format_map with dict subclass

Approach:

  • Create a class that accepts the dictionary as an argument or constructor.
  • Create a function by passing the key as a parameter to it.
  • Return the key value from the function.
  • In the main function, pass the class with the argument as ‘a’ coordinate to the format_map() method and print it.
  • Similarly, do the same by passing the ‘b’ coordinate.
  • Do the same for the a and b coordinates and print them.
  • The Exit of the Program.

Below is the implementation:

# Create a class that accepts the dictionary as an argument or constructor.
class Coordinatepoints(dict):
   # Create a function by passing the key as a parameter to it.
    def __missing__(self, key):
        # Return the key value from the function.
        return key


# In the main function, pass the class with the argument as 'a' coordinate to the
# format_map() method and print it.
print('({a}, {b})'.format_map(Coordinatepoints(a='3')))
# Similarly, do the same by passing the 'b' coordinate.
print('({a}, {b})'.format_map(Coordinatepoints(b='7')))
# Do the same for the a and b coordinates and print them.
print('({a}, {b})'.format_map(Coordinatepoints(a='3', b='7')))

Output:

(3, b)
(a, 7)
(3, 7)

Python String format_map() Method with Examples Read More »

Python String isascii() Method with Examples

String isascii() Method in Python:

If all of the characters are ASCII, the isascii() method returns True (a-z). Otherwise returns False.

Syntax: 

string.isascii()

Parameters: This method has no parameters.

Examples:

Example1:

Input:

Given string = "hello@%btechgeeks670"

Output:

True

Example2:

Input:

Given string = 'ß'

Output:

False

String isascii() Method with Examples in Python

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

Approach:

  • Give the string as static input and store it in a variable.
  • Apply isascii() method on the given string where if all of the characters are ASCII, the isascii() method returns True (a-z). Otherwise returns False.
  • Store it in a variable.
  • Print the result after applying isascii() method on 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 = "btechgeeks789@"
# Apply isascii() method on the given string where if all of the characters are
# ASCII, the isascii() method returns True (a-z). Otherwise returns False.
# Store it in a variable.
rslt = gvn_str.isascii()
# Print the result after applying isascii() method on the given string.
print(rslt)

Output:

True

For any non-ASCII characters, the isascii() method returns False.

For Example:

# A letter in German
gvn_str = 'ß'
print(gvn_str.isascii())

gvn_str = 'õ'
print(gvn_str.isascii())

gvn_str = 'Ã…'
print(gvn_str.isascii())

Output:

False
False
False

The isascii() method also verifies ASCII Unicode characters.

For Example:

gvn_str = '/u0000' # Null Unicode
print(gvn_str.isascii())

gvn_str = '/u007f' # DEL Unicode
print(gvn_str.isascii())

gvn_str = '/u0041' # A's Unicode
print(gvn_str.isascii())

gvn_str = '/u0061'  # a's Unicode
print(gvn_str.isascii())

Output:

True
True
True
True

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

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Apply isascii() method on the given string where if all of the characters are ASCII, the isascii() method returns True (a-z). Otherwise returns False.
  • Store it in a variable.
  • Print the result after applying isascii() method on 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 isascii() method on the given string where if all of the characters are
# ASCII, the isascii() method returns True (a-z). Otherwise returns False.
# Store it in a variable.
rslt = gvn_str.isascii()
# Print the result after applying isascii() method on the given string.
print(rslt)

Output:

Enter some random string = hello@%btechgeeks670
True

Python String isascii() Method with Examples Read More »

Python Random shuffle() Method with Examples

Random shuffle() Method in Python:

The shuffle() method reorganizes the order of items in a sequence, such as a list.

Note: Please keep in mind that this method modifies the original list and does not return a new list.

Syntax:

random.shuffle(sequence, function)

Parameters

sequence: This is Required. It could be any sequence.

function: This is Optional. The name of a function that produces a value between 0.0 and 1.0.
If no function is specified, the random() function will be used.

Return Value: This method produces no output.

Examples:

Example1:

Input:

Given List = ["good", "morning", "Btechgeeks"]

Output:

Given list After shuffling : ['Btechgeeks', 'morning', 'good']

Example2:

Input:

Given List = [10, 20, 30, 40]

Output:

Given list After shuffling : [20, 40, 30, 10]

Random shuffle() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the given list to the random.shuffle() method that reorganizes the order of items in a given list.
  • Print the above-given list after shuffling.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in a variable.
gvn_lst = ["good", "morning", "Btechgeeks"]
# Pass the given list to the random.shuffle() method that reorganizes the order of
# items in a given list.
random.shuffle(gvn_lst)
# Print the above-given list after shuffling randomly.
print("Given list After shuffling :", gvn_lst)

Output:

Given list After shuffling : ['Btechgeeks', 'morning', 'good']
Using Function

To weigh or specify the result, you can define your own function.

If the function returns the same number every time, the result will be the same every time

Approach:

  • Import random module using the import keyword.
  • Create a function say demo_function.
  • Inside the function, return 0.1
  • Give the list as static input and store it in a variable.
  • Pass the given list, above function as arguments to the random.shuffle() method in which if the function returns the same number every time, the result will be the same every time.
  • Print the above-given list after shuffling.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random

# Create a function say demo_function.


def demo_function():
    # Inside the function, return 0.1
    return 0.1


# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "btechgeeks"]
# Pass the given list, above function as arguments to the random.shuffle() method
# in which if the function returns the same number every time, the result will be
# the same every time.

random.shuffle(gvn_lst, demo_function)
# Print the above-given list after shuffling.
print(gvn_lst)

Output:

['this', 'is', 'btechgeeks', 'hello']

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

Approach:

  • Import random module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list to the random.shuffle() method that reorganizes the order of items in a given list.
  • Print the above-given list after shuffling.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Pass the given list to the random.shuffle() method that reorganizes the order of
# items in a given list.
random.shuffle(gvn_lst)
# Print the above-given list after shuffling randomly.
print("Given list After shuffling :", gvn_lst)

Output:

Enter some random List Elements separated by spaces = 10 20 30 40
Given list After shuffling : [20, 40, 30, 10]

 

 

Python Random shuffle() Method with Examples Read More »

Python Random randrange() Method with Examples

Random randrange() Method in Python:

The randrange() method selects an element at random from the specified range and returns it.

Syntax:

random.randrange(start, stop, step)

Parameters

start: This is Optional. It is an integer indicating the starting position.
0 is the default.

stop: This is Required. It is an integer indicating the position at which to end.

step: Optional. The incrementation is specified by an integer.
1 is the default.

Examples:

Example1:

Input:

Given start value = 1
Given stop value = 5

Output:

The random number between 1 and 5 = 3

Example2:

Input:

Given start value = 1
Given stop value = 10
Given step size = 2

Output:

The random number between 1 and 10 = 7

Explanation:

Here it prints a random odd number between 1 and 10(includes only start value) 
since the start value is 1 and stepsize is 2

Random randrange() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as static input and store it in a variable.
  • Give the other number(stop value) as static input and store it in another variable.
  • Pass the given start and stop values as the arguments to the random.randrange() method to get a random number between the given start and stop values (includes only start value).
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as static input and store it in a variable.
gvn_strtval = 1
# Give the other number(stop value) as static input and store it in another variable.
gvn_stopval = 5
# Pass the given start and stop values as the arguments to the random.randrange()
# method to get a random number between the given start and stop values.
# (includes only start value)
# Store it in another variable.
rslt = random.randrange(gvn_strtval, gvn_stopval)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

The random number between 1 and 5 = 3
with giving step value

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as static input and store it in a variable.
  • Give the other number(stop value) as static input and store it in another variable.
  • Give the step size as static input and store it in another variable.
  • Pass the given start, stop and step values as the arguments to the random.randrange() method to get a random number between the given start and stop values(includes only start value) with a given step size.
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as static input and store it in a variable.
gvn_strtval = 1
# Give the other number(stop value) as static input and store it in another variable.
gvn_stopval = 10
# Give the step size as static input and store it in another variable.
gvn_step = 2
# Pass the given start,stop and step values as the arguments to the
# random.randrange() method to get a random number between the given start and
# stop values(includes only start value) with a given stepsize.
# Store it in another variable.
rslt = random.randrange(gvn_strtval, gvn_stopval, gvn_step)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

The random number between 1 and 10 = 7

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

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as user input using the int(input()) function and store it in a variable.
  • Give the other number(stop value)  as user input using the int(input()) function and store it in another variable.
  • Pass the given start and stop values as the arguments to the random.randrange() method to get a random number between the given start and stop values (includes only start value).
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as user input using the int(input()) function and store it in a variable.
gvn_strtval = int(input("Enter some random number = "))
# Give the other number(stop value)  as user input using the int(input()) function 
# and store it in another variable.
gvn_stopval = int(input("Enter some random number = "))
# Pass the given start and stop values as the arguments to the random.randrange()
# method to get a random number between the given start and stop values.
# (includes only start value)
# Store it in another variable.
rslt = random.randrange(gvn_strtval, gvn_stopval)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

Enter some random number = 10
Enter some random number = 17
The random number between 10 and 17 = 10
with giving step value

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as user input using the int(input()) function and store it in a variable.
  • Give the other number(stop value)  as user input using the int(input()) function and store it in another variable.
  • Give the step size as static input and store it in another variable.
  • Pass the given start, stop and step values as the arguments to the random.randrange() method to get a random number between the given start and stop values(includes only start value) with a given step size.
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as user input using the int(input()) function and store it in a variable.
gvn_strtval = int(input("Enter some random number = "))
# Give the other number(stop value) as user input using the int(input()) function 
# and store it in another variable.
gvn_stopval = int(input("Enter some random number = "))
# Give the step size as user input using the int(input()) function and store it in another variable.
gvn_step = int(input("Enter some random number = "))
# Pass the given start,stop and step values as the arguments to the
# random.randrange() method to get a random number between the given start and
# stop values(includes only start value) with a given stepsize.
# Store it in another variable.
rslt = random.randrange(gvn_strtval, gvn_stopval, gvn_step)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

Enter some random number = 50
Enter some random number = 60
Enter some random number = 3
The random number between 50 and 60 = 53

Python Random randrange() Method with Examples Read More »

Python Random randint() Method with Examples

Random randint() Method in Python:

The randint() method returns an integer number representing a randomly chosen element from the specified range.

Note: It is to be noted that randint() method is an alias for randrange(start, stop+1).

Syntax:

random.randint(start, stop)

Parameters

start: This is Required. It is an integer indicating the starting position.

stop: This is Required. It is an integer indicating the position at which to end.

Examples:

Example1:

Input:

Given start value = 4
Given stop value = 12

Output:

The random number between 4 and 12 = 12  (includes both 4 and 12)

Example2:

Input:

Given start value = 40
Given stop value = 45

Output:

The random number between 40 and 45 = 42 (includes both 40 and 45)

Random randint() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as static input and store it in a variable.
  • Give the other number(stop value) as static input and store it in another variable.
  • Pass the given start and stop values as the arguments to the random.randint() method to get a random number between the given start and stop values ( both start and stop values are included).
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as static input and store it in a variable.
gvn_strtval = 4
# Give the other number(stop value) as static input and store it in another variable.
gvn_stopval = 12
# Pass the given start and stop values as the arguments to the random.randint()
# method to get a random number between the given start and stop values.
# ( both start and stop values are included).
# Store it in another variable.
rslt = random.randint(gvn_strtval, gvn_stopval)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

The random number between 4 and 12 = 12

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

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as user input using the int(input()) function and store it in a variable.
  • Give the other number(stop value)  as user input using the int(input()) function and store it in another variable.
  • Pass the given start and stop values as the arguments to the random.randint() method to get a random number between the given start and stop values ( both start and stop values are included).
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as user input using the int(input()) function and store it in a variable.
gvn_strtval = int(input("Enter some random number = "))
# Give the other number(stop value)  as user input using the int(input()) function 
# and store it in another variable.
gvn_stopval = int(input("Enter some random number = "))
# Pass the given start and stop values as the arguments to the random.randint()
# method to get a random number between the given start and stop values.
# ( both start and stop values are included).
# Store it in another variable.
rslt = random.randint(gvn_strtval, gvn_stopval)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

Enter some random number = 40
Enter some random number = 45
The random number between 40 and 45 = 42

Python Random randint() Method with Examples Read More »

Python Random choice() Method with Examples

Random choice() Method in Python:

The choice() method selects an element at random from the specified sequence and returns it.

The sequence could be a string, a range, a list, a tuple, or anything else.

Syntax:

random.choice(sequence)

Parameters

sequence: This is Required. It could be a list, a tuple, a range of numbers, and so on.

Examples:

Example1:

Input:

Given list = [4, 7, 9, 0, 1]

Output:

The random element from a given list =  7

Example2:

Input:

Given string = "hello"

Output:

The random character from a given string =  e

Random choice() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the random.choice() method to get a random element from a given list.
  • Store it in another variable.
  • Print a random element from a given list.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in a variable.
gvn_lst = [4, 7, 9, 0, 1]
# Pass the given list as an argument to the random.choice() method to get a
# random element from a given list.
# Store it in another variable.
rslt = random.choice(gvn_lst)
# Print a random element from a given list.
print("The random element from a given list = ", rslt)

Output:

The random element from a given list =  7
For Strings

Approach:

  • Import random module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Pass the given string as an argument to the random.choice() method to get a random character from a given string.
  • Store it in another variable.
  • Print a random character from a given string.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the string as static input and store it in a variable.
gvn_str = "hello"
# Pass the given string as an argument to the random.choice() method to get a
# random character from a given string.
# Store it in another variable.
rslt = random.choice(gvn_str)
# Print a random character from a given string.
print("The random character from a given string = ", rslt)

Output:

The random character from a given string =  e

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

Approach:

  • Import random module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the random.choice() method to get a random element from a given list.
  • Store it in another variable.
  • Print a random element from a given list.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Pass the given list as an argument to the random.choice() method to get a
# random element from a given list.
# Store it in another variable.
rslt = random.choice(gvn_lst)
# Print a random element from a given list.
print("The random element from a given list = ", rslt)

Output:

Enter some random List Elements separated by spaces = 10 20 30 60 80
The random element from a given list = 10
For Strings

Approach:

  • Import random module using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Pass the given string as an argument to the random.choice() method to get a random character from a given string.
  • Store it in another variable.
  • Print a random character from a given string.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Pass the given string as an argument to the random.choice() method to get a
# random character from a given string.
# Store it in another variable.
rslt = random.choice(gvn_str)
# Print a random character from a given string.
print("The random character from a given string = ", rslt)

Output:

Enter some random string = btechgeeks
The random character from a given string = k

Python Random choice() Method with Examples Read More »

Python Random sample() Method with Examples

Random sample() Method in Python:

The sample() method returns a list containing a randomly selected number of items from a sequence.

Note: Please keep in mind that this method does not alter(change) the original sequence.

Syntax:

random.sample(sequence, size)

Parameters

sequence: This is Required. It could be any sequence like a list, a tuple, a range of numbers, and so on.

size: This is Required. The number of items in the returned list.

Examples:

Example1:

Input:

Given list = [4, 7, 9, 0, 1]
Given size = 3

Output:

The 3 random items from a given list =  [1, 9, 7]

Example2:

Input:

Given list = ["hello", "this", "is", "btechgeeks"]
Given size = 2

Output:

The 2 random items from a given list =  ['is', 'btechgeeks']

Random sample() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Give the size of the list to be returned as static input and store it in another variable.
  • Pass the given list, size as the arguments to the random.sample() method to get the given number(size) of random items from a given list
  • Store it in another variable.
  • Print the given number of random items from a given list
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in a variable.
gvn_lst = [4, 7, 9, 0, 1]
# Give the size of the list to be returned as static input and store it in
# another variable.
gvn_size = 3
# Pass the given list, size as the arguments to the random.sample() method to
# get the given number(size) of random items from a given list
# Store it in another variable.
rslt = random.sample(gvn_lst, gvn_size)
# Print the given number of random items from a given list
print("The", gvn_size, "random items from a given list = ", rslt)

Output:

The 3 random items from a given list =  [1, 9, 7]

Note: Similarly, you can also try for strings, to get the given number of random characters from a given string.

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

Approach:

  • Import random module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the size of the list to be returned as user input using the int(input()) function and store it in another variable.
  • Pass the given list, size as the arguments to the random.sample() method to get the given number(size) of random items from a given list
  • Store it in another variable.
  • Print the given number of random items from a given list
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Give the size of the list to be returned as user input using the int(input())
# function and store it in another variable.
gvn_size = int(input("Enter some random number = "))
# Pass the given list, size as the arguments to the random.sample() method to
# get the given number(size) of random items from a given list
# Store it in another variable.
rslt = random.sample(gvn_lst, gvn_size)
# Print the given number of random items from a given list
print("The", gvn_size, "random items from a given list = ", rslt)

Output:

Enter some random List Elements separated by spaces = 23 10 20 30 40 50
Enter some random number = 2
The 2 random items from a given list = [50, 20]

Python Random sample() Method with Examples Read More »