f=float(input('please input a number:'))
c=(f-32)/1.8print('%.1f=%.1f'%(f,c))======================================================import math
rad=int(input('please input the r:'))#input传递的数要进行类型强转,否则报错
c=2*math.pi*rad
s=math.pi*(rad**2)print('the c=%.1f,the s=%.1f'%(c,s))========================================================
year=int(input('please enter the year:'))
is_leap=(year %4==0and year %100!=0or year %400==0)print(is_leap)#return True/False========================================================
letters='aBcdEfh'print('the length of the letters is : %d'%len(letters))# 同下print('uppercae the title letter: %s '% letters.title())# 等价于 print('change the first letter:',letters.title())print('uppercase the string:',letters.upper())print('判断字符串是否以A开头:',letters.startswith('A'))#startswith :即starts with print('判断字符串是否以!结尾:',letters.endswith('!'))
输出:
the length of the letters is:7
uppercae the title letter: Abcdefh
uppercase the string: ABCDEFH
判断字符串是否以A开头: False
判断字符串是否以!结尾: False========================================================#python的主要变量类型
a =100
b =1000000000000000000
c =12.345
d =1+5j
e ='A'
f ='hello, world'
g =Trueprint(type(a))print(type(b))print(type(c))print(type(d))print(type(e))print(type(f))print(type(g))
输出:
<class'int'><class'int'><class'float'><class'complex'><class'str'><class'str'><class'bool'>========================================================
a=float(input('please enter a number:'))
b=input('单位:')if b=='cm'or b=='厘米':print('%f = %f'%(a,a/2.54))elif b=='in'or b=='英寸':print('%f = %f'%(a,a*2.54))else:print('请输入有效单位\n')========================================================
score=int(input('please enter the grade:'))if score >=90:print('A')elif score>=80:#因为执行到其中一个分支就会退出选择结构,所以不用写成类似 score>=80 and score<=90 这种结构print('B')elif score>=70:print('C')else:print('you r trash')========================================================#求三角形面积import math as ma
a,b,c=3,4,5
p=(a+b+c)/2
s=ma.sqrt(p *(p - a)*(p - b)*(p - c))#海伦公式, 根号下 XXXXXprint(s)
等价于:
from math import sqrt
a,b,c=3,4,5
p=(a+b+c)/2
s=sqrt(p *(p - a)*(p - b)*(p - c))#海伦公式, 根号下 XXXXXprint(s)=========================================================#0到100偶数求和
sums=0for a inrange(101):# 即0-100,等价于for a in range(2, 101, 2):if a%2==0:
sums+=a
else:continueprint(sums)
等价于:
sums,num=0,0while num<=100:
sums+=num
num+=2print(sums)==========================================================for a inrange(3):print(a)
输出:
012===========================================================for b inrange(1,3):print(b)
输出:
12===========================================================#输出斐波那契数列的前20个数#1 1 2 3 5 8 13 21 ...
a =0
b =1for _ inrange(20):
a, b = b, a + b
print(a, end=' ')===========================================================#水仙花数的查找for a inrange(100,1001):
x=a%10#个位
y=a//10%10#十位
z=a//100#百位if x**3+ y**3+z**3== a:print(a)===========================================================
#通过函数的封装,计算组合数C(m,n) (m>n)deffactorial(n):
result=1for a inrange(1,n+1):
result*=a
return result
m=int(input('enter the m:'))
n=int(input('enter the n:'))print(factorial(m)/factorial(n)/factorial(m-n))==================================================#求最大公约数与最小公倍数defdy(x,y):if x<y:
x,y=y,x
for a inrange(y,1,-1):#求最大公约数,故倒着来if x%a==0and y%a==0:return a
defxb(x,y):return(x*y/dy(x,y))#求最小公倍数的公式print(dy(9,12))print(xb(9,12))====================================================
Python的内置函数
- 数学相关:abs/divmod/pow/round/min/max/sum- 序列相关:len/range/next/filter/map/sorted/slice/reversed- 类型转换:chr/ord/str/bool/int/float/complex/bin/oct/hex- 数据结构:dict/list/set/tuple- 其他函数:all/any/id/input/open/print/type
fruits =['orange','peach','durian','watermelon']print(fruits[slice(1,3)])#输出第1,2个元素'peach', 'durian'==========================================================================
Python常用模块
- 运行时服务相关模块: copy / pickle / sys /...- 数学相关模块: decimal / math / random /...- 字符串处理模块: codecs / re /...- 文件处理相关模块: shutil / gzip /...- 操作系统服务相关模块: datetime / os / time / logging / io /...- 进程和线程相关模块: multiprocessing / threading / queue
- 网络应用相关模块: ftplib / http / smtplib / urllib /...- Web编程相关模块: cgi / webbrowser
- 数据处理和编码模块: base64 / csv / html.parser / json / xml /...==========================================================================="""
函数的参数
- 位置参数
- 可变参数
- 关键字参数
- 命名关键字参数
"""# 参数默认值deff1(a, b=5, c=10):return a + b *2+ c *3print(f1(1,2,3))# 1+2*2+3*3=14print(f1(100,200))# 100+200*2+10*3=530print(f1(100))# 100+2*5+3*10=140print(f1(c=2, b=3, a=1))# 1+3*2+2*3=13 (如果不加a,b,c进行限定,则计算方法与第一个类似)# 可变参数deff2(*args):sum=0for num in args:sum+= num
returnsumprint(f2(1,2,3))#6print(f2(1,2,3,4,5))#15print(f2())#0# 关键字参数deff3(**kw):if'name'in kw:print('欢迎你%s!'% kw['name'])elif'tel'in kw:print('你的联系电话是: %s!'% kw['tel'])else:print('没找到你的个人信息!')
param ={'name':'骆昊','age':38}
f3(**param)
f3(name='骆昊', age=38, tel='13866778899')
f3(user='骆昊', age=38, tel='13866778899')
f3(user='骆昊', age=38, mobile='13866778899')
#统计学生人数、名字以及考试成绩并计算平均值
num=int(input('the numbers of stud is:'))
names=[None]*num #即建立一个names的列表,列表中有num个Nonetype(无)类型(即None)的元素#names=[[]]*num #建立一个names的列表,列表中的元素也都是列表,有num个空列表元素#总结:names是一个列表,列表中的元素为[ ]内部的东西与num发生运算产生的
grades=[None]*num
for index inrange(num):#踩坑:input里面的 % 后面的数,要加上括号,否则报错
names[index]=input('the name of stud %d is:'%(index +1))#由于这里的names不为数值型,这里不用对input进行类型转换
grades[index]=int(input('the grade of stud %d is:'%(index +1)))#踩坑:由于这里的输入为数值型,所以必须对input进行类型转换
sums=0for index inrange(num):print('%s : %d '%(names[index],grades[index]))
sums+=grades[index]
aver=sums/num
print(aver)===================================================================================#字典的使用
dic1={'whut':1,'hnu':2,'sichuan':3,'hunan':4}#输出valueprint(dic1['whut'])#遍历key值,也可以使用keys(),但是下面的方法直接使用字典,简单一些for a in dic1:print('%s-------->%d'%(a,dic1[a]))#遍历value值for b in dic1.values():print(b)#同时遍历key valuefor key,value in dic1.items():print(key,value)#判断key是否在字典内,可以直接使用字典if'beijing'in dic1:print(yes)if'shanghai'notin dic1:print('not exist')#get方法,获取一个key值print(dic1.get('sichuan'))print('========================================')#popitem方法,按照栈的顺序删除字典元素,即先入后出#pop方法,删除指定元素print(dic1.popitem())print(dic1.pop('whut',1))#第二个参数 1 为可选参数,下面的也可以print(dic1.pop('hnu'))#清空字典clear
dic1.clear()print(dic1)======================================================
输出:
1
whut-------->1
hnu-------->2
sichuan-------->3
hunan-------->41234
whut 1
hnu 2
sichuan 3
hunan 4not exist
3========================================('hunan',4)12{}===========================================================#字典的进阶:#setdefault方法:
dic1={'whut':1,'hnu':2,'sichuan':3,'hunan':4}
dic1.setdefault('wuhan',5)#字典中没有wuhan,则添加一个print(dic1)#{'whut': 1, 'hnu': 2, 'sichuan': 3, 'hunan': 4, 'wuhan': 5}
dic1.setdefault('wuhan',6)#字典中存在wuhan,则不会改变原来的值print(dic1)#{'whut': 1, 'hnu': 2, 'sichuan': 3, 'hunan': 4, 'wuhan': 5}#可以使用setdefalut进行统计字符串中字符出现的次数
a='if you want to sell american goods to japan,forget about it'
b={}for c in a:
b.setdefault(c,0)
b[c]=b[c]+1print(b)#{'i': 3, 'f': 2, ' ': 10, 'y': 1, 'o': 7, 'u': 2, 'w': 1, 'a': 6, 'n': 3, 't': 6, 's': 2, 'e': 3, 'l': 2, 'm': 1, 'r': 2, 'c': 1, 'g': 2, 'd': 1, 'j': 1, 'p': 1, ',': 1, 'b': 1}
a=['dont','believe','me','just','watch']print(a[0])#dontprint(a[1])print(a[-1])#倒着来,输出 watch,print(a[-5])#dont#修改元素,直接赋值即可
a[0]='with'print(a)#添加元素
a.append('come on')
a.insert(1,'hello')print(a)#['with', 'hello', 'believe', 'me', 'just', 'watch', 'come on']#删除元素del a[1]
a.remove('come on')
a.pop()#弹出最后一个元素
a.pop(0)#弹出第零个元素print(a)#['believe', 'me', 'just']===========================================================
b=['dont','believe','me','just','watch']#列表的遍历for ele in b:print(ele.title(),end=' ')#列表的切片
c=b[1:4]#1 - 3个元素print('\n',c)
x=b[4:1:-1]#4 - 2
y=b[::-1]#倒序print(x)#['watch', 'just', 'me']print(y)
d=b #注意这两个的不同之处,第一个没有复制,仅仅创建了一个新的标签
e=b[:]===============================================================#生成列表:生成表达式、生成器
list2 =[x**2for x inrange(1,11)]#生成表达式print(list2)#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
list3 =[m + n for m in'ABCDEFG'for n in'12345']print(list3)#['A1', 'A2', 'A3', 'A4', 'A5', 'B1', 'B2' ......print(len(list3))# 35, 5*7=35================================================================#生成器deffib(n):
a,b=0,1for x inrange(n):
a, b = b, a + b
#带有yield的函数会被python翻译成一个生成器yield a #返回a,并冻结在此,下次也从这里开始
gen = fib(20)#调用fib时,返回了一个生成器print(gen)#<generator object fib at 0x0000008FCC5495C8>for elem in gen:#通过循环多次调用生成器gen,每次循环都返回a,并冻结fib,直到下一次调用print(elem, end=' ')#1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 print()#回车
f=float(input('please input a number:'))c=(f-32)/1.8print('%.1f=%.1f'% (f,c))======================================================import mathrad=int(input('please input the r:')) #input传递的数要进行...