Recursive function python, cannot print an output - python

I have just started to program in python, and I am stuck with a problem regarding recursion.
The program seems to compile, however, the print output is not shown.
Here is the program:
print 'type s word'
s = raw_input()
print 'enter a number'
n = raw_input()
def print_n(s, n):
if n<=0:
return
print s
print_n(s, n-1)
the output i get is:
xxxx#xxxx-Satellite-L600:~/Desktop$ python 5exp3.py
type s string
hello
add the number of recursions
4
xxxx#xxxx-Satellite-L600:~/Desktop$
What is wrong, and how can I get the program to show an output?

Your posted code defines the function print_n but never calls it. After the function definition place a print_n(s, n).
Once you do this you'll find some errors caused by the fact the n is currently a string (raw_input returns a string). Use int(a_string) to convert a string to an integer. Calling your function like this will solve the issue
print_n(s, int(n))
Or do
n = int(raw_input())
The complete code:
s = raw_input('type a word: ')
n = int(raw_input('enter a number: '))
def print_n(s, n):
if n <= 0:
return
print s
print_n(s, n-1)
print_n(s, n)

try n = raw_input() -> n = int(raw_input())

Related

Python code doesn't print anything, just gives code 0

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

Asterisk Triangle in Python (using recursion)

I have seen multiple "python asterisk triangles" and their solutions, but I am stuck on creating an asterisk triangle using recursion (without a loop, which would make it much easier in my opinion.) Below is the current code I have:
def main():
num = int(input("Enter an integer: "))
triangle = draw_triangle(num)
print(triangle)
def draw_triangle(n):
if n == 0:
return
else:
return ("*" * n + '\n') + draw_triangle(n - 1)
main()
When I run the code, I receive "TypeError: must be str, not NoneType." I have done some research and still do not completely understand what this error is telling me. I apologize if this question was asked before, I was unable to find one dealing with any recursive functions. Thank you.
return to return ""
Input: 5
Output:
*****
****
***
**
*
This error occurs because you return a blank value. Try returning a blank string instead
Solution:
In line 9:
replace return with return ''
The code is working properly but there is just a slight problem.
When testing with base case i.e. if n == 0: the return must be set to something, if not it will return None. Thus after the input number reaches 0 it returns None anything that returns None is interpreted as a failed case in python so
Here is a work around:
def draw_triangle(n):
if n == 0:
return ''
else:
return ("*" * n + '\n') + draw_triangle(n - 1)
def main():
num = int(input("Enter an integer: "))
triangle = draw_triangle(num)
print(triangle)
main()
Thus after reaching n == 0 case the program will return a blank string and continue.

New to coding python , need help on why my code isnt working?

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.

Python codecademy digit_sum

the task was discussed in
codecademy Practice Makes Perfect digit_sum
Where you need to sum the digits of a positive number.
I use the string way to decide the task (not the floor dividing).
My code is
def digit_sum (n):
total = 0
for digit in range(len(str(n))):
total += int(n[digit])
return total
number = raw_input("Please print a long number: ")
print digit_sum(number)
It works all right with 1001 as well as with 434.
However, the program says:
Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a "'int' object has no attribute 'getitem'" error.
What can be wrong when the code is working?
Thanks!
you did not convert n to string, so when you call n[i] it will raise exception
def digit_sum(n):
return sum( int(i) for i in str(n) )
Evert, Jerzyk, Galaxian, thanks for the comments. Thanks for you I saw it: I casted n to str only in one place (3rd line) and thought that this was enough since the 4th line is inside the for loop. I edited the code to
def digit_sum (n):
total = 0
n = str(n)
for digit in range(len(n)):
total += int(n[digit])
return total
number = int(raw_input("Please print a long number: "))
print digit_sum(number)
And now it works!
Galaxian, ShadowRanger, thanks for your short code, I tried it and it' fine!
I haven't caught yet this brief way of coding. By the way I searched for info about map function and found this:explanation on zip, map, lyambda

Python Factorial program help

Here is what i wrote:
number = raw_input('Enter an integer= ')
if number < 0:
print 'Invalid number'
else:
for k in range(1,(number)):
number *= k
print number
I want to be able to input any number (that is greater than 0), but when i input a number say 4 (the factorial of 4 is 24) i get this error:
Traceback (most recent call last):
File "problem.py", line 6, in <module>
for k in range(1,(number)):
TypeError: range() integer end argument expected, got str.
I don't understand what it means and as far as i know the code should be working, Please Help!
This works perfectly: factorial.py
#!/usr/bin/env python
# imports go here
__author__ = 'Michael O. Duffy'
__status__ = "Development"
def factorial(n):
""" Calculate a factorial of an integer """
factorial = 1
if n < 0:
print 'Invalid number'
else:
for k in range(1,n+1):
factorial *= k
return factorial
if __name__ == '__main__':
for number in range(1, 20):
print 'n: ', number, 'n!: ', factorial(number)
You should know that this is an inefficient, academic implementation that shouldn't be used in any serious application. You'll be a lot better off using a gamma or lngamma implementation and a dictionary cache to save on calculations if you use values repeatedly:
http://mathworld.wolfram.com/GammaFunction.html
What about recursion?
def factorial(n):
if n < 0:
print("ERROR!") # throw error, return -1, or whatever
elif n <= 1:
return 1
else:
return n * factorial(n - 1)
raw_input returns a string, not an integer. Create an integer this way:
number = int(raw_input('Enter an integer= '))
The user might type something besides an integer, in which case you might want to handle that possibility.
while True:
try:
number = int(raw_input('Enter an integer= '))
except ValueError:
print "That wasn't an integer"
else:
break
using xxxxx.py
num=int(raw_input("Enter a number"))
n=1
while num>=0:
n=n*num
num=num-1
print "Factorial of the given number is: ",n

Categories

Resources