-1

So im new to python and this question should be fairly easy for anybody in here except me obvisouly haha so this is my code

for c in range(0,20):
    print("number",c+1)
    number = input ("Enter number:\n")
    number = int(number)
    if (number < 1 or number > 9):
        print("try again by inputing a positive number < 10")
        c -=1

so as you may think if the number someone inputs is bigger than 9 or smaller than 0 i just want my c to stay where it is so i get 20 positive numbers from 1-9 instead it doesnt do that and it keeps increasing even tho i have the c-=1 thingy down there

Steve
  • 13
  • 3
  • 5
    Does this answer your question? [How to change index of a for loop?](https://stackoverflow.com/questions/14785495/how-to-change-index-of-a-for-loop) – Błotosmętek May 11 '20 at 10:44

2 Answers2

1

First, do not use range(0,20) but range(20) instead.

Second, range returns an iterator. This means, that when you do c-=1 you do not go back in the iterator, you decrease the number returned by the iterator. Meaning that if c=5 and the number you entered in input is 20, c will become 4, but when returning to the start of the loop, c be be 6.

You probably want something of this sort:

c = 0
while c < 20:
    print("number",c+1)
    number = input ("Enter number:\n")
    number = int(number)
    if (number < 1 or number > 9):
        print("try again by inputing a positive number < 10")
        continue
    c += 1
bgmoshe
  • 61
  • 6
0

an alternative and simple solution to this would be:

i=20
while(i!=0):
    number = input("Enter number:\n")
    number = int(number)
    if (number <1 or number >9):
       print("Invalid no try within 0-9 ")
    else
       print(number) 
       i-=1