Python Factorial while循环

时间:2017-07-13 22:33:35

标签: 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()
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()

1 个答案:

答案 0 :(得分:1)

您没有在while循环的运行之间重置factorial的值。你应该移动

factorial= 1

追随

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