我刚开始用python编程,我遇到了关于递归的问题.
该程序似乎编译,但是,未显示打印输出.
这是程序:
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)
我得到的输出是:
xxxx@xxxx-Satellite-L600:~/Desktop$ python 5exp3.py
type s string
hello
add the number of recursions
4
xxxx@xxxx-Satellite-L600:~/Desktop$
有什么问题,如何让程序显示输出?
您发布的代码定义了该函数print_n但从不调用它.函数定义后放置一个print_n(s, n).
执行此操作后,您将发现由n当前字符串(raw_input返回字符串)引起的一些错误.使用int(a_string)字符串转换为整数.像这样调用你的函数将解决这个问题
print_n(s, int(n))
或者做
n = int(raw_input())
完整的代码:
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)