对于python打印循环两次

时间:2017-10-30 02:49:02

标签: python

此功能的结果由于某种原因打印出两次。有什么理由吗?我无法解决这个问题,我现在已经看了一个小时,试图弄清楚为什么会这样做。

import math


def pop1(t):
    r1 = 1 / (1 + (math.e ** -(t)))
    print(r1)

def pop2(t):
    r1 = 1 / (1 + (math.e ** -(t)))
    return r1




def main():
    for t in range(-6, 7):
        print(t, end=" ")
        pop1(t)

    total = 0
    for t in range(-6, 7):
        result = pop2(t)
        total = total + result
        print(t, result)

    print('Total is', total)



main()

2 个答案:

答案 0 :(得分:0)

修复缩进后,这是一个工作版本:

import math

def pop1(t):
    r1 = 1 / (1 + (math.e ** -(t)))
    print(r1)

def pop2(t):
    r1 = 1 / (1 + (math.e ** -(t)))
    return r1

def main():
    for t in range(-6, 7):
        print(t, end=" ")
        pop1(t)

    total = 0    
    for t in range(-6, 7):
        result = pop2(t)
    total = total + result
    print(t, result)

    print('Total is', total)

main()

<强>输出

-6 0.002472623156634775
-5 0.006692850924284857
-4 0.017986209962091562
-3 0.04742587317756679
-2 0.11920292202211757
-1 0.2689414213699951
0 0.5
1 0.7310585786300049
2 0.8807970779778823
3 0.9525741268224331
4 0.9820137900379085
5 0.9933071490757153
6 0.9975273768433653
6 0.9975273768433653
Total is 0.9975273768433653

答案 1 :(得分:0)

它没有打印两次,它正在做你要做的事情:

您的两次打印是以下原因:

print(r1)

print(t, end=" ")

其次,您的代码缩进不正确,如果您在循环外执行total=total+result,则总计不会添加结果,以下是代码的修复:

import math

def pop1(t):
    r1 = 1 / (1 + (math.e ** -(t)))


def pop2(t):
    r1 = 1 / (1 + (math.e ** -(t)))
    return r1

def main():
    for t in range(-6, 7):

        pop1(t)

    total = 0
    for t in range(-6, 7):
        result = pop2(t)
        total+=result
        print(t, result)


    print('Total is', total)

main()

输出:

-6 0.002472623156634775
-5 0.006692850924284857
-4 0.017986209962091562
-3 0.04742587317756679
-2 0.11920292202211757
-1 0.2689414213699951
0 0.5
1 0.7310585786300049
2 0.8807970779778823
3 0.9525741268224331
4 0.9820137900379085
5 0.9933071490757153
6 0.9975273768433653
Total is 6.5