Newbie question about for...in range() structure

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • sp@k

    Newbie question about for...in range() structure

    Hi there,

    I'm new to Python and I've been writing a rudimentary exercise in
    Deitel's Python: How to Program, and I found that this code exhibits a
    weird behavior. When I run the script, the for...range(1,1 1) structure
    always starts with zero--and I've tried plugging other values as well!
    From the Python commandline, though, this structure produces a normal
    1,2,3,4,5,6,7,8 ,9,10 output. Can anyone tell me what I am doing wrong
    here?

    input = raw_input("Plea se enter a value you wish to factorialize:")

    def fact(n):
    total = 0
    n = int(n)
    while n 0:
    total *= n
    n -=1
    return total

    print "%d" % fact(input)

    e = 1
    for val in range(1,11):
    if val == 0:
    continue
    else:
    e += 1/fact(val)

    print "Where n is 10, e = %d\n\n" % e


    e2 = 1
    input = raw_input("Ente r x:")

    for val in range(1,11):
    if val == 0:
    continue
    else:
    e2 += (float(input) ** val)/(fact(val))

    print "Where the n is 10, e**x = %d\n\n" %e
  • Paul McGuire

    #2
    Re: Newbie question about for...in range() structure

    On Apr 17, 3:30 am, "sp@k" <spockspla...@g mail.comwrote:
    def fact(n):
            total = 0
            n = int(n)
            while n 0:
                    total *= n
                    n -=1
            return total
    >
    My guess is that you want to initialize total to 1, not 0.

    -- Paul

    Comment

    • sp@k

      #3
      Re: Newbie question about for...in range() structure

      My guess is that you want to initialize total to 1, not 0.
      >
      D'oh! Yes, you are right, thank you.

      Comment

      • Bruno Desthuilliers

        #4
        Re: Newbie question about for...in range() structure

        sp@k a écrit :
        (snip - already answered)
        >
        def fact(n):
        total = 0
        n = int(n)
        while n 0:
        total *= n
        n -=1
        return total
        You may be interested in a very different way to get the same result:

        from operator import mul

        def fact(n):
        return reduce(mul, xrange(1, n+1), 1)


        (snip)

        Comment

        Working...