如何在while循环中返回值

时间:2015-02-01 05:02:09

标签: python while-loop return-value

我正在为我的一门CS课程做作业。我已经知道了这件事,但我不知道如何在while循环中返回一个值。

我遇到的问题是我需要每次通过while循环添加商,直到t == 0.我有一切正常工作,直到我得到了除法的加法,所有这一切加在一起两个号码。我需要它做的是记住通过循环将“除法”等于前一项,然后将其添加到当前循环计算的内容。

我希望这有任何意义。 Here is a link to the question for those of you who now have a headache after reading my question

# FORMULA IS AS FOLLOWS
# 1 + x + (x^t)/(t!) until t == 1

t = int(input("Enter a non negative integer for t: "))
x = float(input("Enter a real number for x: "))
fact = 1
finalProduct = 1
counter = 1
while counter <= t :
    counter = counter + 1
    fact = fact * counter

    print("counter:",counter)
    print("fact:",fact)


    xPwr = (x**counter)

    division = (xPwr / fact)
    print("Division: ",division)         
    addition = (division + division)#HERE IS MY PROBLEM
    print("Sum:", addition)

finalProduct = (1 + x + addition)

print("finalProduct",finalProduct)

4 个答案:

答案 0 :(得分:2)

这非常接近教师给出的问题描述:

x = float(input("Enter a real number for x: "))
t = int(input("Enter a non negative integer for t: "))
counter = 1
series = 1
num = 1
denom = 1
while counter <= t :
    num = num * x
    denom = denom * counter
    series = series + num / denom
    counter = counter + 1
print(series)

以下是一个例子:

Enter a real number for x: 2.0
Enter a non negative integer for t: 3
6.333333333333333

答案 1 :(得分:1)

这是一个稍微扩展的版本。

首先,你应该意识到给定的系列是e ** x的近似值;包含的术语越多,最终结果越准确。让我们探讨一下:

import math

def approx_ex(x, max_t):
    """
    Maclaurin series expansion for e**x
    """
    num   = 1     # == x**0
    denom = 1     # == 0!
    total = 1.0   # term_0 == (x**0) / 0!

    for t in range(1, max_t + 1):
        # modify numerator and denominator to find next term
        num   *= x       #   x**(t-1) * x == x**t
        denom *= t       #     (t-1)! * t == t!
        # keep a running total    
        total += num / denom

    return total

def main():
    x = float(input("Input a real number: "))

    actual = math.e ** x
    print("\nApproximation of e ** {} == {}\n".format(x, actual))

    for terms in range(1, 16):
        approx = approx_ex(x, terms)
        error  = approx - actual
        print("{:>2d}: {:16.12f}  ({:16.12f})".format(terms, approx, error))

if __name__ == "__main__":
    main()

这就像

一样
Input a real number: 3.205

Approximation of e ** 3.205 == 24.655500016456244

 1:   4.205000000000  (-20.450500016456)
 2:   9.341012500000  (-15.314487516456)
 3:  14.827985854167  ( -9.827514162290)
 4:  19.224423254193  ( -5.431076762264)
 5:  22.042539627609  ( -2.612960388847)
 6:  23.547883457076  ( -1.107616559380)
 7:  24.237115881853  ( -0.418384134603)
 8:  24.513239622030  ( -0.142260394426)
 9:  24.611570353948  ( -0.043929662508)
10:  24.643085353528  ( -0.012414662928)
11:  24.652267678406  ( -0.003232338051)
12:  24.654720124342  ( -0.000779892115)
13:  24.655324746590  ( -0.000175269866)
14:  24.655463161897  ( -0.000036854559)
15:  24.655492736635  ( -0.000007279822)

非常清楚地表明,随着更多术语的总结,结果会越来越好。

答案 2 :(得分:0)

您应该使用Recursive Functions将变量传递给下一个循环。

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

正在过去&#34; n-1&#34;值到下一个循环。

答案 3 :(得分:-1)

您希望将核心的返回值分配回本地y变量,它不会通过引用传递:

y =核心(x) 在进入循环之前,您还需要设置y。函数中的局部变量在其他函数中不可用。

因此,您根本不需要将y传递给核心(x):

def core(x):
    y = input("choose a number: ")
    if y == x:
        print("You gussed the right number!")
        return y
    elif y > x:
        print("The number is lower, try again")
        return y
    else:
        print("The number is higher, try again")
        return y
and the loop becomes:

y = None
while (x != y) and (i < t):
    y = core(x)
    i += 1

在main()函数中设置y并不重要,只要在用户做出猜测之前它永远不会等于x。