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='\t')
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 [url]www.mkdirs.com[/url]")
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("你购买了\033[32m%s\033[0m,你的余额剩余\033[31m%s\033[0m" % (p_item[0], salary))
else:
print("\033[31m你的余额不足\033[0m")
else:
print("你输入的项目[%s]不存在,请重新输入" % user_choice)
elif user_choice == 'q':
print("你购买了这些商品:".center(30,"-"))
for i in shopping_car:
print("\033[32m%s\033[0m" %i)
print("\033[31m余额%s\033[0m" %salary)
exit()
else:
print("你输入的[%s]不存在" % user_choice)
else:
print("你输入的金额不正确!请重新输入金额!")
## 实例小总结(提高技巧) 题目(1): 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
程序分析:可填在百位、十位、个位的数字都是1、2、3、4,组成所有的排列后再去掉不满足条件的排列.
>>> for i in range(1,5):
... for j in range(1,5):
... for k in range(1,5):
... if(i!=k) and (i!=j) and(j!=k):
... print(i,j,k)
...
#--输出结果-------------------------
1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
题目(2): 输入某年某月某日,程序自动判断这一天是这一年的第几天?
程序分析:以10月1日为例,应该先把前9个月的加起来,然后再加上1天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天.
# -*- coding: UTF-8 -*-
year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month <= 12:
sum = months[month - 1]
else:
print ('data error')
sum += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
leap = 1
if (leap == 1) and (month > 2):
sum += 1
print ('it is the %dth day.' % sum)
#--输出结果-------------------------
year:
2018
month:
10
day:
1
it is the 274th day.
题目(3): 斐波那契数列,又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、….在数学上,费波那契数列是以递归的方法来定义.
F0 = 0 (n=0)
F1 = 1 (n=1)
Fn = F[n-1]+ F[n-2](n=>2)
# -*- coding: UTF-8 -*-
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
# 输出了第10个斐波那契数列
print (fib(10))
题目(4): 输出9*9乘法口诀表,分行与列考虑,共9行9列,i控制行,j控制列.
import os
import sys
for x in range(1,10):
print()
for y in range(1,x+1):
print("%d*%d=%d "%(y,x,x*y),end="")
题目(5): 写一个字符串遍历查找工具,代码如下.
import os
import sys
ls="Type help() for interactive help, or help(object) for help about object"
find="help"
for x in range(len(ls)):
temp=len(find)
if str(ls[x:x+temp]) == str(find):
print(ls[x:x+temp],x)
break
题目(6): 通过使用time模块中的sleep函数,让程序每隔1秒执行一次循环.
import os
import time
dic={1:"admin",2:"guest"}
for key,value in dict.items(dic):
print(key,value)
time.sleep(1)
题目(7): 通过使用time模块,对指定的时间格式进行一定的格式化操作.
import os
import time
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))) #2019-01-18 15:16:28
time.sleep(2)
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))
题目(8): 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
程序分析:兔子的规律为数列 1,1,2,3,5,8,13,21....
import os
f1 = 1
f2 = 1
for i in range(1,22):
print('%12ld %12ld'%(f1,f2))
if (i % 3) == 0:
print("")
f1 = f1 + f2
f2 = f1 + f2
题目(9): 判断101-200之间有多少个素数,并输出所有素数.
程序分析:判断素数的方法,用一个数分别去除2,如果能被整除,则表明此数不是素数,反之是素数.
import os
from math import sqrt
from sys import stdout
h=0
leap=1
for m in range(101,201):
k = int(sqrt(m + 1))
for i in range(2,k + 1):
if m % i == 0:
leap = 0
break
if leap == 1:
print("%-4d"%m)
h += 1
if h % 10 == 0:
print("")
leap = 1
print('The total is %d' %h)
题目(10): 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数.
import os
import string
strs=input("请输入一个字符串:")
letters=0
space=0
digit=0
others=0
for x in range(len(strs)):
ch=strs[x]
if ch.isalpha():
letters+=1
elif ch.isspace():
space+=1
elif ch.isdigit():
digit+=1
else:
others+=1
print("char=%d,space=%d,digit=%d,others=%d"%(letters,space,digit,others))
题目(11): 读取db配置文件,并按照文件中的账号密码判断是否允许登陆.
import os
import sys
def login(x,y):
fp=open("db","r",encoding="utf-8")
data=fp.readline().split(":")
count=len(open("db","r").readlines())
username=data[0]
password=data[1]
for i in range(3):
if x==username.strip() and y==password.strip():
print("登陆成功")
break
else:
data=fp.readline().split(":")
username=data[0]
password=data[1]
continue
fp.close()
login("admin","admin")
login("lyshark","lyshark")
|