Home > Enterprise >  Python factorial sum that shows math
Python factorial sum that shows math

Time:02-05

This is the code I have so far works fine but when it prints it just shows the answer rather then the full equation when I want it to print the full equation

    number=int(input("enter a number a number between 1 and 20"))
    def factorial(number):
      value=1
for i in range(1,number 1):
    value*=i
print("the factorial sum for", number, "is {0:,}".format(value,i))
return

################################

  if number == 0:
    print ("please select a differnt number")
  elif number > 20:
    print("please enter a number between 1 and 20")
 else:
    factorial(number)

CodePudding user response:

To print the whole equation you can write something like

f = 1
s = ''

for i in range(1, n 1):
    f *= i
    s  = str(i)   '*' 

print(s[:-1], '=', f)

CodePudding user response:

here is the code, I added an explanation for each step. There may be some new things in here you are unfamiliar with, but exposure to it is good. Use google aggressively

number = 0
while True: ## this loop will catch any non-ints/float numbers inputted
    try: #test the number
        numberinput = int(input("enter a number a number between 1 and 19: "))  #user enters #
        assert numberinput > 0  #make sure the number is between your limits
        assert numberinput < 20 #make sure the number is between your limits
        number = numberinput  #set the number == to our vetted numberInput
        break #exit infinite loop
    except:  #if any errors in above, we enter this clause
        print('Please enter a valid number between 1 and 19') #tell user to try another number
        continue #continue sends us to the top of the loop (starting with try)


def factorial(number):
    value=1  #initial value
    stringOfCalculations= ''  #empty string that we can build on as we loop through
    for i in range(1, number   1): 
        value *= i 
        if i == 1:  #if the value is 1, we dont want to do * i in the string, we want to just add i to the string since we start with 1
            stringOfCalculations  = f'{i}' #we add i to the start of the string. This is called an f' string, similar to .format() but cleaner
        else: #if the number is not 1
            stringOfCalculations  = f' * {i}' # we want to add * i, since were doing math these steps that aren't 1*1

    stringOfCalculations  = f' = {value}' # after looping, our value is the total, so we append '= value' to our string
    print(stringOfCalculations) # print the full string
    return #you chose to return nothing here, but you could also return the value


factorial(number) #no need for the if clause since we check the number is between 1-19 in the try block
  •  Tags:  
  • Related