首页 > 解决方案 > 如何重新启动我的阶乘计算器,以便用户可以找到多个数字的阶乘?

问题描述

我正在尝试使用 while 循环计算 0 到 25 之间的任何整数的阶乘。

我的阶乘输出正确,但我想重新启动代码,以便用户可以再次使用我的程序,如果他们想找到另一个介于 1 到 25 之间的数字的阶乘。

为此,我创建了一个名为“stop”的变量,以便在 stop="y" 时使用它来停止程序。

我设置了 stop="n" 以便 while 循环可以执行一次。

计算出阶乘后,我希望用户被问到“你完成了吗?如果你完成了,请输入 y”

如果他们按 y 以外的任何字母,我希望 while 循环重新启动。如果他们按 y,我希望程序结束。

Stop= “n”
if stop != “y”:
num=int(input("Enter a number between 1 and 25:"))

if num >25 or num < 0:
print("Can you please enter a number between 0 and 26?")
    factorial=1;
    while(num>0 and num<=25):
    factorial= factorial*num
    num=num-1
    print("The factorial of your number is:")
    print(factorial)
        stop= str(input(“Are you done? Type y if you are”
print(“Thanks for playing!”)

我当前的输出是打印上的语法错误(“感谢播放!”)。我正在使用 IDLE(Python 3.8,32 位);

标签: python

解决方案


我认为您的问题可能是“感谢您玩!”周围的引号。与“输入 1 到 25 之间的数字:”周围的不同(“”与“不同,我假设第一个是从某个地方复制的?)。

并注意你在 python 中的格式;照原样,您的 while 语句后没有任何缩进,因此不会运行任何内容。我相信你想要做的是:

stop= "n"

while stop != "y":
  num=int(input("Enter a number between 1 and 25:"))

  if num > 25 or num < 0:
    print("Can you please enter a number between 0 and 26?")
    continue

  factorial = 1

  while(num>0 and num<=25):
    factorial = factorial*num
    num=num-1
  print("The factorial of your number is: ", factorial)
  stop = str(input("Are you done? Type y if you are"))

print("Thanks for playing!")

推荐阅读