首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >表示数学的Python阶乘和

表示数学的Python阶乘和
EN

Stack Overflow用户
提问于 2022-02-04 19:13:04
回答 2查看 45关注 0票数 0

这是我到目前为止所得到的代码,但是当它打印出来时,它只是显示了答案,而不是完整的等式,当我希望它打印完整的方程式时。

代码语言:javascript
运行
复制
    number=int(input("enter a number a number between 1 and 20"))
    def factorial(number):
      value=1
for i in range(1,number+1):
    value*=i
print("the factorial sum for", number, "is {0:,}".format(value,i))
return

################################

代码语言:javascript
运行
复制
  if number == 0:
    print ("please select a differnt number")
  elif number > 20:
    print("please enter a number between 1 and 20")
 else:
    factorial(number)
EN

回答 2

Stack Overflow用户

发布于 2022-02-04 23:43:47

要打印整个方程,您可以编写如下内容

代码语言:javascript
运行
复制
f = 1
s = ''

for i in range(1, n+1):
    f *= i
    s += str(i) + '*' 

print(s[:-1], '=', f)
票数 0
EN

Stack Overflow用户

发布于 2022-02-04 19:34:35

下面是代码,我为每个步骤添加了一个解释。这里可能有一些你不熟悉的新事物,但是接触它是很好的。积极使用谷歌

代码语言:javascript
运行
复制
number = 0
while True: ## this loop will catch any non-ints/float numbers inputted
    try: #test the number
        numberinput = int(input("enter a number a number between 1 and 19: "))  #user enters #
        assert numberinput > 0  #make sure the number is between your limits
        assert numberinput < 20 #make sure the number is between your limits
        number = numberinput  #set the number == to our vetted numberInput
        break #exit infinite loop
    except:  #if any errors in above, we enter this clause
        print('Please enter a valid number between 1 and 19') #tell user to try another number
        continue #continue sends us to the top of the loop (starting with try)


def factorial(number):
    value=1  #initial value
    stringOfCalculations= ''  #empty string that we can build on as we loop through
    for i in range(1, number + 1): 
        value *= i 
        if i == 1:  #if the value is 1, we dont want to do * i in the string, we want to just add i to the string since we start with 1
            stringOfCalculations += f'{i}' #we add i to the start of the string. This is called an f' string, similar to .format() but cleaner
        else: #if the number is not 1
            stringOfCalculations += f' * {i}' # we want to add * i, since were doing math these steps that aren't 1*1

    stringOfCalculations += f' = {value}' # after looping, our value is the total, so we append '= value' to our string
    print(stringOfCalculations) # print the full string
    return #you chose to return nothing here, but you could also return the value


factorial(number) #no need for the if clause since we check the number is between 1-19 in the try block
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70991694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档