无法在for循环中的升序和降序范围内打印

时间:2019-02-18 05:46:08

标签: python for-loop

我正在尝试在for循环中创建if else规则,但是当前仅在起始值小于结束值时才打印这些值。如果起始值大于终止值,我希望范围以降序打印。

我尝试了几种不同的选项,但是理想情况下,我试图仅使用两个for循环来创建代码。

for i in range(x,y+1):
    if (x<=y):
      print(i) 
    else:
     for i in range(y,x,-1):
      print(i)
count_odd = 0 
count_even = 0 
for n in range(x,y+1):
        if   n%2==0: 
             count_even = count_even+1 
        else: 
             count_odd = count_odd+1 
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd) 

2 个答案:

答案 0 :(得分:3)

如果x<y在代码中放入条件,并相应地使用range升序或降序:

x = 10
y = 2
count_odd = 0 
count_even = 0 
if x < y:
    for n in range(x,y+1):
        if n%2==0: 
            count_even = count_even+1 
        else: 
            count_odd = count_odd+1 
else:
    for n in range(x, y-1, -1):
        if n%2==0: 
            count_even = count_even+1 
        else: 
            count_odd = count_odd+1 

print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd) 

输出:

Number of even numbers : 5                                                                                                            
Number of odd numbers : 4 

修改

您的for初始循环应为:

if (x<=y):
    for i in range(x,y+1):
        print(i) 
else:
    for i in range(x,y-1,-1):
        print(i)

答案 1 :(得分:2)

您需要以不同的方式处理它们,并在条件出现时调用特定的函数。这是一个例子。

x = 1
y = 10


def descOrder(x,y):
    count_even = 0
    count_odd = 0
    for i in range(x, y-1, -1):
        if i % 2 == 0:
            count_even = count_even + 1
        else:
            count_odd += 1
        print(i)
    print ("Even:",count_even, "Odd:",count_odd)


def asceOrder(x, y):
    count_even = 0
    count_odd = 0
    for i in range(x ,y+1):
        if i % 2 == 0:
            count_even += 1
        else:
            count_odd += 1
        print(i)
    print ("Even:",count_even, "Odd:",count_odd)


if x > y:
    descOrder(x, y)
else:
    asceOrder(x, y)