简体   繁体   English

python for 循环不会改变值

[英]python for loop wont change value

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所以我是 python 的新手,这个问题对这里的任何人来说都应该是相当容易的,除了我很明显哈哈,所以这是我的代码

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所以你可能会想,如果有人输入的数字大于 9 或小于 0,我只希望我的 c 保持原样,所以我从 1-9 得到 20 个正数,而不是它不会这样做,而且它会继续增加,即使我有 c-=1 的东西在那里

First, do not use range(0,20) but range(20) instead.首先,不要使用 range(0,20) 而是使用 range(20) 。

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.这意味着,当您执行 c-=1 时,您不会 go 回到迭代器中,您会减少迭代器返回的数字。 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.这意味着如果 c=5 并且您在输入中输入的数字是 20,则 c 将变为 4,但当返回循环开始时,c 将变为 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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