Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在while循环上使用for循环_Python_Python 3.x_Loops - Fatal编程技术网

Python 在while循环上使用for循环

Python 在while循环上使用for循环,python,python-3.x,loops,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 = cou

如何使用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()

你可以这样做:

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()

计数在值1,2,…,number上进行迭代。

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))

你读过Python文档中关于for循环的内容吗?
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))