Python-For循环,在单独的一行上打印每个数字及其平方

Python-For循环,在单独的一行上打印每个数字及其平方,python,list,for-loop,printing,integer,Python,List,For Loop,Printing,Integer,我有一个数字列表: nums = [12, 10, 32, 3, 66, 17, 42, 99, 20] 我的第一个任务是将每个数字打印在新行上,如下所示: 12 10 32 3 66 17 42 99 20 The square of 12 is 144 The square of 10 is 100 The square of 32 is 1024 The square of 3 is 9 The square of 66 is 4356 The square of 17 is 289

我有一个数字列表:

nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
我的第一个任务是将每个数字打印在新行上,如下所示:

12
10
32
3
66
17
42
99
20
The square of 12 is 144
The square of 10 is 100 
The square of 32 is 1024
The square of 3 is 9
The square of 66 is 4356
The square of 17 is 289
The square of 42 is 1764
The square of 99 is 9801
The square of 20 is 40
我可以通过创建一个for循环来打印列表中的整数:

nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
    print(i)
现在我需要编写另一个for循环,将每个数字及其平方打印到新行上,如下所示:

12
10
32
3
66
17
42
99
20
The square of 12 is 144
The square of 10 is 100 
The square of 32 is 1024
The square of 3 is 9
The square of 66 is 4356
The square of 17 is 289
The square of 42 is 1764
The square of 99 is 9801
The square of 20 is 40
到目前为止,我实际上已经能够打印出平方值,但无法单独在单独的行中获得它们。我还需要去掉值周围的括号

我的尝试:

导致:


我需要去掉括号,每行只需要包含一个与左边整数对应的平方值。我该怎么做呢?

我不确定您是否真的想要跟踪这些方块,或者这只是您打印这些方块的努力的一部分

nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
    print(i**2)
假设您确实想要跟踪这些方块,那么一个小的变化是:

这允许您准备好使用当前方块,而无需从阵列中引用它

如果确实要从数组中引用平方值,则应使用负索引从数组末尾获取:


为什么要建立一个列表?为什么不在创建的第一个循环中使用print来同时打印i*i结果呢?按照第一个示例中的相同方法,只在循环中打印:打印i,is,i*i的平方。您不需要在新列表中收集值。我不知道为什么我没有想到这一点-是的,它按预期工作,谢谢!欢迎来到StackOverflow!您应该描述您发布的任何代码,以便询问者和社区能够更好地理解它,无论它有多小。使用负索引,每平方结果为400,但您的第一块代码符合我的要求。除此之外,有没有办法不使用逗号打印结果?我现在得到的是's square of',12,'s',144,如果我尝试这样做:print The square of+I+is+sqr,我会得到错误消息:TypeError:无法连接'str'和'int'对象知道如何解决这个问题吗@我为此道歉。我仍然部分处于Python 2的精神状态。我已经将代码更新为Python3,修复了第二块中的一个bug,并添加了一些在线演示。谢谢,它现在工作得很好。你能解释一下吗?当你说{}的平方是{}.formati,sqr时,看起来你在做字符串替换?你用{}替换的值是i和sqr……那么squared.appendsqr行就是确保我们在数组中的当前平方上的东西?这样,每当您在print语句中引用sqr时,它就知道每次都要打印出下一个平方值?对吗?@HappyHands31 squared除了用于存储未来未编写的代码外,什么都不用。sqr跟踪当前的平方值,然后将其用于附加到数组和组合成字符串。每次通过循环使用当前值i.重新初始化sqr。
nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
    print(i)

squared = [ ]

for i in nums:
    sqr = i * i
    squared.append(sqr)
    print("The square of {} is {}".format(i, sqr))
nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
    print(i)

squared = [ ]

for i in nums:
    squared.append(i*i)
    print("The square of {} is {}".format(i, squared[-1]))
nums = (12, 10, 32, 3, 66, 17, 42, 99, 20)

for i in nums:
    print(i)

for i in nums:
    print("the square of",i,"is", i**2)