Videos
I'm pretty sure you meant to apply that tuple to the range function:
Copyfor num in range(1, 6, 1):
Although range(1, 6) will suffice. A step of 1 is the default.
(1, 6, 1) is just a tuple of 3 elements, 1, 6, and 1.
You just loop in set has three elements 1,6,1. You should replace by range(1,6).
I have an assignment for class about a topic we never went over. Would appreciate help how to do it.
Write a script that inputs a nonnegative integer and computes and displays is facotrial. Try your script on the integers 10, 20, 30 and even larger values. Did you find any integer input for which Python could not produce an integer factorial value?
I have no idea where to start
Iterative approach:
def calculate_factorial(n):
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
Recursive:
def calculate_factorial(n):
if n == 0:
return 1
else:
return n * calculate_factorial(n-1)
It would be great if you could share the code that you tried.
A possible method using a while loop:
factorial_base = int(input('Enter a positive integer:\n')) # The number to factorialize.
factorial = 1
if factorial_base > 0: # 0! = 1, so if the base is 0, just leave the factorial value as default (1).
while factorial_base != 1:
factorial *= factorial_base
factorial_base -= 1
Essentially, this will multiply 1 by the given number to factorialize (i.e. n), then by (n - 1), then by (n - 2), and so on, until the multiplication factor reaches 1.
Hope this helps.
Just started loops . Seemed pretty straight forward. But I got to this question and though the concept makes perfect sense I can't seem to write the code to do the function. After watching youtube videos, though helpful they were for user input (which we've touched on as well) but not what the question is asking. Im confused by the "!" Whether I should be putting that somewhere. Everywhere it would make sense for the operator I get an error. And I realize I am doing it wrong I need to count down 5*4*3*2*1 but I'm doing 5*5. Thats because Im trying to figure out how to get a single number. Should I be making another variable = int(input()? Thanks for any help.
mystery_int = 5
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#In math, factorial is a mathematical operation where an
#integer is multipled by every number between itself and 1.
#For example, 5 factorial is 5 * 4 * 3 * 2 * 1, or 120.
#Factorial is represented by an exclamation point: 5!
#
#Use a for loop to calculate the factorial of the number
#given by mystery_int above. Then, print the result.
#
#Hint: Running a loop from 1 to mystery_int will give you
#all the integers you need to multiply together. You'll need
#to track the total product using a variable declared before
#starting the loop, though!
#Add your code here!
for i in range(mystery_int,mystery_int +1):
i *= mystery_int
print(i * mystery_int)