name=input('姓名') print(type(name),name)
height=1.87 print('转换前的类型:',type(height)) height2=int(height) print( '转换后的类型:',type(height2))
int: float——int 整数类型的字符串——int
float: int——float 数字类型的字符串——float
任何类型都可以转换为str
name='柒' age=18 height=1.87 store=90 stunum=7
print('名字%s,年龄%d,身高%.3fm,及格率%d%%,学号%03d' %(name,age,height,store,stunum)) print(f'名字{name},年龄{age},身高{height:.3f}m,及格率{store}%,学号{stunum:03d}') print('名字{},年龄{},身高{:.3f}m,及格率{}%,学号{:03d}'.format(name,age,height,store,stunum))
算术(幂乘/%//+-),比较,赋值,逻辑(not,and.or)
name=input('username') if name=='admin'or name=='test': print(f'welcom{name}back!') else: print('error')
score=input('分数') if float(score)>=90: print('excellent') elif float(score)>=80 and float(score)<90: print('good') elif float(score)>=60 and float(score)<80: print('pretty') else: print('continue study')
类型转换另一种写法: score=int(input('分数')) if score>=90: print('excellent') elif score <90 and score>=80: print('very good') elif score <80 and score>=60: print('good') else: print('not good')
全部用if写: score=int(input('分数')) if score>=90: print('excellent') if score <90 and score>=80: print('very good') if score <80 and score>=60: print('good') if score<60: print('not good')
import random computer=random.randint(1,3) while True: player=int(input('show hand:')) if player==1 and computer==2 or player==2 and computer==3 or player==3 and computer==1: print('player win') elif player==computer: print('winwin') elif player >3: print('error') else: print('compter win') if player==0: break
num=0 i=2 while i<=100: if i%2==0: print(i) num=num+i i=i+1 print(num)
num=0 i=1 while i<=100: if i%2==1:
# print(i)
num=num+i
i=i+2
print(num)
num=0
i=1
while i<=100:
num=num+i
i=i+1
print(num)
while True: year=int(input('年份')) if (year%4==0 and year%100==1) or year%400==0: print(f'{year}闰年') else: print('%d不是闰年' %year)
for 变量 in 容器 循环执行的代码 for 变量 in range(n): pass for 变量 in range(start,end): pass
break 终止循环的执行; continue 终止此次循环,继续下一次循环
字符串.find(sub_str,start,end) 字符串.replace(oldstr,newstr,count)
字符串.split('sep',maxsplit) 字符串.split() 字符串.split(maxsplit=n)
字符串.join(列表) 可以是字符串,可以是元祖,可以是字典 将字符串添加到每个元素之间 列表中的元素必须是字符串类型
字符串[下标] 指获取指定位置的字符
num=len(str) print(num)
字符串.[start:end:step] 反转逆置字符串:str[::-1]
mylist=[] mylist=[1,'小明',2.14.False] 列表支持下标、切片、长度: 获取第一个数据:list[0] 获取最后一个数据:list[-1]
第一和第二数据:list[0:2]
len(mylist)
通过数据查找下标 列表.index(数据,start,end)
数据 in 容器
列表.count(数据)
尾部添加:list.append(数据) 指定下标位置添加:列表.insert(下标,数据)
将list2中'name'的数据添加到list1中:list1.extend(list1) 将list2添加到list1中:list1.extend([list1])
列表转换为元组:tuple2=tuple([1,2,3])
tuple[下标]
dict1['键']=增加或修改的数据
del dict1['like'] 删除某个数据 dict1.clear() 清空
字典[键] 如果不存在则会报错 字典.get(键,数据值) 如不存在则返回 None,数据值一般不写
print(变量)
写法2 for 变量 in 字典.keys(): print(变量)