In my homework a user is supposed to enter a number and display factorial,Fibonacci series and all cubed numbers up to the number entered by the user in Python, cannot figure out where is the problem
#!/Python27/python
def factorial( n ):
if n <1: # base case
return 1
else:
return n * factorial( n - 1 )
# recursive call
def fact(n):
for i in range(1, n+1 ):
print "%d" % ( factorial( i ) )
# write Fibonacci series up to n
def fib(n):
a, b = 0, 1
while b < n:
print b
a, b = b, a+b
def cube(n): return n*n*n
def cubes(n):
for i in range(1, n+1):
print "%d" % (cube(i))
def main():
nr = int(input("Enter a number: ")
factorial(nr)
fact(nr)
cubes(nr)
main()
The problem arises from you not having enough brackets:
def main():
nr = int(input("Enter a number: "))
...
You forgot the closing bracket for int()
To display the output in a table, I would to return a list from each function then in main do something like:
import itertools
print "Factorial up to {n}\tFibonacci of 1 to {n}\tCubes of 1 to {n}".format(n = nr)
print '\n'.join('\t'.join(map(str, seq)) for seq in itertools.izip_longest(factorial(nr), fib(nr), cubes(nr), fillvalue=''))
Now if each of the functions (respectively) returned the following lists:
>>> factorial(nr)=> [1, 2, 3, 4]
>>> fib(nr)=> [3, 4, 5, 6, 7]
>>> cubes(nr)=> [7, 453, 23, 676]
Using the above method will yield output like this:
Factorial up to -inf Fibonacci of 1 to -inf Cubes of 1 to -inf
1 3 7
2 4 453
3 5 23
4 6 676
7
It doesn't quite look like a table, but if you stuff more tab characters into the output, you should get something looking closer to table format