Remember
pow() computes exponentiation. Its three-argument form can calculate an integer power modulo another integer.
pow() computes exponentiation. Its three-argument form can calculate an integer power modulo another integer.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
number = 3
print(pow(number, 2))
print(pow(number, 2, 5))Top-level scope
3pow() computes exponentiation. Its three-argument form can calculate an integer power modulo another integer.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
number = 3
print(pow(number, 2))
print(pow(number, 2, 5))
|
v
DISPLAYED RESULT
9
4
FINAL BINDINGS
number --> object 1 (int)
object 1: 3Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
number = 3
print(pow(number, 2))
print(pow(number, 2, 5))Top-level scope
3The example has finished. Compare the final output with the values and references above.
9 4
What do you expect this program to print?
number = 3
print(pow(number, 2))
print(pow(number, 2, 5))pow() FunctionThe pow() function in Python returns the value of a number raised to a given power. It can also return the result modulo another number. This makes it very useful in both basic arithmetic and advanced algorithms like cryptography.
pow(base, exponent[, modulus])
base – The number to be raised (required)exponent – The power to raise the base to (required)modulus – The number to divide the result by and return remainder (optional)base ** exponent(base ** exponent) % modulusprint(pow(2, 3))
8
print(pow(2, -2))
0.25
print(pow(2, 3, 5))
3
This returns (2**3) % 5 = 8 % 5 = 3.
pow(a, b, c) is more efficient than (a ** b) % cmodulus is provided, all values must be integerspow() with three arguments and passing floats — will raise TypeError** instead of ^ for exponentiation (Python uses ^ as bitwise XOR)In competitive programming and coding interviews, pow(a, b, c) is a fast and safe way to compute large powers under a modulus, avoiding overflow errors.
pow(x, y) returns x**ypow(x, y, z) returns (x**y) % z efficientlyWrite a program to compute the last digit of ab for given input values:
a = int(input("Enter base: "))
b = int(input("Enter exponent: "))
print("Last digit is:", pow(a, b, 10))
Connect what you noticed in the example with the idea below.
pow() computes exponentiation. Its three-argument form can calculate an integer power modulo another integer.
pow(a, b) adds a and b.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.