Introduction
Calculating the square root of a number is a common mathematical operation in programming. This tutorial will guide you through creating a Python program that computes the square root of a given number using Python’s built-in functionality.
Problem Statement
Create a Python program that:
- Takes a number as input.
- Calculates the square root of the number.
- Displays the square root.
Example:
- Input:
16
- Output:
The square root of 16 is 4.0
Solution Steps
- Take Input from the User: Use the
input()
function to get a number from the user. - Convert Input to Numeric Value: Convert the input string to a float using
float()
to handle both integers and decimal numbers. - Calculate the Square Root: Use the
math.sqrt()
function to calculate the square root. - Display the Result: Use the
print()
function to display the square root.
Python Program
# Python Program to Calculate the Square Root
# Author: https://www.javaguides.net/
import math
# Step 1: Take input from the user
num = float(input("Enter a number: "))
# Step 2: Calculate the square root
square_root = math.sqrt(num)
# Step 3: Display the result
print(f"The square root of {num} is {square_root}")
Explanation
Step 1: Take Input from the User
- The
input()
function prompts the user to enter a number. The input is converted to a float usingfloat()
to accommodate both integer and decimal inputs.
Step 2: Calculate the Square Root
- The
math.sqrt()
function from Python’smath
module is used to calculate the square root of the number.
Step 3: Display the Result
- The
print()
function is used to display the square root. Thef-string
format is used to include the original number and its square root directly within the string.
Output Example
Example:
Enter a number: 16
The square root of 16 is 4.0
Example:
Enter a number: 7.5
The square root of 7.5 is 2.7386127875258306
Conclusion
This Python program demonstrates how to calculate the square root of a number using the math.sqrt()
function. It is a useful exercise for beginners to understand how to work with mathematical functions and handle user input in Python.