关于python 的while的用法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于python 的while的用法相关的知识,希望对你有一定的参考价值。
L=[1,2,4,8,16,32,64] #定义一个列表
x=5 #把5赋予x(这样x是全局的)
found=i=0 #把0赋予found和i
while not found and i<len(L): (这句完全不懂)
if 2**x==L[i]: (L[i]是什么意思)
found=1 (不懂)
else:
i=i+1 (这个我遇到多次了,有点不明白)
if found: (found有是什么)
print 'at index', i #输出字符串‘at index’和i人值
else:
print x, 'not found ' #输出x的值和字符串'not found'
上面的代码我把我明白的标了注释,有可能不对,请指出。
不明白的说了原因。请朋友们帮忙说一下标出来。
while循环语句和for语句都是Python的主要循环结构。while语句是Python中最通用的迭代结构,也是一个条件循环语句。
while循环语句的语法如下所示:
while 条件:
执行代码块
while循环中的执行代码块会一直循环执行,直到当条件不能被满足为假False时才退出循环,并执行循环体后面的语句。while循环语句最常被用在计数循环中。
举一个最简单的,来看看while循环控制流语句基本用法是怎么样的。
x = 0while x<5:
print x,
x+=1
# 0,1,2,3,4
变量x的初始值为1,条件是x小于10的情况时,执行代码块x+=1的操作,直到x的值不再小于10。
while循环语句和for语句一样,也是常搭配break、continue、else一起使用,可以完成更多重条件的要求。
x=5 #把5赋予x(这样x是全局的)
found=i=0 #把0赋予found和i
while not found and i<len(L): (这句完全不懂)### 意思如果found为假且i的值在L的长度之内,就循环
if 2**x==L[i]: (L[i]是什么意思)### L[i]代表取L的第i个值,L[0]就是1,L[2]就是4,L[3]得8
found=1 (不懂)### 给变量found赋值1
else:
i=i+1 (这个我遇到多次了,有点不明白)### 意思是 i增1,执行前如果i为1,执行后i就等于2
if found: (found有是什么)### 如果i为真(不等于0就是真),就打印下面的
print 'at index', i #输出字符串‘at index’和i人值
else: ### 如果i为假
print x, 'not found ' #输出x的值和字符串'not found'本回答被提问者采纳
关于python的for循环
ten_thing = "Apple Orange Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_thing.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"There are len(stuff) items now.")
各位大神吗,上面的那段while的循环如果用for语句写应该怎么写?
怎么复制老师把缩进吃掉。。。
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_thing.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "boy"]
def test():
n=0
for i in stuff:
n=n+1
if n!=10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"There are len(stuff) items now.")
return test()
test()
非要用个for的话··我只能想到这个办法了···
参考技术A python里边while循环,除了简单的i < n这一类的可以用for in range(n)替代,其他的是没法用for替换的,或者说很难替换,它和c语言一类的里边的for是两回事以上是关于关于python 的while的用法的主要内容,如果未能解决你的问题,请参考以下文章