繁体   English   中英

如何修复我的 python 代码中的 if 语句?

[英]How to fix my if statement in my python code?

我正在尝试制作一个程序来计算您的受欢迎程度并基于此,使用算法循环浏览朋友列表并基于此打开 txt 文件,然后计算他们的受欢迎程度,如果它在 10 个受欢迎程度的半径范围内,它们被认为是兼容的。 但是,我的代码不起作用,无论如何我的 if 语句都会返回 true。 但是,在打印流行度时,它说有些在我的范围内,有些不在。 为什么我的代码失败了?

def popularity(G, So, Sm, Sp):
    g = float(G) * 0.3
    so = float(So) * 0.4
    sm = float(Sm) * 0.1
    sp = float(Sp) * 0.2
    return g + so + sm + sp

gfactor = input("What is your G-Factor? ")
social = input("What is your Social Quotient? ")
smartness = input("What is your smartness level? ")
sports = input("What is your sports skill? ")

poplr = popularity(gfactor, social, smartness, sports)
print(str(math.ceil(poplr * float(10))) + "%")
print("Finding friends... ")

for i in friends:
    fs = open(i + ".txt")
    json_str = fs.read(37)
    data = json.loads(json_str)
    friend_poplr = popularity(data["g"], data["So"], data["Sm"], data["Sp"]) * float(10)
    if friend_poplr > float(poplr) - float(10):
        if friend_poplr < float(poplr) + float(10):
            print("# " + i + " is a compatible friend #")
        else:
            print("# " + i + " is not a compatible friend #")
    else:
            print("# " + i + " is not a compatible friend #")

是的,我已经导入了 math 和 json,还有一个朋友列表,但我正在审查他们的名字。 请帮忙

我认为问题在于您将friend_polr乘以 10 而您对poplr不做同样的事情。 您需要做的就是将 poplr 乘以 10 以使它们都相等。 在下面的示例中,我对您的代码进行了一些其他小的改进

def popularity(G, So, Sm, Sp):
    g = float(G) * 0.3
    so = float(So) * 0.4
    sm = float(Sm) * 0.1
    sp = float(Sp) * 0.2
    return g + so + sm + sp

gfactor = input("What is your G-Factor? ")
social = input("What is your Social Quotient? ")
smartness = input("What is your smartness level? ")
sports = input("What is your sports skill? ")

poplr = popularity(gfactor, social, smartness, sports) * 10

print(str(math.ceil(poplr)) + "%")
print("Finding friends... ")

for i in friends:
    fs = open(i + ".txt")
    json_str = fs.read(37)
    data = json.loads(json_str)
    fs.close()                   # remember to close the file
    friend_poplr = popularity(data["g"], data["So"], data["Sm"], data["Sp"]) * 10
    if friend_poplr > poplr - 10:
        if friend_poplr < poplr + 10:
            print("# " + i + " is a compatible friend #")
            continue
    print("# " + i + " is not a compatible friend #")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM