使用Python进行阶乘计算

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

我是Python的新手,目前正在阅读 Python 3作为绝对的初学者,并且遇到了以下问题.

I am new to Python and currently reading Python 3 for absolute beginner and face following problem.

我想用程序计算阶乘.

  • 要求用户输入非负数n
  • 然后使用for循环计算阶乘
  • 代码是这样的:

    and the code is like that:

    N = input("Please input factorial you would like to calculate: ") ans = 1 for i in range(1,N+1,1): ans = ans*i print(ans)

    同时我想添加一个功能来检查输入数字N是否为非负数.像:

    while i would like to add a feature to check whether input number N is non-negative number. like:

    if N != int(N) and N < 0:

    如果不是非负数,我希望用户再次输入N.

    I want the user to input N again if it is NOT non-negative number.

    感谢您的温柔帮助.

    推荐答案

    构造可能如下所示:

    while True: N = input("Please input factorial you would like to calculate: ") try: # try to ... N = int(N) # convert it to an integer. except ValueError: # If that didn't succeed... print("Invalid input: not an integer.") continue # retry by restarting the while loop. if N > 0: # valid input break # then leave the while loop. # If we are here, we are about to re-enter the while loop. print("Invalid input: not positive.")

    在Python 3中,input()返回一个字符串.在所有情况下,您都必须将其转换为数字.因此,您的N != int(N)没有任何意义,因为您无法将字符串与整数进行比较.

    In Python 3, input() returns a string. You have to convert it to a number in all cases. Your N != int(N) thus makes no sense, as you cannot compare a string with an int.

    相反,尝试直接将其转换为int,如果不起作用,请让用户再次输入.那会拒绝浮点数以及所有其他无效的整数.

    Instead, try to convert it to an int directly, and if that doesn't work, let the user enter again. That rejects floating point numbers as well as everything else which is not valid as an integer.

    更多推荐

    使用Python进行阶乘计算

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

    发布评论

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

    >www.elefans.com

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