使用迭代打印从1到10的表的函数 def tablesOneToTen():#一个将从1-10打印乘法表的函数 x=1 y=1 对于这类迭代任务,您最好使用For循环,因为您已经知道了要处理的边界,Python还使创建For循环变得特别容易
使用使用迭代打印从1到10的表的函数 def tablesOneToTen():#一个将从1-10打印乘法表的函数 x=1 y=1 对于这类迭代任务,您最好使用For循环,因为您已经知道了要处理的边界,Python还使创建For循环变得特别容易,python,python-3.x,while-loop,iteration,Python,Python 3.x,While Loop,Iteration,使用while循环,您必须使用条件检查您是否在范围内,同时显式增加计数器,这样更容易出错 由于您知道需要乘法表来计算x和y的值,范围从1-10,为了熟悉循环,您可以为循环创建两个: def tablesOneToTen(): # a function that will print out multiplication tables from 1-10 x = 1 y = 1 while x <= 10 and y <= 12: f = x
while
循环,您必须使用条件检查您是否在范围内,同时显式增加计数器,这样更容易出错
由于您知道需要乘法表来计算x
和y
的值,范围从1-10
,为了熟悉循环,您可以为循环创建两个:
def tablesOneToTen(): # a function that will print out multiplication tables from 1-10
x = 1
y = 1
while x <= 10 and y <= 12:
f = x * y
print(f)
y = y + 1
x = x + 1
tablesOneToTen()
运行此命令将为您提供所需的表:
def tablesOneToTen(): # a function that will print out multiplication tables from 1-10
# This will iterate with values for x in the range [1-10]
for x in range(1, 11):
# Print the value of x for reference
print("Table for {} * (1 - 10)".format(x))
# iterate for values of y in a range [1-10]
for y in range(1, 11):
# Print the result of the multiplication
print(x * y, end=" ")
# Print a new Line.
print()
对于while
循环,逻辑是类似的,但当然比它需要的更详细,因为您必须初始化、计算条件和增量
作为其丑陋性的证明,while
循环的外观如下:
Table for 1 * (1 - 10)
1 2 3 4 5 6 7 8 9 10
Table for 2 * (1 - 10)
2 4 6 8 10 12 14 16 18 20
Table for 3 * (1 - 10)
3 6 9 12 15 18 21 24 27 30
def tablesoneten():
#初始化x计数器
x=1
#第一个条件
而x使用python3
def tablesOneToTen():
# initialize x counter
x = 1
# first condition
while x <= 10:
# print reference message
print("Table for {} * [1-10]".format(x))
# initialize y counter
y = 1
# second condition
while y <=10:
# print values
print(x*y, end=" ")
# increment y
y += 1
# print a new line
print(" ")
# increment x
x += 1
或:
输出:
for i in range(1, 10+1):
for j in range(i, (i*10)+1, i):
print(j, end="\t")
print()
希望它能帮助您获得1到10个表格。从直接缩进开始:x
在循环中从不更改,至少在代码已发布的情况下。您需要两个循环x
需要再次从1
开始。欢迎来到stackoverflow。除了您提供的答案,请考虑提供一个简要解释为什么以及如何修复这个问题。
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
a = [1,2,3,4,5,6,7,8,9,10]
for i in a:
print(*("{:3}" .format (i*col) for col in a))
print()