Home > Blockchain >  square root of a number with display of four decimal numbers Python
square root of a number with display of four decimal numbers Python

Time:09-19

I had a homework in which I had to calculate the square root of the input numbers with the display of four numbers after the decimal point. for example the input is 4(the number of numbers that the user wants to calculate their square root) 1, 2, 19, 100 and their output is 1.0000, 1.4142, 4.3588, 10.0000 I wrote the program below but I got 0. Can you please tell me what is wrong with it?

import math
numberss=[]
sqrtlist=[]
tedad=int(input())
for i in range(tedad):
    addad=float(input())
    numberss.append(addad)
for item in numberss:
    sqrtlist.append(math.sqrt(item))
for sqrrs in sqrtlist:
    print(format(sqrrs,".4f"))

CodePudding user response:

Your code works perfectly. Perhaps you are entering incorrect values into the terminal. Nevertheless, optimisations can be made in your code:

import math

sqrtlist=[]
tedad=int(input())

for i in range(tedad):
    sqrtlist.append(math.sqrt(float(input())))

for sqrrs in sqrtlist:
    print(format(sqrrs,".4f"))

CodePudding user response:

input n numbers separated by space e.g.: 1 2 4 5

inp_nums = list(map(int, input().split())) 
sq_root = []

for num in inp_nums:
    sq_root.append(f'{num ** 0.5:.4f}')
print(sq_root)

result:

['1.0000', '1.4142', '2.0000', '2.2361']

CodePudding user response:

You need to validate the input of the item count as an integer then the individual values as float. You can write a simple function that can handle both cases.

Construct a list of the N input values.

You can then unpack a generator to get the output as required.

def getvalue(prompt, converter):
    while True:
        try:
            return converter(input(prompt))
        except ValueError as e:
            print(e)
# get the item counter
N = getvalue('How many values do you want to enter? ', int)
# build length N list
values = [getvalue('Enter a value: ', float) for _ in range(N)]
# generate the output strings
print(*(f'The square root of {v} is {v**0.5:.4f}' for v in values), sep='\n')

Terminal:

How many values do you want to enter? 4
Enter a value: 1
Enter a value: 2
Enter a value: 19
Enter a value: 100
The square root of 1.0 is 1.0000
The square root of 2.0 is 1.4142
The square root of 19.0 is 4.3589
The square root of 100.0 is 10.0000

CodePudding user response:

It works for me:

import math
numberss=[]
sqrtlist=[]
tedad=int(input("How many:"))
for i in range(tedad):
    addad=float(input("Number please:"))
    numberss.append(addad)
for item in numberss:
    sqrtlist.append(math.sqrt(item))
for sqrrs in sqrtlist:
    print(format(sqrrs,".4f"))


How many:4
Number please:1
Number please:2
Number please:19
Number please:100
1.0000
1.4142
4.3589
10.0000
  • Related