简体   繁体   English

如何使用 for 循环和 range() python 中的 function 制作一个打印数字倍数的脚本

[英]How to make a script that prints the multiples of a number using a for loop and range() function in python

The multiples of number is when you add that number to it self multiple times.数字的倍数是当您多次将该数字添加到它自己时。 range() generates a sequence of integer numbers. range() 生成一系列 integer 数字。 It can take one, two, or three parameters:它可以采用一个、两个或三个参数:

range(n): 0, 1, 2, ... n-1 range(x,y): x, x+1, x+2, ... y-1 range(p,q,r): p, p+r, p+2r, p+3r, ... q-1 (if it's a valid increment).范围(n): 0, 1, 2, ... n-1 范围(x,y): x, x+1, x+2, ... y-1 范围(p,q,r): p , p+r, p+2r, p+3r, ... q-1 (如果它是一个有效的增量)。

What you want is already implemented by the range function in python.您想要的已经由 python 中的 function range实现。

You can read its documentation here .您可以在此处阅读其文档。

This code with print all the multiples a given number x , n times此代码打印给定数字xn次的所有倍数

x = 2
n = 5
multiples = [x * i for i in range(1, n+1)]
print(multiples)

output: output:

[2, 4, 6, 8, 10]

This can be accomplished range itself - by setting third argument same as first, assuming that you want to get 10 multiplies of 3 you can do:这可以通过range本身来完成 - 通过设置与第一个参数相同的第三个参数,假设您想要获得310次乘法,您可以这样做:

n = 3
k = 10
mult = list(range(n, (n*k)+1, n))
print(mult)  # [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

Note that due to first argument being inclusive and second being exclusive I need to add 1 to n*k , otherwise I would get 9 instead of 10 numbers.请注意,由于第一个参数是包容性的,第二个是独占性的,我需要将1添加到n*k ,否则我会得到 9 而不是 10 个数字。 Keep in mind that range is designed for integer numbers.请记住,范围是为 integer 数字设计的。

def the_multiples_of_number(start_number,end_number,the_number_you_want_to_the_multiples):
    for x in range(start_number,end_number,the_number_you_want_to_the_multiples):
        print(x)

the_multiples_of_number(0,100,7) #it should prints out the multiples of 7 between 0 & 100 the_multiples_of_number(0,100,7) #它应该打印出 0 和 100 之间 7 的倍数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM