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

S

sp@k

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,11) 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("Please 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("Enter 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
 
P

Paul McGuire

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
 
B

Bruno Desthuilliers

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top