首页 > 解决方案 > 为什么 Python 不读取下一行(如果)?

问题描述

我写了关于毕达哥拉斯的程序我得到了答案,但是 python 在 (if) 之后没有读取 (break) 。((a+b+c=1000)&(a**2 + b**2 =c**2) )我的程序标题:(特殊毕达哥拉斯三元组),我想找到一个b c存在一个答案。我知道(a=200, b=375, c=425),但是当程序启动时,它永远不会停止并继续。它还键入这三个数字的乘积。

import random as r
def pyth(b,d,c):
    pyth = None
    if b**2+c**2 == d**2 :
        pyth = True
        h=d*c*b
        print(h)
        return pyth
    if b**2+d**2==c**2 :
        pyth= True
        h=d*c*b
        print(h)
        return pyth
    if d**2 + c**2 == b**2:
        pyth =True
        h=d*c*b
        print(h) 
        return pyth
   else:
       pyth = False 
       return 

a = list(range (150,1000))
b=0
c=0
d=0
h = 0
for i  in range(0,10000000):
    b = r.choice(a)
    c = r.choice(a)
    d = 1000-b-c
    e = b+c+d
if e == 1000 :
    pyth(b,d,c)
if pyth == True:
    break
else:
    continue

标签: pythonif-statement

解决方案


不需要pyth变量。您可以只使用return Truereturn False

if语句需要缩进,以便它在循环中。

您需要测试函数调用的值。

你不需要else: continue。除非您中断循环,否则循环会自动继续。continue仅当您想跳过循环体的其余部分并开始下一次迭代时才需要;在身体的末端不需要它。

import random as r

def pyth(b,d,c):
    if b**2+c**2 == d**2 :
        h=d*c*b
        print(h)
        return True
    if b**2+d**2==c**2 :
        h=d*c*b
        print(h)
        return True
    if d**2 + c**2 == b**2:
        h=d*c*b
        print(h) 
        return True
    else:
       return False

a = list(range (150,1000))

for i  in range(0,10000000):
    b = r.choice(a)
    c = r.choice(a)
    d = 1000-b-c
    e = b+c+d
    if e == 1000 and pyth(b,d,c)
        break

推荐阅读