Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
a factorial of a positive integer n, written as n!, is defined as:
n*(n-1)(n-2)…*1
if n is 0 n! is defined as 1
if n is negative, n! is undefined
An example is:
12! = 12*11*10*9*8*7*6*5*4*3*2*1
Write a program that
1. Inputs a positive integer from the user. If the integer is not positive, it displays an error message
2. Prompts the user to either have the factorial calculated by sequential programming (Option 1) or by recursion (Option 2)
Option 1:
using one of the top down iterative methods (e.g. while, for) find the factorial of any positive integer (including 0).
Option 2:
using recursion (see text section 6.3), find the factorial of any positive integer (including 0)
prints the factorial
Submit to this assignment a Word document (version 2010 or earlier) that contains the source code of your program and screen shots running it with both options and, for each option, with 0, 9, and -4
Hints:
you will need to define a function to perform this task using recursion
don’t try this with too large a number --- that may generate an error because of the memory it takes to perform
I seem to have figured out how to do the functions; however, I cannot seem to get them to work in the main() function.
When I run my program, the Menu() function executes; however, after I enter 1 or 2, my program returns
(Traceback (most recent call last): File "C:/Users/user/Documents/Prjct4", line 59, in <module> main() File "C:/Users/user/Documents/Prjct4", line 54, in main num = factorial() UnboundLocalError: local variable 'factorial' referenced before assignment)
The following is what I have so far:
def Menu():
print
print ("For Sequential Programming Calculator, Enter 1")
print ("For Recursion Calculator, Enter 2")
print
while True:
choice = input("Enter your choice here: ")
if (choice >= 1) and (choice <=2) and (int(choice)==choice):
return choice
else:
print ("Invalid Choice! Please enter 1 or 2")
def factorial():
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
num = int(input("Enter a number: "))
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",factorial(num)
def recur_factorial():
if n == 1:
return n
else:
factorial= n*recur_factorial(n-1)
return factorial
num = int(input("Enter a number: "))
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)
def main():
print
print("Factorial Calculator")
print
while True:
choice = Menu()
if choice == 1:
num = factorial()
elif choice == 2:
factorial = recur_factorial()
main()
If anyone could help me figure this out, I would greatly appreciate it! Thank you!
You have many bugs in your program.
However, the one that is first caused you a problem is that in your main code, you are assigning a value to a variable called factorial. But factorial is supposed to be a function - as per your earlier definition. Why are you assigning the result to a variable anyhow? You don't do anything with it. Maybe you mean print factorial(num).
The next problem you encountered is that you have uninitialised variables all over the place. I assume, from the traceback in your comment, that you changed the code in main to pass num into factorial - like factorial(num). But where do you expect num to get its value from?
You have some code (twice) that asks the user for a value for num, but it is in a place where it will never be executed - after the returns in your functions.
Perhaps you mean for this code to be in main before you call the factorial functions?
Related
If the given number is less than the 2, it asks to reenter the number by using recursion.
I've first given 2 and then after recursion, I gave 3, but the output is still 2.
How to output 3?
def inexpno():
exp = int(input("Enter the Experiment n.o : ")) # Takes a exp number
if exp<=2: # Enter your completed experiment here
print("It is completed Correction for both Record and Observation\n\n")
print("Do you want to select another experiment")
we = input("")
if we == "yes" or we == "YES":
inexpno() # TO CHANGE
else:
exit()
return exp
print(inexpno())
Currently you don't save the return value from inexpno() in the recursive call on line 8. You simply need to save it as exp:
exp = inexpno()
Just change your recursive line to
return inexpno()
so I'm very noobish, I got this python code that I found somewhere in my folders, because I started learning python a while ago, and I need this code for class today. Thing is, it doesn't print anything, it just indicates that there's no problem with it. Can you help me? I need to sc the code and sc the output, if you can guide me to what line of code im missing or anything really.. thanks
def square(n):
word = int(raw_input('Enter number here: '))
if len(word) > 0:
squared = n ** 2
print ("%d squared is %d" %(n,squared))
First of all, using Python 3, you need to replace raw_input with input. Secondly and most importantly, integer does not work with len function and you should compare your integer directly. To handle potential type mismatch, use following code (you can put it in a loop or do any other modifications)
def square():
n = input('Enter number here: ')
try:
n = int(n)
except TypeError:
print("Input is not a number")
else:
if word > 0:
squared = n ** 2
print ("%d squared is %d" %(n,squared))
# Let's call the function
square()
By the way, I think calling integer variable word is not very self-descriptive.
I think this will work:
def square(n):
number = int(input('Enter number here: '))
if number > 0:
squared = n ** 2
print ("%d squared is %d" %(n,squared))
def Factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
def Fibonacci(num):
i=0
present=1
previous=0
while i<=num:
nextterm=present+previous
present=previous
previous=nextterm
i=i+1
print("The fibonacci number for", i, 'is', nextterm)
def CallFibOrFac(x):
num = 10
if x == 'Fib':
Fibonacci(num)
if x == 'Fac':
print (Factorial(n))
x = input('enter fibonacci or factorial')
num = input('enter value for fibonacci')
Fibonacci(num)
n = input('enter value for factorial'
print(Factorial(n))
I defined all my functions and wrote an if statement, but when I enter Factorial, when it asks for x=input(‘enter fibonacci or factorial’), it gives me the input to ‘enter value for fibonacci’ when I need the n=input(‘enter value for factorial’) to display when I put in "factorial".
Although you have a function to choose whether to call Fib or Fact, you never call that deciding function. Instead, what I take to be your main program utterly ignores the user's first input and proceeds to call both functions.
Back up a few steps. Learn to recognize the user's input and call -- or do not call -- a single function.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I need your help if possible. I am very new to Python, but I've got a good understanding in C#, java and now have started learning python as part of my learning program. I am stuck with one of my tasks to do and I can't get any help as no one that I know uses python.
My task is :
"Find the prime numbers from the given list of 10 numbers. User should input 10 numbers"
Could anyone help me please? Thanks in advance
At very simple i make this program for you as per your requirement that user must enter 10 numbers and program finds either it is prime or not.
try this:
for i in range(0, 10):
num = int(input('Enter Number:'))
if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
print(num, "is not a prime number")
print(i, "times", num // i, "is", num)
break
else:
print(num, "is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num, "is not a prime number")
Note: In a for loop a take input from user 10 times if you want to take inputs in the starting then you can also to that and you can then run a loop o that list. Choice is yours!
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
for i in range(10):
number = input("Choose number #%s : " % i)
if is_prime(int(number)):
print("%s is prime" % number)
else:
print("%s is not prime" % number)
You need a function isPrime(n) which check if n is a prime number like this:
import math.sqrt
def isPrime(n):
for i in range(2,int(sqrt(n))+1):
if n%i==0:
return False
return True
Then, you just get the input numbers (int(input("Enter a number")), you store your numbers and you use the function in all the numbers of the list.
To get an input of 10 Numbers just put input() in a for loop like this:
for i in range (0,11):
input("Number")
in addition to that you need a function which calls whether your number is a prime number
def isPrime(n):
for i in range(2,int(sqrt(n))+1):
if n%i==0:
return False
return True
from math import sqrt; from itertools import count, islice
import sys
def is_prime(n):
return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))
def primer(*args):
return '-'.join([str(x) for x in args if is_prime(x)])
while True:
try:
user_input = input('Enter any amount of numbers seperating them with a comma; or enter quit to quit: ')
if any(user_input==x for x in ("quit", "q", "exit", "e")):
sys.exit()
our_list = [int(x) for x in user_input.split(',')]
print(primer(*our_list))
except ValueError:
print('Please only enter numbers')
Normally you should try first, have broken code and then ask; but hey I'm bored so I made an exception for you, here is the whole code. :3
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm pretty new to programming, and I have no idea how to go about this.
Basically I need a function that repeatedly prompts a user to input an integer until they enter a non-numerical characters, then it takes the numbers and averages them.
This what I have so far, the ave function is to average the numbers, that's not the problem
def ioAve():
L = input("Enter your number: ")
if L == int:
print(L)
if L != int:
ave(L)
The program doesn't return anything at all.
This is probably the most pythonic way I can think of to solve this. Your approach of checking if an entered number is of a certain type is less desirable than catching the exceptions that might be raised when trying to convert (e.g. in this case a ValueError is raised when an invalid value is passed to int() ). You can learn more about exceptions in Python at the Python wiki.
The solution below also uses a list, which is an object that can contain multiple values. You can learn more about lists at effbot.org.
numbers = list()
while True:
try:
number = int(input("Enter a number: "))
numbers.append(number)
except ValueError:
break
print ("The average is", sum(numbers) / len(numbers))
cont = True
nums = []
while cont:
entered = input("Enter a number: ")
cont = all(char.isdigit() for char in entered)
if cont:
nums.append(int(entered))
print("The average is:", sum(nums)/len(nums))
Something like this:
print('Average: ',(lambda x:sum(x)/len(x))
([x for x in iter(lambda:(lambda x:int(x)
if x and all(x.isdigit() for x in x)else
...)(input('Enter a number: ')),...)]))
Sorry, I couldn't resist.
Something like this maybe. I'm sure there is a more pythonic way thou.
#import sys instead of using sys for program termination
def main():
sum = 0
iterations = 0
while True:
try:
num = int(raw_input("Input an integer: "))
iterations += 1
sum += num
except:
print "Average: "+str(sum//iterations)
#sys.exit() use break to "jump" out of an infinite loop
break
if __name__ == "__main__":
main()