Python基础三(数据类型)

一,数据类型笔记粗写
数据运算:
数据类型初识:
数字:
整数 int(integer)
整型
长整型
in py3 已经不区分整型与长整型,统一都叫整型
float 浮点数
复数 complex
布尔 只有两种状态,分别是:
真 True
假 Fales

字符串
salary.isdigit():“.”这是什么意思?
计算机中,一切皆为对象
世界万物,皆为对象,一切对象皆可分类
列表,元祖

索引(下标),都是从零开始
切片
.count 查某个元素的出现次数
.index 根据内容找对应的位置
“小孩” in a (in的用法)
增加
a.append()追加
a.insert(index,“内容”)
a.extend 扩展
修改
a[index]="新的值"
a[start:end]=[a,b,c]
删除
remove“内容”
pop(index)
del (删除列表或者值)
a.clear()清空
排序
sort()默认是从小到大排序,将sort()改为sort(reverse=True)可从大到小排序
reverse()
身份判断
>>>type(a) is list
>>>True
元祖
tuple=(20,)一个元素需要在末尾加一个逗号
字典
字典无序,键唯一
字符串

循环loop:
有限循环,字数限制 for
无限循环 while
contiue 结束本次循环,继续下一次循环
break 跳出整个当前循环

不可变类型:整型,字符串,元祖
可变类型:列表,字典

二,格式化输出的用法
#格式化输出
name=input("Name")
age=int(input("Age"))
job=input("Job")
salary=input("Salary") #salary=工资

# if salary.isdigit():#判断长得像不像数字,比如200d,“200”
#     salary=int(salary)
# else:
#     #print("must input digit")
#     exit("must input digit")#退出程序

#%d:必须输入数字
msg='''
------info of %s------
Name:%s
Age:%d
Job:%s
Salary:%d 
You will be retired in %s years
------end------
'''%(name,name,age,job,salary,65-age)
print(msg)
View Code

   三,列表的用法

#_author: liu.cao
#date: 2018/6/24
# a=["小明","小白","小虎","小屁孩"]
# #增 切片
# print(a[1:4])#顾头不顾尾
# print(a[0:])#取到最后
# print(a[1:-1])#取到倒数第二个
# print(a[0::2])#步长
#
# #添加 append insert
# a.append("小狗") #将数据插入到最后一个位置
# print(a)
# a.insert(1,"小胖")#将数据插入任意一个位置
# print(a)
#
# #修改
# a[1]="金星"
# print(a)
# a[1:3]=["a","b"]
# print(a)
#
# #删除 remove pop del
# a.remove("a")#直接删除值
# print(a)
#
# a.pop(1)#根据索引删除值
# b=a.pop(1)#删除的值可以接收并打印
# print(a)
# print(b)
#
# del a[0] #del 既可以删除值又可删除对象
# del a
# print(a)

#count计算某元素出现次数
#extend
a=[1,2,3]
b=[4,5,6]
a.extend(b)
print(a)
print(b)
#index 根据内容找位置
a=["小明","小白","小虎","小屁孩"]
print(a.index("小虎"))#知道人的名字,但是不知道人的位置,需要取到它所在的位置,多个人的名字要取值已第一个为主
#reverse 倒序
a=["小明","小白","小虎","小屁孩"]
a.reverse()
print(a)

x=[4,6,8,2,1,9]
x.sort() #排序
print(x)
View Code

  四,字典的用法

#创建字典的方式
dict1={"name":"xiaohai"}
#dict2=dict((("name","xiaohai"),))
#
dict1["age"]=18
print(dict1)

ret=dict1.setdefault("age",34)#如果键存在,不改动,返回字典中相应的键对应的值
print(ret)
ret2=dict1.setdefault("hobby","gilr")#如果键不存在,在字典中新增新的键值对,并返回相应的值
print(ret2)

#查 通过键去查找值
dict2={"name":"xiaohai","age":34,"hobby":"gilr"}
print(dict2["name"])

print(list(dict2.keys()))#拿到键,转化为列表
print(list(dict2.values()))#拿到值,转化为列表
print(list(dict2.items()))#拿到所有的键值对

#
dict3={"name":"xiaohai","age":34,"hobby":"gilr"}
dict3["name"]="xiaohu"
#print(dict3)
dict4={"1":"2","2":'222'}
dict4.update(dict3) #类型列表中extend用法
print(dict4)
print(dict3)

#
dict5={"name":"xiaohai","age":34,"hobby":"gilr"}
#del dict5["name"]#删除字典中的指定键值对
#print(dict5)
#print(dict5.clear(dict5))#清空整字典
#print(dict5.pop("age"))#删除字典中指定键值对,并返回该键值对的值
#ret3=dict5.pop("age")
#print(ret3)
#print(dict5)
a=dict5.popitem()#随机删除某组键值对,并以元祖返回值
print(a,dict5)
del dict5#删除整个字典
View Code

  五,字典的其它用法

dict1=dict.fromkeys(['host1','host2','host3'],'test') #涉及到后面的深浅拷贝
print(dict1)

#字典嵌套
av_catalog = {
    "欧美":{
        "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
        "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
        "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
        "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
    },
    "日韩":{
        "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    },
    "大陆":{
        "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    }
}

av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来"#取值
print(av_catalog["大陆"]["1024"])
#ouput(输出结果)
['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']

#排序
dict2={8:'111',1:'666',3:'777'}
print(sorted(dict2))#对键进行排序
print(sorted(dict2.items()))#对键值进行排序

#字典的遍历
#方法一,推荐
dict3={"name":"xiaohai","age":34,"hobby":"gilr"}
for i in dict3:
    print(i,dict3[i])#拿到键值
#方法二,要转换的过程需要时间
for i,j in dict3.items():
    print(i,j)
View Code

  六,字符串的用法

a="let's go" #当有单引号的时候用双引号括起来
print('helloworld'[2:])#通过索引取值
#关键字 in
print("123" in "hello")#判断值是否在内
#格式字符串
#%s s=string
#%d d=dight
#%f f=folat

#字符串拼接
#方法一,效率低
a="123"
b='abc'
# c=a+b
# print(c)
#方法二,join
c=''.join([a,b])#''表示空字符串
print(c)

#字符串的内置方法
str="hello kitty {name} is {age}"

print(str.count('l')) #统计元素个数
print(str.capitalize()) #首字母大写
print(str.center(50,'-')) #居中
print(str.endswith('y')) #以某个内容结尾
print(str.startswith('h')) #以某个内容结尾
#print(str.expandtabs(tabsize=5))#\t空格个数,这个方法不重要
print(str.find('t'))#查找到第一个元素,并将索引值返回
print(str.format(name='xiaohai',age='22'))#格式化输出的第二个方法
print(str.format_map({'name':'xiaohai','age':22}))
print(str.index('t'))#类似find方法,但是找不到值的时候会报错
print('123456'.isdigit())#判断是不是数字,必须是整型
print('123456'.isnumeric())#判断是不是数字,方法同isdigit
print('abc'.isidentifier())#检验是否是非法字符
print('Abc'.islower())#判断是不是全小写
print('Abc'.isupper())#判断是不是全大写
print(''.isspace())#判断是不是空格
print('My Title'.istitle())#标题的格式是不是大写
print("MY Title".lower())#大写变小写
print("MY Title".upper())#小写变大写
print(' \t My Title \n'.strip())#将左右换行符,空格去除
print(' \t My Title \n'.lstrip())#将左边换行符,空格去除
print(' \t My Title \n'.rstrip())#将右边换行符,空格去除
#print("MY Title Title".replace('Title','lesson',1))#替换功能
#print("MY Title Title".rfind())
print("MY Title Title".split('i',1))#已XX为分割对象
print("MY title title".title())


#摘一些重要的字符串方法
print(str.count('l'))
print(str.capitalize()) #首字母大写
print(str.startswith('h')) #以某个内容结尾
print(str.find('t'))#查找到第一个元素,并将索引值返回
print(str.format(name='xiaohai',age='22'))#格式化输出的第二个方法
print('Abc'.islower())#判断是不是全小写
print('Abc'.isupper())#判断是不是全大写
print(' \t My Title \n'.strip())#将左右换行符,空格去除,重要程度*****
print("MY Title Title".split('i',1))#已XX为分割对象
View Code

 七,continue的小练习

exit_flag=False#标志位

for i in range(10):
    if i<5:
        continue
    print(i)
    for j in range(10):
        print("第二层",j)
        if j==6:
            exit_flag=True #理解为儿子跳楼了,you jump
            break
    if exit_flag:#理解为发现儿子跳楼,i,jump
        break
View Code

 八,练习1,登陆程序

# _user="Louis"
# _password="123456"
#
# passed_authentication=False #定义登陆成功的状态为 假,不成立【这里可看成一个flag=标志位】
#
# for i in range(3):
#     username=input("Username")
#     password=input("Password")
#
#     if username==_user and password==_password:
#         print("welcome %s login..."%_user)
#         passed_authentication=True#真,成立
#         break#跳出,中断,不再往下输出循环
#     else:
#         print("invalid username or password !")
# if not passed_authentication:#只有在True的情况下,条件成立
#     print("你尝试太多次了,请放弃!!!")

print("----------第二种方法(简洁版)------------------------")

_user="Louis"
_password="123456"


for i in range(3):
    username=input("Username")
    password=input("Password")

    if username==_user and password==_password:
        print("welcome %s login..."%_user)
        break#跳出,中断,不再往下输出循环 (break for过后就不会执行最后的else语句)
    else:
        print("invalid username or password !")
else:#只要上面的for循环正常执行完毕,中间没被打断,就会执行else语句
    print("你尝试太多次了,请找回密码再试!!!")
View Code

       练习2,Range用法练习

for i in range(1,101):#输出1到100的基数,方法1
#     if i%2==1:
#         print("loop:",i)

# for i in range(1,101,2):#输出1到100的基数,方法2,用步长
#     print(i)
#
# print("----------------------------------")
#
# for i in range(100):#输出小于50大于70的值
#     if i<50 or i>70:
#         print(i)

#print("----------------------------------")
View Code

      练习3,登陆程序加强版

# _user="Louis"
# _password="123456"
# counter=0
#
# while counter<3:#当while后面的条件成立(True),才会执行下面的代码
#     username=input("Username")
#     password=input("Password")
#
#     if username==_user and password==_password:
#         print("welcome %s login..."%_user)
#         break#跳出,中断
#     else:
#         print("invalid username or password !")
#     counter+=1
# else:
#     print("你尝试太多次了,请找回密码再试!!!")

print("------------打印三次后还添加条件----------------------")
_user="Louis"
_password="123456"
counter=0

while counter<3:#当while后面的条件成立(True),才会执行下面的代码
    username=input("Username")
    password=input("Password")

    if username==_user and password==_password:
        print("welcome %s login..."%_user)
        break#跳出,中断
    else:
        print("invalid username or password !")
    counter+=1
    if counter==3:
        keep_going_choice=input("还想继续玩吗?(y/n)")
        if keep_going_choice=="y":
            counter=0
else:
    print("你尝试太多次了,请找回密码再试!!!")
View Code

 

posted @ 2018-06-27 20:40  乐观的小孩  阅读(345)  评论(0编辑  收藏  举报