简体   繁体   English

递归函数python,无法打印输出

[英]Recursive function python, cannot print an output

I have just started to program in python, and I am stuck with a problem regarding recursion. 我刚刚开始用python编程,而我遇到了有关递归的问题。

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. 您发布的代码定义了函数print_n但是从不调用它。 After the function definition place a print_n(s, n) . 在函数定义之后放置一个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). 完成此操作后,您会发现由n当前为字符串( raw_input返回一个字符串)这一事实引起的一些错误。 Use int(a_string) to convert a string to an integer. 使用int(a_string)将字符串转换为整数。 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)

尝试n = raw_input() -> n = int(raw_input())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM