In: Computer Science
Write a Python program to: ask the user to enter two integers: int1 and int2. The program uses the exponential operator to calculate and then print the result when int1 is raised to the int2 power. You also want to calculate the result when int1 is raised to the .5 power; however, you realize that it is not possible to take the square root of a negative number. If the value for int1 that is entered is a negative number, print a message to the user explaining why you cannot complete the task. Otherwise, calculate the square root and print it. Finish the program by printing the values of int1 and int2.
The explanation of the code is given in the comments wherever needed.
PYTHON CODE:
# using try catch to report for wrong input or any other exception raised during the program run.
try:
# getting two integers using List Comprehension
# alternatively you can take input one by one
int1, int2 = [int(int1) for int1 in input("Enter two integers separated by blank space: ").split()]
# getting the result when int1 is raised to the int2 power
expVal = int1**int2
print("{} raised to the {} power = {}".format(int1, int2, expVal))
# checking if int1 is positive
if int1 > 0 :
# calculating the square root of the int1
expSqrt = int1**0.5
# printing the square root of int1
print("Square root of {} = {}".format(int1, expSqrt))
#explicitly checking for negative value as the msg is for negative
#alternatively you can use simple else also
elif int1 < 0:
# explaining why task can not be completed
print("Square root can not be calculated because First number is negative. \nSquare root of a negative number will be a complex number which is beyond the scope of this program.")
# Finishing the program by printing the values of int1 and int2.
print("First Number is {} and Second Number is {}".format(int1,int2))
except:
print("Something went wrong! Please try again...")