使用Python进行阶乘计算 [英] Factorial calculation using Python

查看:208
本文介绍了使用Python进行阶乘计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想用程序计算阶乘.

  1. 要求用户输入非负数n
  2. 然后使用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进行阶乘计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆