Write a Python Script Using Function to Calculate x Power y

Given two integer numbers X and Y, you have to write a Python function to raise X to the power of Y

This can be done using ** operator to raise x to y in python just use X ** Y

In the mathematics it is denoted by x ^ y (or)
z = xy   
 
 
 
Write a Python Script Using Function to Calculate x Power y

 
 
 
Write a Python Script Using Function to Calculate x Power y


Define a function power(x, y) given two variables as input arguments, x will be the number that will be raised to the power of y. Using return statement and ** operator just calculate x ** y and return it.

def power(x, y):
   return x ** y




In the main function, take a variable named number and ask a user to enter a number. Take another variable named n and again ask the user to enter the value of n as an integer. So that number can be raised to power of n i.e, number ^ n

number = int(input("Enter a Number : "))
n = int(input("Enter the Value of n : "))




Take a result variable and call the function power() and pass the number and n values as the input to the function get the return value store in result variable

Once we get the result use print function to print the x power y.

result = power(number, n)
print(f"{number} ^ {n} = {result}")





Final Program
========================

def power(x, y):
   return x ** y

number = int(input("Enter a Number : "))
n = int(input("Enter the Value of n : "))

result = power(number, n)

print(f"{number} ^ {n} = {result}")




OUTPUT
=============

Enter a Number : 15
Enter the Value of n : 0
15 ^ 0 = 1




OUTPUT
===============

Enter a Number : 23
Enter the Value of n : 1
23 ^ 1 = 23




OUTPUT
=============

Enter a Number : 35
Enter the Value of n : 35
35 ^ 35 = 1102507499354148695951786433413508348166942596435546875
 
 
 
 
 
Calculate x ^ y when y is a floating point value. Example y value is fraction ½  or ⅓ then convert the integer type conversion to floating point values as shown below

def power(x, y):
    return x ** y


number = float(input("Enter a Number : "))
n = float(input("Enter the Value of n : "))

result = power(number, n)

print(f"{number} ^ {n} = {result}")
 
 



OUTPUT
================
Enter a Number : 2
Enter the Value of n : 3
2.0 ^ 3.0 = 8.0
 
 


OUTPUT
===============
Enter a Number : 25
Enter the Value of n : .5
25.0 ^ 0.5 = 5.0
 
 



OUTPUT x ^ (⅓)
==============
Enter a Number : 27
Enter the Value of n : 0.333333
27.0 ^ 0.333333 = 2.9999967041649445

 
 

Conclusion
===============

Try to run the below program by yourself providing random x and y values and validate the result using calculator.



 
 

Post a Comment

0 Comments