我正在做的事情"艰难地学习Python"并且我坚持使用while循环

时间:2015-07-06 19:30:23

标签: python while-loop

本章末尾的学习练习要求我创建一个函数,该函数调用一个while循环,该循环将在用户决定的时间间隔内计算,但我不断得到无限循环。如果我用数字替换x,它将结束,但如果我把它保留为x,据我所知,它不会从用户注册raw_input()。

def counting_up():
    i = 0
    numbers = []
    print "Where do you want to end?"
    x = raw_input(">")

    print "How much would you like to increment by?"
    a = raw_input(">")

    while i < x:
        print "At the top, i is %d." % i
        numbers.append(i)

        i = i + a
        print "Numbers now: ", numbers
        print "At the bottom, i is %d." % i

        print "Your numbers: ", numbers
        for num in numbers:
            print num
counting_up()

1 个答案:

答案 0 :(得分:0)

当您从x函数获得raw_input()时,它会将其存储为字符串。然后,当您尝试将数字i与字符串x进行比较时,如果2是数字,它将不会按照它的方式运行。

尝试将变量转换为整数,以便将它们作为数字进行比较。

while i < int(x):
    #code

但是,因为您现在将输入转换为整数,所以如果用户的输入不是数字形式,程序将抛出错误。你可以假设他们会给你正确的输入,或者像这样做一些错误检查:

x = raw_input(">")
try:
    x = int(x)
except Exception as e:
    print "You have to input a number!"
    exit()
相关问题