1。我的幸运数字
sName = input("请输入你的名字:" )
sName = sName.strip().lower()
luckyNumber = 0
for x in sName:
v = ord(x) - ord("a") + 1 #ord 转换成对应的 Unicode 值
luckyNumber += v
print("value of",x,"=",v)
print("你的幸运数字是:",luckyNumber)
2.判断男生或女生是否符合结婚年龄,if语句
iAge = int(input("你的年龄是:"))
sGebder = input("你的性别的男或女(男/女):")
if sGebder == "男":
if iAge > 22:
print("你已符合结婚年龄")
else:
print("你不符合结婚年龄")
elif sGebder == "女":
if iAge >= 20:
print("你已符合结婚年龄")
else:
print("你不符合结婚年龄")
else:
print("错误,请输入正确的数据")
3.while 循环
sMessage = ""
while sMessage != "q": #输入 q 时停止
sMessage = input("我是复读机,和我说句话:")
print("复读机说:",sMessage)
while True:
sMessage = input("我是复读机,和我说点啥:")
if sMessage == "q": #输入 q 结束
break
print("复读机说:",sMessage)
4.continue 结束当此迭代
names = ["张杰","周深","黄磊","王宝强","赵丽颖","孙红雷","黄渤"]
i = 0
henrys = []
while i < len(names):
sName = names[i]
i += 1
if not sName.startswith("黄"): # startswith 判断字符串是否以指定字符或子字符串开头
continue
print("你好",sName)
henrys.append(sName)
print("找到姓 黄 的名字:",henrys)
5.序列缝合与循环解包
names = ["王震球","宝儿姐","张楚岚","陆玲珑"]
salarys = [1800,2400,1500,5000]
for name,salary in zip(names,salarys): #for也可以给出多个
print(name + "工资是:" ,salary)
6.带下标的遍历
names = ["王震球","宝儿姐","张楚岚","陆玲珑"]
print(list(enumerate(names))) # enumerate 枚举,列举 对应下标
for id,name in enumerate(names):
print(name, "是下标为:",id,"在列表里")
7.反向遍历
names = ["王震球","宝儿姐","张楚岚","陆玲珑"]
for x in reversed(names):
print(x)
8.滚雪球的复利
fBalance = 10000 #总欠款
fRate = 0.0005 #日利息
balances = []
for i in range(365*30):
fBalance = fBalance + fBalance*fRate
balances.append(fBalance)
print("30年后的总欠款:",fBalance)
9.计算圆周率的值
import random
import math
N,nHits=50000,0
xs,ys = [],[] #i x[i],y[i]
for i in range(N):
x = random.random()*2 -1
y = random.random()*2 -1
xs.append(x)
ys.append(y)
if x*x + y * y <= 1:
nHits += 1
pi = 4 * nHits/N
print("pi %.6f" %pi)
10.一张纸对折多少次可以超过珠峰高度?
iCounter = 0
fThickness = 0.0001 #纸张厚度 0.1mm
while True:
if fThickness > 8844.43:
break
else:
fThickness *= 2
iCounter += 1
print("对折了{}次后超过了珠峰的高度,其厚度为{}".format(iCounter,fThickness))
11.冒泡排序
def bubbleSort(seq):
for i in range(len(seq)-1,0,-1):
for j in range(0,i):
if seq[j] > seq[j+1]:
seq[j],seq[j+1] = seq[j+1],seq[j]
seq = [3,5,7,1,9,2,6,8,4]
bubbleSort(seq)
print("排序后:",seq)