给定起点和终点, 编写Python程序以打印该给定范围内的所有偶数。
例子:
Input: start = 4, end = 15
Output: 4, 6, 8, 10, 12, 14
Input: start = 8, end = 11
Output: 8, 10
范例1:使用for循环打印给定列表中的所有偶数
定义范围的开始和结束限制。使用for循环从头开始迭代直到列表中的范围, 并检查num%2 ==0。如果条件满足, 则仅打印数字。
# Python program to print Even Numbers in given range
start, end = 4 , 19
# iterating each number in list
for num in range (start, end + 1 ):
# checking condition
if num % 2 = = 0 :
print (num, end = " " )
输出如下:
4 6 8 10 12 14 16 18
范例2:
从用户输入获取范围限制
# Python program to print Even Numbers in given range
start = int ( input ( "Enter the start of range: " ))
end = int ( input ( "Enter the end of range: " ))
# iterating each number in list
for num in range (start, end + 1 ):
# checking condition
if num % 2 = = 0 :
print (num, end = " " )
输出如下:
Enter the start of range: 4
Enter the end of range: 10
4 6 8 10
注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。