Python 2.7.5,在函数内使用循环并调用函数

时间:2013-11-26 20:10:22

标签: function python-2.7 input while-loop

我似乎无法多次显示用户输入。例如,如果输入是

Jeff 6

输出应为

Jeff
Jeff
Jeff
Jeff
Jeff
Jeff

我是Python新手,但到目前为止,这是我的代码:

def getName():
    name = raw_input("please enter name")
    return name

def getRepval():
    irepnum = float(raw_input("please enter number to show name entered"))
    return irepnum 

def inamed(name, irepnum): 
    count = 1 #the loop to show the name entered by the user
    while irepnum != count: 
        print name
        count += 1 #do I need to use return?? 

def main():  #having the main func like this gives me an infinite loop 
    irepnum = 0 

    iname = getName() #I think my problem is somewhere here. 

    irepnum = getRepval() 

    inamed(irepnum,name) 

main()

1 个答案:

答案 0 :(得分:1)

您需要像现在一样致电inamed(iname, irepnum),而不是inamed(irepnum, name)

除了name没有被定义的明显错误(实际变量被称为iname)之外,错误的顺序导致函数中的irepnum被设置为用户的字符串输入名称。由于count,无论多大,从不与传递的字符串相等,代码无限循环。

一些提示:

  • 学习使用for循环和xrange。你想要的成语是for count in xrange(irepnum):。 (使用它可以防止这个错误。)

  • 为您的标识符添加更多不同的名称。目前,您有一个inamed函数和一个iname变量。混乱。

  • 不要在int足够的地方使用花车。滥用花车是一件麻烦事。