简体   繁体   English

当真正的循环不起作用时在里面增加

[英]Increment inside while true loop doesnt work

x=0

def add(var):

    var+=1
    return var

while True:

    y = add(x)
    print(y)

This code gives output only as 1 for every iteration.此代码在每次迭代中仅将 output 设为 1。 But I need this code to increment the value, with the same code(architecture).但我需要这段代码来增加值,使用相同的代码(架构)。

you can try this code你可以试试这段代码

i = 1
def add(var):
    var+=1
    return var
    
while True:
  print(i)
  i = add(i)

You may try this...你可以试试这个...

x=0 
def add(var): 
    var+=1 
    return var 
while True: 
    x = add(x) 
    print(x)

Try this尝试这个

def add(var):
    var+=1
    return var
x = 0
while True:
    y = add(x)
    print(x)

You can define y outside the loop, then add it to y您可以在循环外定义y ,然后将其添加到y

Or just do this:或者只是这样做:

y = 0
while True:
    print(y)
    y += 1

You can use a for-loop instead too.您也可以使用 for 循环。

for i in range(100): # whatever number you want to loop.
    print(i)

You keep passing x = 0, so it will always print 1. Try replacing x with y instead.你一直在传递 x = 0,所以它总是会打印 1。尝试用 y 替换 x。

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

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