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)
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
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.