Practical 4: Program to calculate and display the power of a number using formatting characters.
Problem Statement
Write a Python program to calculate and display the power of a number using formatting characters.
The program should:
- Accept a base number and an exponent from the user.
- Compute the result using the exponentiation operator (**).
- Display the result using formatting techniques like format() or f-strings.
Solution Code
# Program to display the power of a number using formatting characters
# Input: Take base and exponent from the user
base = int(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))
# Calculating power
result = base ** exponent
# Output the result using formatting
print(f"The result of {base} raised to the power of {exponent} is {result}")
Output
- The program will take two integer inputs: a base and an exponent.
- It will compute the power using the ** operator.
- The result will be displayed using f-string formatting.
Example output:
Enter the base number: 2
Enter the exponent: 8
The result of 2 raised to the power of 8 is 256
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 3 Practical 4 solution where we have written Python program to calculate and display the power of a number using formatting characters.
- Taking Input from the User:
- The input() function is used to take two integer values from the user: base and exponent.
- The int() function converts the input from string to an integer.
- Calculating the Power:
- The ** operator is used to compute the power (base ** exponent).
- The result is stored in the variable result.
- Displaying the Output Using Formatting:
- The print() function uses f-string formatting (f”{variable}”) to neatly display the output.
- This ensures a more readable and formatted display.
Key Concepts Learned
- Exponentiation Using ** Operator:
- The ** operator is used for power calculations in Python.
- String Formatting Using f-strings:
- The f”{variable}” syntax allows easy formatting of strings with variable values.
- Improved Readability in Output:
- Using formatted strings makes output clearer and more professional.