Python for循环,if语句

Python for循环,if语句,python,for-loop,if-statement,Python,For Loop,If Statement,我对python真的很陌生。我正在努力让它工作 import math number, times = eval(input('Hello please enter the value and number of times to improve the guess followed by comma:')) guess=number/2 sq_math= math.sqrt(number) if times>1: for i in range(2,times+1):

我对python真的很陌生。我正在努力让它工作

import math
number, times = eval(input('Hello please enter the value and number of times to improve the guess followed by comma:'))
guess=number/2
sq_math= math.sqrt(number)
if times>1:
    for i in range(2,times+1):
        guess=(guess+times/guess)/2
        if round(guess,1) == round(sq_math,1):
         break

else:
    pass

print('Newtons method guessed {0}, square root was {1}'.format(guess, sq_math))

那他最好的办法是什么?谢谢你们

您想进行布尔不相等比较
四舍五入(猜测,1)!=四舍五入(sq_math,1)
在一个单独的
if
子句中,就像您对等式比较所做的那样
=

if times>1:
    # break this next line up in to two lines, `for` and `if`
    # for i in range(2,times+1) and round(guess,1) != round(sq_math,1): 
    for i in range(2,times+1):                  # for check
        if round(guess,1) != round(sq_math,1):  # if check
            guess=(guess+times/guess)/2
        if round(guess,1) == round(sq_math,1):
            break
        times-=1 #decrement times until we reach 0
演示:


我认为主要问题是这个公式不正确:

guess = (guess + times / guess) / 2
应该是:

guess = (guess + number / guess) / 2
我认为您的
if
语句和
for
循环没有任何问题。完整的解决方案:

import math

number = int(input('Please enter the value: '))
times = int(input('Please enter the number of times to improve the guess: '))

answer = math.sqrt(number)

guess = number / 2

if times > 1:
    for _ in range(times - 1):
        guess = (guess + number / guess) / 2
        if round(guess, 1) == round(answer, 1):
            break

print("Newton's method guessed {0}; square root was {1}".format(guess, answer))
用法


尽管我相信我真的实现了巴比伦式的求平方根的方法。

您好,欢迎来到Stack Overflow。请回顾并帮助我们解释您希望发生的事情、您遇到的错误以及您不理解的内容。它有什么作用?它应该做什么?有错误吗?你期望什么样的产出?您得到了什么输出?请不要这样做:
number,times=eval(input(…)
“您好,请输入值和次数以改进猜测,后跟逗号:9,56牛顿方法猜测7.483314773547883,平方根为3.0”,出于某种原因,它不想给我正确的答案。对不起,我不知道正确的答案是什么。你想得到的正确答案是什么?你可以在公式中看到。当轮数(guess)为3时,它应该中断并打印guess。看起来,
次数
计数没有变化。尝试在
for
-循环的
末尾添加
时间-=1
(请参见答案中的更新代码),当我尝试
169100
时,我得到的答案相差十倍。许多其他数字也是如此,如100、144等。
import math

number = int(input('Please enter the value: '))
times = int(input('Please enter the number of times to improve the guess: '))

answer = math.sqrt(number)

guess = number / 2

if times > 1:
    for _ in range(times - 1):
        guess = (guess + number / guess) / 2
        if round(guess, 1) == round(answer, 1):
            break

print("Newton's method guessed {0}; square root was {1}".format(guess, answer))
% python3 test.py
Please enter the value: 169
Please enter the number of times to improve the guess: 6
Newton's method guessed 13.001272448567825; square root was 13.0
%