在while循环中使用for循环

时间:2017-03-20 08:16:51

标签: python python-3.x loops

如何生成一些使用for循环而不是while循环计数的代码?我的代码如下;

def square():
    count = 1
    number = input("How far?")
    number = int(number)
    if number < 1:
        print ("broken")
    elif number >= 1:
        while count <= number:
            square = count*count
            print ("{0}*{0}={1}".format(count, square))
            count = count+1
square()

2 个答案:

答案 0 :(得分:1)

你可以这样做:

def square():
    number = input("How far?")
    number = int(number)
    if number < 1:
        print ("broken")
    elif number >= 1:
        for count in range(1,number+1):
            square = count*count
            print ("{0}*{0}={1}".format(count, square))
square()

使用

for count in range(1,number+1):

counts遍历值1,2,...,number

答案 1 :(得分:0)

U可以使用列表推导来完成:

def square():
    number = int(input("How far?"))
    # range will be from 1 to number +1, and will proceed square for all
    return [val ** 2 for val in range (1, number+1)]

squares = square()
if not squares:
    print('broken')
# u can iterate over result even if list is empty(if u pass broken number)
for val in squares:
    print ("{0}*{0}={1}".format(count, square))