创建Python阶乘

编程入门 行业动态 更新时间:2024-10-26 20:21:33
本文介绍了创建Python阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

晚上

我是遇到麻烦的python学生的简介. 我正在尝试制作python阶乘程序.它应该提示用户输入n,然后计算n的阶乘,除非用户输入-1.我很困惑,教授建议我们使用while循环.我知道我什至还没有达到'if -1'的情况.不知道如何让python仅仅使用math.factorial函数就可以计算出阶乘.

I'm an intro to python student having some trouble. I'm trying to make a python factorial program. It should prompt the user for n and then calculate the factorial of n UNLESS the user enters -1. I'm so stuck, and the prof suggested we use the while loop. I know I didn't even get to the 'if -1' case yet. Don't know how to get python to calc a factorial with out just blatantly using the math.factorial function.

import math num = 1 n = int(input("Enter n: ")) while n >= 1: num *= n print(num)

推荐答案

学校中的经典"阶乘函数是一个递归定义:

The 'classic' factorial function in school is a recursive definition:

def fact(n): rtr=1 if n<=1 else n*fact(n-1) return rtr n = int(input("Enter n: ")) print fact(n)

如果您只想找到一种解决方法:

If you just want a way to fix yours:

num = 1 n = int(input("Enter n: ")) while n > 1: num *= n n-=1 # need to reduce the value of 'n' or the loop will not exit print num

如果您要测试小于1的数字,

If you want a test for numbers less than 1:

num = 1 n = int(input("Enter n: ")) n=1 if n<1 else n # n will be 1 or more... while n >= 1: num *= n n-=1 # need to reduce the value of 'n' or the loop will not exit print num

或者,在输入后测试n:

Or, test n after input:

num = 1 while True: n = int(input("Enter n: ")) if n>0: break while n >= 1: num *= n n-=1 # need to reduce the value of 'n' or the loop will not exit print num

这是使用减少的功能性方式:

Here is a functional way using reduce:

>>> n=10 >>> reduce(lambda x,y: x*y, range(1,n+1)) 3628800

更多推荐

创建Python阶乘

本文发布于:2023-11-29 19:38:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647429.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阶乘   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!