练习一:
1,2,3,4,组成的互不相同的3位数有多少个
解:
在python中是没有&&及||这两个运算符的,取而代之的是英文and和or。其他运算符没有变动。
python不支持类似 x++ 或 x-- 这样的前置/后置自增/自减运算符,因此只能用 += 或 -= 这种。
list = {1,2,3,4}
cnt = 0
for i in list:
for j in list:
for k in list:
if i!=j and i!=k and j!=k:
cnt+=1
print(cnt)
排序
x = int(input('x= '))
y = int(input('y= '))
z = int(input('z= '))
list=[]
list.append(x)
list.append(y)
list.append(z)
list.sort()
#list.sort(reverse = False)
for i in list:
print(i)
时间:sleep 1s
import time
print( time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
time.sleep(1)
print( time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
递归:
#递归求5!
def func(n):
if n==0:
return 1
return n*func(n-1)
for i in range(10):
print(i,'!=',func(i))
buf = 'abcdef'
递归打印逆序字符串
def print_buf(a,l):
if l == 0:
return
print(a[l-1])
return print_buf(a,l-1)
print_buf(buf,len(buf))
join
#用逗号分隔开来,连接字符串
list = ['123','456','789']
s = ' '.join(str(i) for i in list)
s
range()
a,b = b,a
#调换位置 不需要像c一样用一个temp交换
list = [1,2,3,4,5]
for i in range(0,int(len(list)/2),1):
list[i],list[len(list)-1-i] = list[len(list)-1-i],list[i]
print(list)
list
for i in range():
for j in range():
x[i][j] = ...
#矩阵加法
X = [[1,2,3],
[4,5,6],
[7,8,9]
]
Y = [[10,2,3],
[4,50,6],
[7,8,90]
]
Z = [[0,0,0],
[0,0,0],
[0,0,0]
]
for i in range(3):
for j in range(3):
Z[i][j] = X[i][j] + Y[i][j]
for z in Z:
print (z)
匿名函数
sum_value = lambda x,y:x+y
print (sum_value(1,2))
(七)查找字符串的位置
s1 = 'asdffgdhfdjhgj'
s2 = 'ffg'
print (s1.find(s2))
(八)在字典中找到年龄最大的人,并输出
people = {'laowang':40,'tangyudi':30,'zhangsan':45}
m = 'tangyudi'
for key in people.keys():
if people[m] < people[key]:
m = key
print (m,people[m])
(九)列表转换为字典
k = ['tang','yudi']
v = [123,456]
print (dict([k,v]))
(十)从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存
f = open('test.txt','w')
s = input('输入一个串串')
s = s.upper()
f.write(s)
f.close()
f = open('test.txt','r')
print (f.read())
f.close()