简体   繁体   中英

Why isn't my if/else statment working in my range? (python)

start = int(input("Enter your starting value "))
end = int(input("Enter your ending value "))
inc = int(input("Enter your increment value "))

inc = int(input("Enter your increment value "))
for j in range (start,end,inc):
    if start > end:
        print("Nothing to show here!")
    else:
        print(j)

Instead of outputting "Nothing to show here," as it should. it just outputs the end value instead, It works perfectly fine otherwise. but I want to know why it doesn't output my quote.

If start is greater than end (and inc is positive), the range itself is empty; the loop never runs, so the test is never performed and the print doesn't happen. If you want a test like this, it needs to be outside the loop, eg:

if start > end:
    print("Nothing to show here!")
else:
    for j in range(start,end,inc):
        print(j)

Technically, this is wrong when inc is negative (there would be things to show when start > end ); if you need to handle that (in some cases you may know inc will always be >= 1 ), I'd probably just simplify to:

rng = range(start,end,inc)
if not rng:  # Test if the range is empty
    print("Nothing to show here!")
else:
    for j in rng:  # Iterate non-empty range
        print(j)

This happens because start will never be larger than end , even if the increment exceeds the value of end .

For example:

for i in range(1, 10, 100):
    print(i)

This code block will only run once and print the number 1. This happens because a for loop does 3 things.

First, it assigns the current index to the variable given. So it executes i = 1 Second, it checks if i < 10 . In the first iteration, that is true. So it prints 1 And third, it increments i . This means that after that iteration it executes i = 1 + 100

The third step in the next iterations overshadows the first step. That means that the assignment doesn't happen and that the incrementation is executed.

The other reason that this doesn't work, is because the end argument of range is exclusive. This means that the check the for loop makes in the second step is not a <= but a < . So even if the increment is 1, start will never have the same value of end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM