3-2-1 程序控制结构-while循环结构-多次求解一元二次方程?-while循环常见错误?

3-1-2 多分支结构(Chained)

一元二次方程

希望程序自动多次计算,然后输入‘q’退出循环


注:下一篇正式讲这个


引入while循环结构


while 循环继续条件:

缩进语句块(循环体)【体内要设定条件改变语句】

其余语句


1.只是将if改成while


例:打印字符串5次


count = 0

while count < 5:
    print 'programming is fun!'
    count += 1   

输入:

count = 0

while count < 5:
    print 'hello world!'
    count += 1  

输出:

hello world!
hello world!
hello world!
hello world!
hello world!

奋斗无法输入大写英文字母,只能黏贴,why


循环示例:

1+2+3+...+10

i = 1
s = 0

while i <= 10:
    s += i
    i += 1
    
print s


输出55



如果初始值i=0

依旧输出55

因为0+1+...+10


while循环常见错误:

1.没有修改循环条件(陷入死循环)

count = 0

while count < 10:
    print count

留意:

用control+c断掉循环


2.改错循环条件(陷入死循环)

count = 0

while count < 10:
    print count
    count -= 1

3.去掉缩进(陷入死循环)

count = 0

while count < 10:
    print count
count += 1

4.每次打印0,死循环

count = 0

while count < 10:
    if count % 2 == 0:
        print count

5.第一次输出0,之后死循环不输出

count = 0

while count < 10:
    if count % 2 == 0:
        print count
        count += 1

尝试后输出这个东西,没有输出0 奋斗why

  File "<ipython-input-14-47bda9674db8>", line 1, in <module>
    runfile('/Users/kousan/.spyder2/temp.py', wdir='/Users/kousan/.spyder2')


6.输出偶数

count = 0

while count < 10:
    if count % 2 == 0:
        print count
    count += 1

输出:

0
2
4
6
8


测验1-2求100以内所有偶数之和的程序

sum = 0
i = 0
while i < 100:
    if i % 2 == 0:
        sum += i
        i += 2
print sum

是正确的

2+2+2+...+2

循环可以一直继续













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值