返回总目录页

Python练习题

 

1、使用while循环输入1 2 3 4 5 6    8 9 10

1
2
3
4
5
6
i=0
while i<10:
    i=i+1
    if i==7:
        continue
    print(i)

  结果:

复制代码
E:\python\python>python test.py
1
2
3
4
5
6
8
9
10
复制代码

2、求1-100的所有数的和

1
2
3
4
5
6
i=0
sum=0
while i<100:
    i+=1
    sum =sum+i
print(sum)

  结果:

E:\python\python>python test.py
5050

3、输出 1-100 内的所有奇数

1
2
3
4
5
i=0
while i<100:
    i+=1
    if i%2==1:
        print(i)

  结果:

E:\python\python>python test.py
1
3
5
7
......
99

4、输出 1-100 内的所有偶数

1
2
3
4
5
i=0
while i<100:
    i+=1
    if i%2==0:
        print(i)

  结果:

E:\python\python>python test.py
2
4
6
......
100

5、求1-2+3-4+5 ... 99的所有数的和

1
2
3
4
5
6
7
8
9
i=0
sum=0
while i<99:
    i+=1
    if i%2==0:
        sum=sum-i
    if i%2==1:         #可用else:
        sum=sum+i
print(sum)

  结果:

E:\python\python>python test.py  #口算:1+(99-1)/2*1=50
50

6、用户登陆(三次机会重试)

1
2
3
4
5
6
7
8
9
10
11
12
13
sum=0
while sum<3:
    sum+=1
    username=input("请输入你的名字:")
    password=input("请输入你的密码:")
    if username=='ma' and password=='123456':
        print("您已经成功登录")
        break
    else:
        print("您输入的用户或密码有误")   
        print("---------------------------")
        print("")
        continue

  结果:

复制代码
E:\python\python>python test.py
请输入你的名字:ls
请输入你的密码:ls
您输入的用户或密码有误
---------------------------

请输入你的名字:ls
请输入你的密码:ls
您输入的用户或密码有误
---------------------------

请输入你的名字:ls
请输入你的密码:ls
您输入的用户或密码有误
---------------------------


E:\python\python>python test.py
请输入你的名字:ls
请输入你的密码:ls
您输入的用户或密码有误
---------------------------

请输入你的名字:ma
请输入你的密码:123456
您已经成功登录

E:\python\python>
复制代码

 7、

1
2
3
4
5
6
7
8
9
10
11
12
13
while 1:
    comment=input('请输入评论:')
    list=['粉嫩','铁锤']
    # for li in list:
    if comment in list:
        print('您输入的%s为敏感字符'%(comment))
    else:
        print('评论成功')
    select=input('请输入y继续评论:')
    if select == 'y' :
        continue
    else:
        break

  结果:

请输入评论:l
评论成功
请输入y继续评论:y
请输入评论:铁锤
您输入的铁锤为敏感字符
请输入y继续评论:n

Process finished with exit code 0

 8、字符串单个字符while打印

1
2
3
4
5
s='fdsafsdagfdsg'
i=0
while i<len(s):
    print(s[i])
    i += 1

  或

1
2
3
s='fdsafsdagfdsg'
for i in s:
    print(i)

  结果:

复制代码
f
d
s
a
f
s
d
a
g
f
d
s
g
复制代码

 

posted @   马昌伟  阅读(276)  评论(0编辑  收藏  举报
努力加载评论中...
博主链接地址:https://www.cnblogs.com/machangwei-8/
点击右上角即可分享
微信分享提示