Python Program to Find Factorial of Number Using Recursion - python

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))

Related

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())))

Collatz from automate the boring stuff

I know there are multiple posts on this question. But I could not post my code in any other way except by asking a question. Can someone please help me understand how I can stop n from being input into the collatz function each time the global scope executes.
Write a function named collatz() that has one parameter named number.
If number is even, then collatz() should print number // 2 and return this value.
If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that keeps calling collatz() on that number
until the function returns the value 1.
(Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence,
you’ll arrive at 1! Even mathematicians aren’t sure why.
Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)#
Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.
desired output
3
10
5
16
8
4
2
1
Input Validation
Add try and except statements to the previous project to detect whether the user types in a noninteger string.
Normally, the int() function will raise a ValueError error if it is passed a noninteger string, as in int('puppy').
In the except clause, print a message to the user saying they must enter an integer.
def collatz(number):
if number%2==0:
number=number//2
print(number)
elif number%2==1:
number=3*number+1
print(number)
print('Enter number: ')
n=int(input())
while n!=1:
collatz(n)
You‘ve created an infinite loop, since your „n“ doesn‘t change within the loop and „n!=1“ is never met as long as the user doesn’t input “1” in the beginning.
Try this:
def collatz(number):
if number % 2 == 0:
number = number // 2
else:
number = 3 * number + 1
print(number)
return number
n = int(input("Enter number: "))
while n != 1:
n = collatz(n)

Code for Python as Prime and function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Stuck on this problem and I couldn't find an answer and my code keeps failing.
Write a function called specialPrime which takes in an integer as an argument and returns True if the integer is a prime number and length of the integer squared is less than six digits, False if it is not a prime number or the integer squared is greater than six digits. Write a program which prompts the user to type in an integer and uses you specialPrime function to determine whether or not the integer is special.
Example Interaction
Enter a number: 140
140 is not a special prime number.
Enter a number: 89
89 is a special prime number.
My code
def specialPrime(isPrime,G6):
isPrime= int(input('Enter a number:')
if isPrime < 2 return False
elif isPrime == 2
return True
for n in range(2, x)
if x % n ==0:
return False
return True
G6 = len(isPrime**2)
if G6 > 6: return False
else
return True
while True
print( isPrime + 'is a special number')
else
print( isPrime + 'is not a special prime')
`
First:
Write a function called specialPrime which takes in an integer as an argument and returns True [or] False
Your function doesn't take an integer as an argument, it takes two arguments that… I'm not sure what they're intended to be, because you ignore them anyway. So, start with that. Also, give it a meaningful name. isPrime sounds like a flag that tells you whether a number is prime, or a function that figures out whether a number is prime, not a candidate number that may or may not be prime. So:
def specialPrime(number):
The next part of your code is close, but it's got problems too:
You're supposed to be testing the value you got as an argument, not some completely different value you got from input.
if, elif, for, and all other "compound statements" in Python need colons.
if, etc., statements with multi-line bodies need those bodies indented.
What is x? You were testing isPrime, and suddenly you're testing another variable that you haven't even defined anywhere.
You return True if the number is == 2, and also if it's > 2 but has no divisors between 2 and the number. That means you aren't testing the other condition; you're just assuming it's always true.
So:
if number < 2: return False
elif isPrime == 2:
pass
for n in range(2, number):
if number % n ==0:
return False
This can all be improved in multiple ways, but those are the minimal changes to make it make sense as Python code.
Next, you're trying to take the length of a number. Numbers don't have lengths. You can take the length of a string representation of a number:
digits = len(str(number**2))
if digits > 6:
… or you can do arithmetic to test the number of digits:
square = number**2
if square > 999999:
Also, notice the names digits and square, which tell you that it's a count of digits, or a square of a number, instead of G6, which tells you that it's a group of the 6 major EU countries.
Either way, you then have some of the same problems from the first block with colons and indents again, which you need to fix the same way.
Finally:
Write a program which prompts the user to type in an integer and uses you specialPrime function to determine whether or not the integer is special.
There's nothing about a while True-type loop here—it's a reasonable extension to the program, but get the basics working first.
So you need to prompt the user to type in an integer. Here is where you use input:
number = input('Enter a number:')
But the result of input is a string. If the user types 23, what you get is the string '23'. So, you need to call int to convert it:
number = int(input('Enter a number:'))
Now you have to call your function:
if specialPrime(number):
And again, you have some of the same errors with colons and indents that you need to fix.
After all of those fixes, the code will run. If there are no logic errors in your tests, it will give the right answer. If there are… well, you can debug it from there.
You could modify your code to use a couple of helper functions for each of the two requirements of special_prime(x):
def squared_less_than_six_digits(x):
return len(str(x**2)) < 6
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x):
if x % n == 0:
return False
return True
def special_prime(x):
return is_prime(x) and squared_less_than_six_digits(x)
def main():
user_input = 0
while True:
try:
user_input = int(input("Please enter an integer:"))
except ValueError:
print("Error: You did not enter a integer. Please try again.")
continue
else:
print("You entered the integer {}. Its square is {}.".format(user_input, user_input**2))
break
if special_prime(user_input):
print("It is a special prime.")
else:
print("It is not a special prime.")
if __name__ == "__main__":
main()
Try the above code out here!
Testing:
Prime number whose square is less than six digits:
Please enter an integer: 2
You entered the integer 2. Its square is 4.
It is a special prime.
Prime number whose square is greater than or equal to six digits:
Please enter an integer: 317
You entered the integer 317. Its square is 100489.
It is not a special prime.
Nonprime number whose square is less than six digits:
Please enter an integer: 1
You entered the integer 1. Its square is 1.
It is not a special prime.
Nonprime number whose square is greater than or equal to six digits:
Please enter an integer: 318
You entered the integer 318. Its square is 101124.
It is not a special prime.

Factorial using two functions Python 3.x

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.

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.

Categories