5/15


#1

Directions:
Define a function factorial that takes an integer x as input.

Calculate and return the factorial of that number.

Here is my attempt:

def factorial(x):
	result = 1
	if x == 1:
		return result
	elif (x - 1) > 0:
		result = result * x * (x - 1)
		x = x - 1
		return result
  	for num in x: #Do I loop here or earlier?
			result = result * x
	else:
		return result
    
print factorial(x)

It works for x = 1, x = 2, and x=3. However, I am stuck on how to create the loop for x = 4, 5, …

Do I replace the if statements with a loop? Generally, when do I use if/elif/else and when do I use loops?


#2

The for loop should be earlier, because currently when x=5, we get:

	elif (x - 1) > 0:
		result = result * x * (x - 1)
		x = x - 1
		return result

the elif condition evaluates to true, so the elif clause executes, return keyword is reached so the function ends. (return keyword will end the function)


#3

I made this change, but seemed to worsened the error so that x = 3 no longer works. I can’t figure out how to use “for,” so I tried “while.”

def factorial(x):
	result = 1
	if x == 1:
		return result
	elif (x - 1) > 0:
		while (x - 1) > 0:
			result = result * x * (x - 1)
			x = x - 1
	return result
    
print factorial(x)

#4

both for and while is possible, but if you want to use for loop, the range function is really recommended

as for your current while loop, this:

result = result * x * (x - 1)

is way to many multiplications you are making given you have a loop iterating over all the values.


#5

This threw me way off (with all due respect). :face_with_head_bandage:
Can we just say the entire code could be 6 lines? I was relying too much on this.

  1. Define
  2. Set value
  3. Iterate / loop
  4. Calculate
  5. Reduce count
  6. Return value

#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.