IF 条件判断语句
单分支结构: 单分支结构的判断是最简单的一种形式,如果满足条件则执行,否则跳过IF语句.
import sys
num = 0
if num == 0:
print("数值确实等于零!")
双分支结构: 双分支用来判断两种不同的情况,比如要么为真要么为假.
import sys
num=0
if num == 0:
print("数值确实等于零!")
else:
print("你在逗我吗,这不是零,皮一下很开心!")
多分支结构: 多分枝结构用来判断大多数情况,其给予每个结果一个返回值.
import sys
score = 88.8
level = int(score % 10)
if level >= 10:
print('Level A+')
elif level == 9:
print('Level A')
elif level == 8:
print('Level B')
elif level == 7:
print('Level C')
elif level == 6:
print('Level D')
else:
print('Level E')
模拟登陆(1): 模拟用户登录小实验,输入密码必须不显示.
import sys
import getpass
name=input("输入用户名:")
pwd=getpass.getpass("请输入密码:")
if name == "lyshark" and pwd=="123123":
print("欢迎,lyshark,登陆!")
else:
print("用户名或密码错误!")
猜数字游戏(2): 猜数字小游戏,输入参数返回指定结果.
# -*- coding: utf-8 -*-
import sys
my_num = 38
user_input = int(input("输入一个数字:"))
if user_input == my_num:
print("你猜对了!")
elif user_input < my_num:
print("猜小了!")
else:
print("猜大了!")
## WHILE 循环语句
死循环: 演示一个死循环的小例子.
import os
count = 0
while True:
print("这是一个死循环...",count)
count +=1
循环打印: 循环打印0-9这几个数字,且结果不要换行,在一行中输出.
import os
count = 0
while count <= 9:
print(count, end=' ')
count += 1
中断循环: 演示一个while循环被中断的情况.
import os
count = 0
while count <=9:
print(count, end=' ')
if count == 5:
break
count += 1
else:
print('end')
实例1: 打印指定字符串,循环打印其中的每一个元素,并每次递减.
import os
url="www.baidu.com"
while url:
print(url)
url=url[1:]
#--输出结果-------------------------
www.baidu.com
ww.baidu.com
w.baidu.com
.baidu.com
baidu.com
aidu.com
idu.com
du.com
u.com
.com
com
om
m
实例2: 循环打印一些数据,这里打印0-9
并每次递增.
import os
x=0;y=10
while x<y:
print(x)
x+=1
#--输出结果-------------------------
0
1
2
3
4
5
6
7
8
9
实例3: 打印一个字符串,循环打印,打印完成后输出game over
.
import os
url="www.baidu.com"
while url:
print(url)
url=url[:-1]
else:
print("game over")
#--输出结果-------------------------
www.baidu.com
www.baidu.co
www.baidu.c
www.baidu.
www.baidu
www.baid
www.bai
www.ba
www.b
www.
www
ww
w
game over
实例4: 逐一显示指定列表中的所有元素,这里有三种方法.
>>> list=[1,2,3,4,5,6]
>>> count =0
>>>
>>> while list:
... print(list[0])
... list.pop(0)
...
>>> list=[1,2,3,4,5,6]
>>> while list:
... print(list[-1])
... list.pop()
...
>>> list=[1,2,3,4,5,6]
>>> while count < len(list):
... print(list[count])
... count+=1
...
实例5: 求100以内所有偶数之和,使用嵌套判断.
>>> num=0
>>> sum=0
>>> while num <=100:
... if num %2 ==0:
... sum=sum+num
... else:
... pass
... num=num+1
实例6: 逐一显示指定字典的所有键,并于显示结束后说明总键数.
>>> d1 = {'x':1,'y':23,'z':78}
>>> keylists = d1.keys()
>>> while keylists:
print(keylists[0])
keylists.pop[0]
else:
print(len(d1))
实例7: 创建一个包含了100以内所有奇数的列表.
>>> l1 = []
>>> x = 1
>>> while x < 100:
l1.append(x)
x += 2
实例8: 列表l1 = [0,1,2,3,4,5,6]
,列表l2 = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
,以第一个列表中的元素为键,以第二个列表中的元素为值生成新字典d1
.
>>> l1 = [0,1,2,3,4,5,6]
>>> l2 = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> d1 = {}
>>> count = 0
>>> if len(l1) == len(l2):
while count < len(l1):
d1[l1[count]] = l2[count]
count += 1
>>> print(d1)
实例9: 循环并打印相关文字,当到达100次的时候退出.
count = 0
while True:
print("hello lyshark:",count)
count +=1
if count == 100:
print("break")
break
实例10: 模拟登陆小程序,程序启动要求输入密码,并判断如果次数小于3次则登陆成功,否则禁止登陆.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import getpass
import os
name = "lyshark"
pwd = "123123"
count = 0
while True:
if count < 3:
print("请输入用户名和密码:")
username = input("用户名:")
password = getpass.getpass("密码:")
if username == name and password == pwd:
print("恭喜你登陆成功!")
break
else:
print("登陆失败!用户名或者密码错误")
else:
print("你已经输错3次,正在退出....")
break
count += 1
## FOR 循环遍历语句
列表遍历: 通过使用for循环打印一个list列表中的元素.
import os
names = ["tom","admin","lyshark","jack"]
for x in names:
print(x)
列表迭代: 对于一个序列来说,也可以通过索引进行迭代.
import os
names = ["tom","admin","lyshark","jack"]
for x in range(len(names)):
print(names[x])
打印序列: 通过for循环,遍历并打印一个序列.
import os
T = [(1,2),(3,4),(5,6),(7,8)]
for (a,b) in T:
print(a,b)
循环遍历: 遍历0-9范围内的所有数字,并通过循环控制语句打印出其中的奇数.
import os
for i in range(10):
if i % 2 == 0:
continue
print(i, end=' ')
循环遍历: 通过循环控制语句打印一个列表中的前3个元素.
import os
names = ['Tom', 'Peter', 'Jerry', 'Jack', 'Lilly']
for i in range(len(names)):
if i >= 3:
break
print(names[i])
循环遍历: 通过for循环打印99乘法表.
import os
for j in range(1, 10):
for i in range(1, j+1):
print('%d*%d=%d' % (i, j, i*j), end=' ')
i += 1
print()
j += 1
range()函数: 通过使用range函数,每隔一定的个数元素挑选一个元素.
>>> string="hello world my name lyshark"
>>> for i in range(0,len(string),2):
... print(string[i])
range()函数: 通过range遍历,修改列表元素,在原来元素的基础上修改元素.
>>> list=[1,2,3,4,5]
>>> for i in range(len(list)):
... list[i]+=1
...
>>> list
[2, 3, 4, 5, 6]
zip()函数: zip函数常用于动态的构造字典.
>>> L1 = [1,2,3,4,5]
>>> L2 = ['a','b','c','d','e',]
>>> zip(L1,L2)
>>>
>>> keys = [1,2,3,4,5,6,7]
>>> vaules = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> D = {}
>>> for (k,v) in zip(keys,values)
D[k] = v
>>> D
实例1: 逐一分开显示指定字典d1中的所有元素,也就是字典遍历打印.
>>> d1 = {'x':123,'y':321,'z':734}
>>> for (k,v) in d1.items():
print(k,v)
y 321
x 123
z 734
实例2: 逐一显示列表中l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
中索引为奇数的元素.
>>> l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>>
>>> for i in range(1,len(l1),2):
print(l1[i])
实例3: 将属于列表l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
,但不属于列表l2=['Sun','Mon','Tue','Thu','Sat']
的所有元素定义为一个新列表l3
,并加入到其中.
>>> l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
>>> l2=['Sun','Mon','Tue','Thu','Sat']
>>> l3 = []
>>> for i in l1:
>>> if i not in l2:
>>> l3.append(i)
实例4: 将属于列表namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7']
,删除列表removelist=['stu3','stu7','stu9']
,请将属于removelist列表中的每个元素从namelist中移除(属于removelist,但不属于namelist的忽略即可).
>>> namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7']
>>> removelist=['stu3','stu7','stu9']
>>> for i in removelist:
>>> if i in namelist:
>>> namelist.remove(i)
>>> print(namelist)
实例5: 给指定的一个列表加编号,使用enumerate加编号.
>>> temp=["手机","电脑","玩具"]
>>> for (x,y) in enumerate(temp):
print(x,y)
0 手机
1 电脑
2 玩具
小总结: 实现让用户不断的猜年龄,但只给最多3次机会,再猜不对就退出程序.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
age = 22
count = 0
for i in range(10):
if count < 3:
a = int(input("请输入一个猜测的数:"))
if a == age:
print("恭喜你,答对了")
break
elif a > age:
print("你猜的数字大了")
else:
print("你猜的数字小了")
else:
b = input("这都猜不对,你继续玩吗?(yes or not):")
if b == 'yes':
count = 0
continue
else:
print("Bye!下次再玩")
count += 1
## 跳过执行与跳出语句
pass语句: pass是为了保持程序结构的完整性,该语句不做任何事情,一般用做占位语句.
>>> for ch in "LyShark":
... if ch == "h":
... pass
... print("这里执行了pass语句")
... print("字符:",ch)
...
#--输出结果-------------------------
字符: L
字符: y
字符: S
这里执行了pass语句
字符: h
字符: a
字符: r
字符: k
break语句: break语句用来终止循环语句,即使循环没有结束任然要执行.
>>> for ch in "LyShark":
... if ch == "a":
... break
... print("字符:",ch)
...
#--输出结果-------------------------
字符: L
字符: y
字符: S
字符: h
continue语句: 该语句语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环.
>>> for ch in "LyShark":
... if ch == "a":
... continue
... print("字符:",ch)
...
#--输出结果-------------------------
字符: L
字符: y
字符: S
字符: h
字符: r
字符: k
## 本章小总结(课后练习)
实现元素分类: 有如下值集合[11,22,33,44,55,66,77,88,99]
,将所有大于66的值保存至字典的第一个key中,将小于66的值保存至第二个key的值中,即:{'k1': 大于66的所有值,'k2': 小于66的所有值}
,代码如下:
list= [11,22,33,44,55,66,77,88,99]
bignum=[]
smallnum=[]
dir={}
for num in list:
if num>66:
bignum.append(num)
if num<66:
smallnum.append(num)
else:
pass
dir['k1']=bignum
dir['k2']=smallnum
print(dir)
实现元素查找: 查找元素,移动空格,并查找以a或A开头,并且以c结尾的所有元素.
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
for i in li:
if i.strip().capitalize().startswith('A') and i.strip().endswith('c'):
print(i)
for i in tu:
if i.strip().capitalize().startswith('A') and i.strip().endswith('c'):
print(i)
for i in dic.values():
if i.strip().capitalize().startswith('A') and i.strip().endswith('c'):
print (i)
实现商品输出: 输出商品列表,用户输入序号,显示用户选中的商品.
#方法一
l1=[1,2,3,4]
l2=["手机", "电脑", '鼠标垫', '游艇']
d=dict(zip(l1,l2))
print(d)
num=input("请输入商品编号:")
print("你选择的商品为 %s" %d[int(num)])
#方法二
li = ["手机", "电脑", '鼠标垫', '游艇']
for k, i in enumerate(li):
print(k,i)
k=input("请输入商品编号:")
print("你选择的商品为 %s" % li[int(k)])
实现命令行: 实现一个简单的命令行小工具框架,可自行添加扩展功能.
import sys
import os
import platform
def help():
print("By:LyShark www.mkdirs.com")
def clear():
temp=platform.system()
if(temp == "Windows"):
os.system("cls")
elif(temp == "Linux"):
os.system("clear")
def main():
while True:
try:
shell=str(input("[Shell] # "))
if(shell == ""):
continue
elif(shell == "exit"):
exit()
elif(shell == "help"):
help()
elif(shell == "clear"):
clear()
else:
print("未知命令行")
except Exception:
continue
# 程序的开头,模拟C语言写法.
if __name__ == '__main__':
main()
实现三级菜单: 实现用户交互,显示省市县三级联动的选择.
dic = {
"河北": {
"石家庄": ["鹿泉", "藁城", "元氏"],
"邯郸": ["永年", "涉县", "磁县"],
},
"湖南": {
"长沙":['a','b','c'],
"株洲":['d','e','f']
},
"湖北": {
"武汉":['g','h','i'],
"黄石":['j','k','l']
}
}
for k in dic.keys():
print(k)
flag=True
while flag:
n=input("请输入你所在省:")
for k in dic.keys():
if n in dic.keys():
if k == n:
for i in dic[n].keys():
print(i)
w = input("请输入你所在的城市:")
for i in dic[n].keys():
if w in dic[n].keys():
if i == w:
for k in dic[n][w]:
print(k)
s=input("请输入你所在的县:")
for j in dic[n][w]:
if s in dic[n][w]:
if j==s:
print("你所在的位置是:%s省%s市%s县" % (n,w,s))
flag = False
break
else:
print('不存在,请重新输入')
break
else:
print('不存在,请重新输入')
break
else:
print('不存在,请重新输入')
break
实现一个购物车: 实现一个购物车小程序,并符合以下要求.
1.要求用户输入总资产,例如:20000
2.显示商品列表,让用户根据序号选择商品,加入购物车
3.购买,如果商品总额大于总资产,提示账户余额不足,否则购买成功
product = [
("iphone",5800),
("watch",380),
("bike",800),
("book",120),
("computer",4000)
]
shopping_car = []
salary = input("请输入你的金钱: ")
if salary.isdigit():
salary = int(salary)
while True:
for i in enumerate(product):
print(i)
user_choice = input(">>>或者q:")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice >= 0 and user_choice < len(product):
p_item = product[user_choice]
if salary >= p_item[1]:
shopping_car.append(p_item[0])
salary -= p_item[1]
print("你购买了 33[32m%s 33[0m,你的余额剩余 33[31m%s 33[0m" % (p_item[0], salary))
else:
print("