Avatar ·

How to calculate the sum 1!+2!+3!+...+n!

📁 Advanced Python Topics, AI

Problem condition:

Given a natural number n, calculate the sum 1!+2!+3!+...+n!. Only one loop can be used in solving this problem. Using the math library is prohibited in this problem.

n = int(input())N = 1sum = 0for a in range(1, n+1):    for b in range(1, a+1):        N = N * b    sum += Nprint(sum                    
Avatar ·

Mark Lutz - "Learning Python", chapter 20, page 596

As is known, names that are assigned inside a function are considered local by default - they are located in the function's scope and exist only during the function's execution. But I haven't yet mentioned that local variables are determined statically, during compilation of the code in the def statement, rather than according to assignment operations performed at runtime. This feature causes the most bizarre messages in newsgroups received from beginning programmers. Usually, if a name is not assigned any value inside a function, its lookup will be performed in the enclosing module's scope. But look what happens

Log in to leave an answer

Blogs