📜  Python程序打印一个范围内的所有偶数

📅  最后修改于: 2022-05-13 01:55:19.048000             🧑  作者: Mango

Python程序打印一个范围内的所有偶数

给定起点和终点,编写一个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。如果条件满足,则仅打印数字。

Python3
for num in range(4,15,2):
  #here inside range function first no dentoes starting, second denotes end and third denotes the interval
    print(num)


Python3
# 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 = " ")


输出:

4 6 8 10 12 14 

示例 #2:从用户输入中获取范围限制

Python3

# 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