When it is required to check if a given variable is of power 4, a method named ‘check_power_of_4’ is defined that takes an integer as parameter. The modulus operator and the ‘//’ operator is used to check for the same and return True or False depending on the output.
Example
Below is a demonstration of the same
def check_power_of_4(my_val): if (my_val == 0): return False while (my_val != 1): if (my_val % 4 != 0): return False my_val = my_val // 4 return True my_num = 64 print("The number to be checked is : ") print(my_num) if(check_power_of_4(my_num)): print(my_num, 'is a power of 4..') else: print(my_num, 'is not a power of 4..')
Output
The number to be checked is : 64 64 is a power of 4..
Explanation
A method named ‘check_power_of_4’ is defined that takes the number as a parameter.
If this value is 0, False is returned.
If it is not equal to 1, then the modulus operator is used with this integer to check if it returns 0, if not, it returns False.
Otherwise, the value is operated with 4 using the ‘//’ operator.
Outside the method, the number is defined and is displayed on the console.
The method is called by passing this number as a parameter.
The relevant output is displayed on the console.