One thing I struggle with when going through these exercises is knowing why one solution is better than another. I've heard that if you can accomplish something with a smaller amount of code, then that's a good sign, but how do I know when a for loop is better than a while, or when I should use nested if statements? Do I need to be mindful of performance differences between different approaches?
Below are my solutions for #5 Factorial and #6 Prime. What changes are some changes I could make to improve them and what would be the justifications for those changes?
def factorial(x): if int(x) > 0: fact = 1 for x in range(0,x): fact *= (x + 1) return fact
def is_prime(x): fact = 0 for n in range(1,x+1): if x % n == 0: fact += 1 if fact == 2: return True else: return False