Factorial using two functions Python 3.x - python

Hello everyone I have a homework assignment that I am supposed to do in python 3.x
I am struggling to figure out how to do this so I'm hoping you can explain to me how to about this.
Problem
The factorial of a positive integer n (written n!) is the product 1 x 2 x 3 x ... x n. Write a program that asks the user to input a positive integer and then calculates and displays the factorial of the number. The program should include two functions: getN to which the input is sent, and which guarantees that the input is a positive integer. The function fact should calculate the factorial value. The program (main) should then display the factorial value.
So far I have a rough sketch of how I want to go about this
#This program will show the answer to a factorial after the user inputs a value.
def getN(n):
try:
n = int(input("Please enter a non-negative integer: "))
except n < 1:
print("You did not enter a value of 1 or greater.")
def fact(n):
count = 1
while n > 0:
count *= n
n -= 1
if n == 0:
break
def main(n):
n = int(input("Please enter a non-negative integer: "))
getN(n)
main(n)
I believe its supposed to look something like this. If you can give me some feedback about what I should do that what be greatly appreciated. Thanks!

Please see inline comments
def getN():
try:
n = int(input("Please enter a non-negative integer: "))
if n < 1:
raise ValueError # it will be thrown also if input is not a valid int
except ValueError: # n < 1 is not an Exception type
print("You did not enter a value of 1 or greater.")
else:
return n
def fact(n):
count = 1
for i in range(1, n+1): # you see how simple it is with for loop?
count *= i
return count
def main():
n = getN() # before you were just asking n twice, never using fact()
print(fact(n))
main()

Seems reasonable to me. It looks like you never return or print the actual factorial calculation. Maybe your function 'fact' should "return count"? In addition, you don't need to check "if n==0" in your fact function, since if it is 0 it will end the while loop due to the condition of the while loop.

Related

Keep asking for numbers and find the average when user enters -1

number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)

Python Program to Find Factorial of Number Using Recursion

The factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 is 12345*6 = 720. Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
I would like help just to know how to read the entries and call the functions
For that purpose you can add the following code below your functions:
# main program
method = {
"IV": add_node,
"IA": add_edge,
"RV": delete_node,
"RA": delete_edge
}
numinputlines = int(input())
for _ in range(numinputlines):
instruction, *rest = input().split()
if len(rest) == 3: # There is a cost:
rest[-1] = int(rest[-1])
method[instruction](*rest)
The method dictionary helps to translate a 2-letter code to a method that needs to be called. As the arguments to those methods are all in the same order, you can just capture those in a list rest, and "unpack" that list when passing the arguments. There is just one special thing to take care of. Two methods get a cost argument, and it must be of number type. Since input is read as string, you need to convert that cost string to a number. The if statement takes care of this case.
This should answer your question, but it does not finish the exercise. You will still have to debug your code. For instance, currently your code will raise an exception on the example input you have given -- vertex "B" is referenced in IA B A 1 before it is added with IV B.
Also, you'll need to add the code to produce the output.
But since your question was about capturing the input and calling the functions, I have left the rest for you to tackle.
How do I calculate a factorial of an integer in Python? Note that the factorial function is defined only for positive integers; therefore, you should also check that n >= 0 and that isinstance(n, int). Otherwise, raise a ValueError or a TypeError respectively.
def factorial(n):
if(not isinstance(n, int) or n < 0):
raise ValueError("Invalid argument")
if (n==1 or n==0):
return 1
else:
return (n * factorial(n - 1))
# Driver Code
num = int(input("Please enter a number"))
print("Factorial : ",factorial(num))

ask the user for a non negative integer using the while loop

Write a program that does the following: ask the user for a nonnegative integer, using the while loop, calculate and print out the factorial of the input (you are not allowed to use the math module or the math.factorial() function). The user may provide 0, output should be 0! = 1. If the user enters a negative integer then write a message for the user that an nonnegative integer is expected and end the program.
Try this:
num = -1
while num < 0:
num=int(input())
factorial=1
for i in range(1, num+1):
factorial *= i
print(factorial)
P.S. Looks like programming homework :) Please, solve it on your own.
We first define a variable with value 1 then multiply it with from 1 to n
then return the answer
def fact(n):
if n<0:
return "an nonnegative integer is expected"
result = 1
for i in range(1,n+1):
result *= i
return f"{n} != {result}"
if __name__ == "__main__":
print(fact(int(input())))

Being told I have an infinite loop, but I'm unsure how to fix it. (Python Coding Course)

I'm currently in a python coding class and this is an assignment. I apparently have an infinite loop somewhere in my code, yet I can't seem to find it.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
# At this point the program should take your now factorial and give you the fibonacci sequence
# takes your factorial and makes it the fibonacci
nterms = factorial
# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=', ')
while count < nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1
I've used both the debugging tool and attempted to find the problem myself by running the programming and attempting various break sequences but I'm just not grasping it.
There is no infinite loop in your code, both loops will finish in finite time. What is happening is that your teacher, without looking at your code, has discovered that the finite time is very, very long and mistaken this for an infinite loop.
The reason it's taking so long is that you have misunderstood the question - "I was asked to make a program that took an integer and gave me said factorial of an integer. Then give the Fibonacci sequence of the integer" - means find the factorial and Fibonacci sequence of the same integer rather than feeding the first result into the second. Simply replace the line nterms = factorial with the line nterms = num to fix the problem.
(See comments on question for additional information used in this answer)
First, you already know what a loop is and how it works. You should review the loop in your code and make sure any variable used is defined. Since this is an assignment, this is the best I can do for you, to be honest your problem is already solved.
Maybe try enclosing your code in a function with arguments/input-variables, this way your code might run smoother and better. Hope this helps.

Creating an exclusion in Python

I'm writing a program that should add all positive values that a user enters, and the program should loop until he/she enter a negative number. The program loops smoothly but it includes the negative number in the sum. Any help is appreciated!
def main ():
X=0
Y=0
print("I can add the sum of all positive numbers")
X = int (input ("Please enter a positve number between 0 and infinity: "))
if X > 0:
while Y >= 0:
print("I can add the sum of all positive numbers")
Y = int(input("Please enter a positive number between 0 and infinity: "))
X = X + Y
print("The sum of the numbers you entered is: ", X)
else:
print("Sorry I can only add positive numbers")
main()
Make the addition X = X + Y before you input the number (but inside the while). You initialized both variables so the "extra" addition before entering a number is just X = 0 + 0 and has no negative effect.
Otherwise it will execute the addition one more time (even if you entered a negative number) before the while loop exits. The condition of the while loop is only tested when first trying to enter it and each time the code inside it is finished and the program checks if it should perform another "loop".

Categories