-
一、变量
- 变量类型
变量可以指定不同的数据类型,这些变量可以存储整数,小数或字符。
2.变量赋值
- 每个变量在使用前必须赋值,赋值后该变量才会被创建;
- 等号(=)用来给变量赋值;
- 等号(=)运算符左边是一个变量名,等号(=)运算符右边是存储在变量中的值。例如:
-
1 # autor:guangqing xu2 counter =100 #赋值整数型变量3 miles = 1000.0 #浮点型4 name = "guangqing" #字符型5 print(counter)6 print(miles)7 print(name)
- 3.交互程序
-
# autor:guangqing xuname=input("name:")age=int(input("age:"))job=input("job:")salary=input("salary:")info='''--------info of %s ----name %sage %djob %ssalary %s'''%(name,name,age,job,salary)info2='''-------- info of {_name} -----name:{_name}age:{_age}job:{_job}salary:{_salary}'''.format(_name=name,_age=age,_job=job,_salary=salary)info3='''------ info of {0} ----name:{0}age:{1}job:{2}salary:{3}'''.format(name,age,job,salary)print(info2)
-
二、表达式 if ... else
- 1、场景1
# 提示输入用户名和密码
# 验证用户名和密码
# 如果错误,则输出用户名或密码错误
# 如果成功,则输出 欢迎,XXX!
-
1 # autor:guangqing xu2 _username = "guangqing"3 _password = "abc123"4 username = input("username:")5 password = input("password:")6 if _username==username and _password==password:7 print("Welcome user {name} login...".format(name=username))8 else:9 print("Invalid username or password!")
-
1 import getpass2 name= raw_input("请输入用户名:")3 password = getpass.getpass("请输入密码:")4 if name=="guangqing" and password=="abc123":5 print("欢迎,guangqing")6 else:7 print("用户名和密码错误")
- 3次输入错误则停止运行;
-
# autor:guangqing xu_username="guangqing"_password="abc123"#for i in range(0,3,1): #循环3次count=0while count<3: user = input("user:") password = input("password:") if user == _username and password == _password: print("welcome user %s login" % user) break else: print("wrong username or password") count +=1print(user,password) #打印输入的内容
- 场景二、猜年龄游戏
-
1 # autor:guangqing xu2 age_of_qing=253 guess_age=int(input("guess_age:"))4 if guess_age==age_of_qing:5 print("Congratulations, you got it !")6 elif guess_age < age_of_qing:7 print("think bigger!")8 else:9 print("think smaller!")
外层变量,可以被内层代码使用内层变量,不应被外层代码使用
-
三、表达式 for loop
- 最简单的循环10次
-
# autor:guangqing xufor i in range(0,10,1): #1为步长 print("loop:",i) 输出:
loop: 0
loop: 1loop: 2loop: 3loop: 4loop: 5loop: 6loop: 7loop: 8loop: 9需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环
-
# autor:guangqing xufor i in range(0,10,1): if i<5: continue #不往下走了,直接进入下一次loop
-
需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出
-
# autor:guangqing xufor i in range(0,10,1): if i>5: break #不往下走了,直接跳出整个loop print("loop:",i)
如何实现让用户不断的猜苹果个数,但只给最多3次机会,再猜不对就退出程序。
-
# autor:guangqing xucount_of_apple=25for i in range(0,3,1): guess_count=int(input("guess count:")) if guess_count==count_of_apple: print("恭喜你,猜对了....") break elif guess_count>count_of_apple: print("很遗憾,猜大了...") else: print("很不幸,猜小了...")else: print("猜这么多次都猜不对...")
-
四、while loop
- 循环100次退出
-
# autor:guangqing xucount=0while True: print("你的誓言永不变...",count) count +=1 if count==100: print("没有什么是无穷尽的...",count) break
# autor:guangqing xucount=0while count<100: print("你的誓言永不变...",count) count +=1else: print("没有什么是无穷尽的,除了时间...",count)
回到上面for 循环的例子,如何实现让用户不断的猜苹果个数,但只给最多3次机会,再猜不对就退出程序。
-
1 # autor:guangqing xu 2 count_of_apple=25 3 count=0 4 while count<3: 5 guess_count=int(input("guess count:")) 6 if guess_count==count_of_apple: 7 print("恭喜你,猜对了....") 8 break 9 elif guess_count>count_of_apple:10 print("很遗憾,猜大了...")11 else:12 print("很不幸,猜小了...")13 count +=114 else:15 print("猜这么多次都猜不对...")
- 五、模块初识
- sys
-
# autor:guangqing xuimport sys#print(sys.path) #打印环境变量print(sys.argv) #具体路径
os
-
# autor:guangqing xuimport os#cmd_res=os.system("dir") #执行命令,不保存结果cmd_res=os.popen("dir").read() #读出具体文件print("-->",cmd_res)os.mkdir("new_dir") #创建一个新目录
完全结合一下
-
import sys,osos.system("".join(sys.argv[1:]))#把用户的输入的参数当作一条命令交给os.system来执行
-
六、列表、元组操作
- 切片:取多个元素
-
names=["#guangqing","Jiale","3fengfei","xiahui","zhangliao","xiahui"]
#print(names[0],names[2]) #print(names[-1]) #切片 取最后一个值 #print(names[-2:]) # 切片 取最后两个值 #print(names[0:3]) #切片 取下标0至下标3之间的数字 包含0,不包含4 #print(names[:3]) #切片 取下标0至下标3之间的数字 包含0,不包含4
追加、插入、修改
-
names=["#guangqing","Jiale","3fengfei","xiahui","zhangliao","xiahui"]names.append("zhangfei") #追加 到最后names.insert(1,"zhugeliang") #插入指定的位置 强行在Jiale前面插入names[2]="lixiaolong" # 修改print(names)
删除
-
# autor:guangqing xunames=["#guangqing","Jiale","3fengfei","xiahui","zhangliao","xiahui"]#deletenames.remove("guangqing") #删除 guangqingdel names[2] =names.pop(2) #删除指定位置names.pop() #删除最后一个names.pop(0)
拓展
-
names=["#guangqing","Jiale","3fengfei","xiahui","zhangliao","xiahui"]names2=[1,2,3,4]names.extend(names2) #把names2 数据 合并到namesprint(names,names2)['#guangqing', 'Jiale', '3fengfei', 'xiahui', 'zhangliao', 'xiahui', 1, 2, 3, 4] [1, 2, 3, 4]
拷贝
-
import copynames=["#guangqing","Jiale","3fengfei","xiahui",["hongjun","jim"],"zhangliao","xiahui"]names2=names.copy() #将names 数据复制到names2#names2=names#names2=copy.deepcopy(names)print(names)print(names2)names[2]="许先生" #names 更改 names2 未更改names[4][0]="qingge" #names/names2 均更改;调用 import copy --- deepcopy names更改,names2不更改print(names)print(names2)['#guangqing', 'Jiale', '3fengfei', 'xiahui', ['hongjun', 'jim'], 'zhangliao', 'xiahui']['#guangqing', 'Jiale', '3fengfei', 'xiahui', ['hongjun', 'jim'], 'zhangliao', 'xiahui']['#guangqing', 'Jiale', '许先生', 'xiahui', ['qingge', 'jim'], 'zhangliao', 'xiahui']['#guangqing', 'Jiale', '3fengfei', 'xiahui', ['qingge', 'jim'], 'zhangliao', 'xiahui']Process finished with exit code 0
统计、排序&翻转
-
names=["#guangqing","Jiale","3fengfei","xiahui","zhangliao","xiahui"]#names.clear() #清空#names.reverse() #反转#names.sort() #排序 特殊符号--数字--大写-小写print(names)
2、字符串操作
- 特性:不可修改
-
# autor:guangqing xuname = "my \tname is {name} and i am {year} old"print(name.capitalize()) #首字母大写print(name.center(50,"-")) #中心 输出------my name is {name} and i am {year} old------print(name.count("a")) #统计a 出现的次数print(name.endswith("ld")) #判断"结尾" 是否 以ld结束print(name.expandtabs(tabsize=30)) #输出my name is {name} and i am {year} oldprint(name[name.find("name"):]) #输出name is {name} and i am {year} oldprint(name.format(name="guangqing",year=25)) #输出my name is guangqing and i am 25 oldprint(name.format_map({ "name":'jiale','year':'23'})) #输出my name is jiale and i am 23 oldprint("ab123".isalnum()) #字符测试 是否是字母和数字print("abC".isalpha()) #是否全部是字母print('1'.isdecimal())#是否整数print('1q'.isdigit()) #是否整数 较为常用print('a 1A'.isidentifier()) #判读是不是一个合法的标识符print('33a'.isnumeric()) #判断是否为数字print('My Name Is '.istitle()) #判断是否为标题(是否只有首字母为大写print('guangqing xu'.title()) #将首字母改成大写 输出Guangqing Xuprint('My Name Is '.isprintable()) #tty file ,drive file 是否可打印print('My Name Is '.isupper()) #是否为大写字母(所有)print('+'.join(['1','2','3','4'])) #输出 1+2+3+4print(name.ljust(50,"-"))#my name is {name} and i am {year} old------------print(name.rjust(50,"-")) #------------my name is {name} and i am {year} oldprint("GUangqing xu".lower()) #全部转换成小写字母print("GUangqing xu".upper()) #全部转换成大写字母print('\nguangiqng'.lstrip()) #删除左回车print( '\nguangqing\n'.rstrip()) #删除右回车print( ' \nguangqing\n'.strip()) #左右回车均删除p=str.maketrans('abcdefri','123@#678')print("defria".translate(p)) #对defria 进行翻译 输出@#6781print("guangqing xu".replace('g','G',1)) #对第一次出现g的地方更改成Gprint('guangqing lil'.rfind('l')) #最右边出现l 的位置 输出12print('1+2+3+4'.split('\n')) #输出 ['1+2+3+4']print('1+2\n+3+4'.splitlines()) #分割线 输出 ['1+2', '+3+4']print('guangqing xu'.swapcase()) #全部转换成大写字母print('lex li'.title()) #首字母大写print('guangqing xu'.zfill(50)) #输出00000000000000000000000000000000000000000000lex liprint( '---')