表达式if ... else
一、用户登陆验证
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# 提示输入用户名和密码 # 验证用户名和密码 # 如果错误,则输出用户名或密码错误 # 如果成功,则输出 欢迎,XXX! #!/usr/bin/env python # -*- coding: encoding -*- _username = 'qian'_password = 'zxc123'
username = input("username:")
password = input("password:")
if _username == username and _password == password:
print("Welcome user {name} login...".format(name=username))
else:
print("Invalid username or password!")
|
二、猜年龄游戏
在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,如果错误,提示是猜大了还是小了,
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#!/usr/bin/env python # -*- coding: utf-8 -*- my_age = 26
guess_age = int(input("guess age:") )
if guess_age == my_age :
print("yes, you got it. ")
elif guess_age > my_age:
print("think smaller...")
else:
print("think bigger!")
|
二、while loop
有一种循环叫死循环
1
2
3
4
5
|
count = 0
while True :
print ( "死循环" ,count)
count + = 1
|
上面猜年龄用while 循环去实现: 只猜3次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#!/usr/bin/env python # -*- coding: utf-8 -*- count = 0
my_age = 26
while count < 3:
guess_age = int(input("guess age:") )
if guess_age == my_age :
print("yes, you got it. ")
break
elif guess_age > my_age:
print("think smaller...")
else:
print("think bigger!")
count +=1
else:
print("you have tried too many times..fuck off")
|
三、表达式for loop
最简单的循环5次
1
2
3
4
5
6
|
#_*_coding:utf-8_*_ __author__ = 'Many Qian'
for i in range ( 5 ):
print ( "loop:" , i )
|
输出:
1
2
3
4
5
|
loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
|
需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环
1
2
3
4
|
for i in range ( 10 ):
if i< 5 :
continue #不往下走了,直接进入下一次loop
print ( "loop:" , i )
|
需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出
1
2
3
4
|
for i in range ( 10 ):
if i> 5 :
break #不往下走了,直接跳出整个loop
print ( "loop:" , i )
|
用上面学的for循环做猜年龄:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#!/usr/bin/env python # -*- coding: utf-8 -*- my_age = 26
for i in range(3):
guess_age = int(input("guess age:") )
if guess_age == my_age :
print("yes, you got it. ")
break
elif guess_age > my_age:
print("think smaller...")
else:
print("think bigger!")
else:
print("you have tried too many times..fuck off")
|