使用迭代从1到10打印出表的函数

时间:2015-11-09 01:07:35

标签: python python-3.x while-loop iteration

#Get amount of principal, apr, and # of years from user
princ = float(input("Please enter the amount of principal in dollars "))
apr = float(input("Please enter the annual interest rate percentage "))
years = int(input("Please enter the number of years to maturity "))

#Convert apr to a decimal
decapr = apr / 100

#Use definite loop to calculate future value
for i in range(years):
    princ = princ * (1 + decapr)
    print('{0} {1:.2f}'.format(i, princ))

我正在尝试创建一个函数,它将从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() 的乘法表中给出值。

除了嵌套的1-10循环之外,我是否应该添加ifelif语句以使此代码有效?

3 个答案:

答案 0 :(得分:1)

对于这类迭代任务,您最好使用for循环,因为您已经知道您正在使用的边界,Python也会创建{ {1}}循环特别容易。

使用for循环时,您必须使用条件检查您是否在范围内,同时还明确增加计数器,从而更有可能犯错误。

由于您知道需要whilex值的乘法表,范围从y,为了让您熟悉循环,请创建两个1-10循环:

for

运行此选项将为您提供所需的表格:

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

使用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 循环,逻辑类似但当然只是比它需要的更冗长,因为你必须初始化,评估条件和增量。

作为其丑陋的证明,while循环看起来像这样:

while

答案 1 :(得分:0)

使用defaultConfig

Python 3

或:

for i in range(1, 10+1):
    for j in range(i, (i*10)+1):
        if (j % i == 0):
            print(j, end="\t")
    print()

输出:

for i in range(1, 10+1):
    for j in range(i, (i*10)+1, i):
            print(j, end="\t")
    print()

希望它能帮助您获得1到10张桌子。

答案 2 :(得分:0)

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