python - 无法在 for 循环中同时按升序和降序范围打印

标签 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) 

最佳答案

在代码中添加一个条件 if 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)

关于python - 无法在 for 循环中同时按升序和降序范围打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54741090/

相关文章:

c++ - for循环中使用的位操作

java - 在 Java 中使用 for 循环将元素从一个列表转移到另一个列表

javascript - 从对象动态创建元素

python - PySpark - RDD 中对象的时间重叠

python - 可以像 JavaScript 一样定义函数吗?

python - Google App Engine yaml 文件配置

python - Django 列表在 View 之间不会被破坏

excel - For循环从每一行复制值

python 3、pandas 和创建新列失败并出现 keyerror

c++ - FOR 循环语句中的 IF 语句?