在Python中不使用任何循环打印n的m个倍数
在本教程中,我们将编写一个程序,无需使用循环即可找出数字n的m个倍数。例如,我们有一个数字**n = 4**和**m = 3**,输出应为**4, 8, 12**。四个的三个倍数。这里,主要限制是不使用循环。
我们可以使用**range()**函数在不使用循环的情况下获得所需的输出。range()函数的作用是什么?**range()**函数返回一个范围对象,我们可以将其转换为迭代器。
让我们看看**range()**的语法。
语法
range(start, end, step)
算法
start - starting number to the range of numbers end - ending number to the range of numbers (end number is not included in the range) step - the difference between two adjacent numbers in the range (it's optional if we don't mention then, it takes it as 1) range(1, 10, 2) --> 1, 3, 5, 7, 9 range(1, 10) --> 1, 2, 3, 4, 5, 6, 7, 8, 9
示例
## working with range() ## start = 2, end = 10, step = 2 -> 2, 4, 6, 8 evens = range(2, 10, 2) ## converting the range object to list print(list(evens)) ## start = 1, end = 10, no_step -> 1, 2, 3, 4, 5, 6, 7, 8, 9 nums = range(1, 10) ## converting the range object to list print(list(nums))
输出
如果您运行上述程序,您将获得以下结果。
[2, 4, 6, 8] [1, 2, 3, 4, 5, 6, 7, 8, 9]
现在,我们将编写我们的程序代码。让我们先看看步骤。
算法
现在,我们将编写我们的程序代码。让我们先看看步骤。
1. Initialize n and m. 2. Write a range() function such that it returns multiples of n. 3. Just modify the step from the above program to n and ending number to (n * m) + 1 starting with n.
请看下面的代码。
示例
## initializing n and m n = 4 m = 5 ## writing range() function which returns multiples of n multiples = range(n, (n * m) + 1, n) ## converting the range object to list print(list(multiples))
输出
如果您运行上述程序,您将获得以下结果。
[4, 8, 12, 16, 20]
结论
我希望您喜欢本教程,如果您对本教程有任何疑问,请在评论区提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP