在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]
結論
我希望您喜歡本教程,如果您對本教程有任何疑問,請在評論區提出。
廣告