Reputation: 39
I need to take an input of a number greater than 2, and take the square root until the square root is less than two. I need a print statement that includes the count of the times the square root of the number was taken as well as the output. What I have so far is:
import math
input_num = float(input("Enter a number greater than two: "))
while input_num < 2:
input_num = float(input("Enter a number greater than two: "))
else:
sqrt_num = math.sqrt(input_num)
count = 1
while sqrt_num > 2:
sqrt_num = math.sqrt(sqrt_num)
count += 1
print(count, ": ", sqrt_num, sep = '')
With the output of:
Enter a number greater than two: 20
2: 2.114742526881128
3: 1.4542154334489537
I want to include that first iteration of count 1. How do I write a proper loop so it looks like:
Enter a number greater than two: 20
1: 4.47213595499958
2: 2.114742526881128
3: 1.4542154334489537
Upvotes: 1
Views: 4892
Reputation: 328
Its kind of a hacky way to do it, or at least doesn't make as much sense since it makes the variable sqrt_num not the square root, but I would initialize count to 0 and initialize sqrt_num to input_num, like so:
import math
input_num = float(input("Enter a number greater than two: "))
while input_num < 2:
input_num = float(input("Enter a number greater than two: "))
else:
sqrt_num = input_num
count = 0
while sqrt_num > 2:
sqrt_num = math.sqrt(sqrt_num)
count += 1
print(count, ": ", sqrt_num, sep = '')
Upvotes: 3