-3

When num is not between 10-20, I need to decrease i value in else part. How can I do that?

Here is my code:

arr = []

for i in range(10,20):
    num = int(input("Enter Number: "))
    if num > 10 and num <= 20:
        arr.append(num)
    else:
        i = i - 1
print(arr)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
deKaV
  • 15
  • 4
  • 5
    Welcome to StackOverflow. Your question is unclear to me. What do you ultimately want to try to achieve? An array size 10 with numbers between 10 and 20 that are filled manually? Are you sure you need to decrease i, not num? Don't forget to add the changed number to the array as well. – luksch Sep 20 '20 at 09:39
  • 3
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). You should keep the loop as it is and not try to change `i`. In every iteration , independently, you ask for input until a desired number is entered – Tomerikoo Sep 20 '20 at 09:40
  • @YashShah Hi Yash, I need to get count between 10 and 20, It could be 0 to 10. But the answer is same, isn't it? – deKaV Sep 20 '20 at 09:41
  • Hi @luksch, Thank you. I'm sorry about my English. If the number is not between 10 and 20, I need to decrease i count and save next value in that i space. – deKaV Sep 20 '20 at 09:43
  • But you never use `i` so what will that change? Also what if the user puts 5 wrong numbers? you go back 5 spaces over numbers already appended... – Tomerikoo Sep 20 '20 at 09:51
  • Hi @Tomerikoo, This is what I need to do, Lets assume I inserted 22. But it is not in the range. So it doesn't add to the array. But value of "i" is increased by 1. So it go to next array space. I need to get next input to previous array space. – deKaV Sep 20 '20 at 09:58
  • 1
    Again, as I said, you don't even use `i`. The list method `append` always adds items at the end, so you don't need to worry about `i` – Tomerikoo Sep 20 '20 at 15:59

1 Answers1

1

Your loop cycles over a range of int numbers. Reducing the int i at the end of the loop does not help, since in the next loop cycle the next instance out of the range is taken as i.

You could solve this in different ways. One is mentioned by @Tomerikoo in the comments.

If you want to keep the loop construct similar to what you tried, you can do this:

arr = []
i = 0
while i < 10:
    num = int(input("Enter Number: "))
    i += 1
    if num > 10 and num <= 20:
        arr.append(num)
    else:
        i = i - 1
print(arr)

But you could also do without i:

arr = []
while len(arr)<10:
    num = int(input("Enter Number: "))
    if num > 10 and num <= 20:
        arr.append(num)
print(arr)

note that the programs do not gracefully react if non-integers are entered

luksch
  • 11,497
  • 6
  • 38
  • 53