Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python阶乘while循环_Python_Loops_While Loop_Factorial - Fatal编程技术网

Python阶乘while循环

Python阶乘while循环,python,loops,while-loop,factorial,Python,Loops,While Loop,Factorial,需要有关此代码的帮助。它第一次计算阶乘精细度,但当它在while循环中循环时,它似乎在存储值并将其递增。有什么建议吗 #Get number and store in variable, also declare and initialize factorial variable number = int(input("Please enter a nonnegative integer number (or enter 0 to end program): ")) print() factor

需要有关此代码的帮助。它第一次计算阶乘精细度,但当它在while循环中循环时,它似乎在存储值并将其递增。有什么建议吗

#Get number and store in variable, also declare and initialize factorial variable
number = int(input("Please enter a nonnegative integer number (or enter 0 to end program): "))
print()
factorial= 1

#Check if number is a negative integer and if it is, prompt for input again or give option to end program
if number <0:
    while number !=0 and number <0:
      print("You have entered a negative integer. Please try again.")
      number = int(input("Please enter a nonnegative integer number (or enter 0 to end program): "))
      print()

#Calculate and display factorial of number while input is valid
while number != 0 and number >=1:
  #Calculate and display factorial value
  while number >= 1:
    factorial = factorial * number
    number = number -1
  print("The factorial for that number is: {}".format(factorial))
  print()

  #Get the next number
  number = int(input("Please enter another nonnegative integer number or enter 0 to end program: "))
  print()

  #Check if newly entered number is a negative integer and if it is, prompt for input again or give option to end program 
  if number <0:
    while number !=0 and number <0:
      print("You have entered a negative integer. Please try again.")
      print()

      #Prompt again for valid nonnegative integer
      number = int(input("Please enter a nonnegative integer number (or enter 0 to end program): "))
      print()
#获取数字并存储在变量中,同时声明并初始化阶乘变量
number=int(输入(“请输入一个非负整数(或输入0以结束程序):”)
打印()
阶乘=1
#检查数字是否为负整数,若为负整数,则再次提示输入或给出结束程序的选项
如果数字=1:
阶乘=阶乘*数
数字=数字-1
print(“该数字的阶乘为:{}”。格式(阶乘))
打印()
#接下一个号码
number=int(输入(“请输入另一个非负整数或输入0以结束程序:”)
打印()
#检查新输入的数字是否为负整数,若为负整数,则再次提示输入或给出结束程序的选项

如果number在while循环的两次运行之间,您没有重置factorial的值。你应该把线移走

factorial= 1
追求

#Calculate and display factorial of number while input is valid
while number != 0 and number >=1:

你有很多多余的代码。请看一下如何提供一个服务。你是对的。我正在上Python课程。还是个新手。接下来,我将学习函数和模块化代码。这将有助于减少冗余代码。谢谢,现在我明白为什么了。我把那条线放在最外面的while环中。我是Python新手。