Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用while循环迭代一系列整数_Python_Loops - Fatal编程技术网

Python 使用while循环迭代一系列整数

Python 使用while循环迭代一系列整数,python,loops,Python,Loops,如何重写第一个代码以使用while循环而不是给定的for循环?两个程序的输出应该相同 num = 500 for j in range(30, 100): if j > 70: num = num – 5 else: num = num + 2 print(num) print("program output is", num) 我已尝试过此方法,但无法正常工作: num = 5

如何重写第一个代码以使用while循环而不是给定的for循环?两个程序的输出应该相同

num = 500
for j in range(30, 100): 
     if j > 70:
         num = num – 5   
     else:    
         num = num + 2    
     print(num)
print("program output is", num)
我已尝试过此方法,但无法正常工作:

num = 500
while j > 30 and j < 100: 
     if j > 70:
         num = num – 5   
     else:    
         num = num + 2    
     print(num)
for循环在每次迭代中自动更新循环变量j

然而,在while循环中,您必须自己为变量指定一个新值,否则循环将永远不会结束

一个类似循环的

for j in range(a, b):
    # do something ...
相当于此while循环:

请阅读介绍,并复习以了解社区期望。堆栈溢出不是一项免费的编码服务,因此,向我展示如何解决这类问题一般都不受欢迎。您必须展示自己在解决问题方面所做的努力,然后就您的实现中存在的不足提出一个具体的问题。
j = a
while j < b:
    # do something ...
    j += 1
num = 500
j = 30
while j < 100:
     if j > 70:
         num = num – 5
     else:
         num = num + 2
     print(num)
     j += 1
print("program output is", num)