1. Pyhton基础语法(1)

1. Python变量与字符串

1.1 Python数据类型

数据类型 分类
Number(数字) int、float、bool、complex、long
String(字符串) NULL
List(列表) NULL
Tuple(元组) NULL
Set(集合) NULL
Dictionary(字典) NULL
Bool(布尔) NULL
  1. 不可变数据(变量对应的值中的数据是不能被修改,如果修改就会生成一个新的值从而分配新的内存空间):Number、String、Tuple、Bool
  2. 可变数据(变量对应的值中的数据可以被修改,但内存地址保持不变):List、Dictionary、Set

1.2 字符串操作

  1. int len(String) --> String长度

  2. String String.find(str[,strat_index,end_index]) --> 正序索引,str是否在String中,如果是返回开始的索引,否则,返回-1

  3. String String.rfind(str[,start_index,end_index]) --> 倒序索引,str是否在String中,如果是返回开始的索引,否则,返回-1

  4. String String.index(str[,start_index,end_index]) --> 正序索引,str是否在String中,如果是返回开始的索引,否则,报错

  5. String String.rindex(str[,start_index,end_index]) --> 倒序索引,str是否在String中,如果是返回开始的索引,否则,报错

  6. int String.count(str[,start_index,end_index]) --> String中str的次数

  7. String String.replace(str1,str2,count) --> 将String中的str1替换为str2,最多替换count次

  8. String String.capitalize() --> String第一个字母大写

  9. String String.title() --> String每一个单词首字母大写

  10. String String.lower() --> String大写转小写

  11. String String.upper() --> String小写转大写

  12. String String.strip() --> 删除String两端空白字符

  13. String String.lstrip() --> 删除String左边空白字符

  14. String String.rstrip() --> 删除String右边空白字符

  15. List String.splitlines() --> 按行分割

  16. List String.split(str) -->按str分割

    len("hello") --> 5  #1
    string="hello"
    string.find("e") --> 1  #2
    string.rfind("l")  --> 3  #3
    string.index("e") --> 1  #4
    string.rindex("l") --> 3  #5
    string.count("l") --> 2  #6
    string.replace("l","e",3) --> "heeeo"  #7
    string.capitalize() --> "Hello" #8
    "this is a test".title() --> "This Is A Test"  #9
    "HELLO".lower() --> "hello"  #10
    string.upper() --> "HELLO"  #11
    " hello ".strip() --> "hello"  #12
    " hello ".lstrip() --> "hello "  #13
    " hello ".rstrip() --> " hello"  #14
    "a\nb\nc\nd".splitlines() --> ["a","b","c","d"]  #15
    "a,b,c,d".split(",") --> ["a","b","c","d"]  #16
    

    ==c/c++/java中字符为单引号(‘ ’),字符串为双引号(“ ”).python中单引号和双引号都为字符串==

    ==python支持a=b=c=1的赋值==

1.3 输入输出与格式化输出

1.3.1 输入

  1. String input(your_hint)

1.3.2 输出

1.3.2.1 输出
  1. print()
1.3.2.2 字符串格式化输出
  1. format函数使用(有占位符无索引)

    print("{} love {}".format("I","you"))
    
    Result:
     I love you
    
  2. format函数使用(有占位符有索引)

    print("{1} love {0}".format("you","I"))
    
    Result:
     I love you
    
  3. format函数使用(有占位符有别名)

    print("{blank1} love {blank0}".format(blank0="you",blank1="I"))
    
    Result:
        I love you
    
1.3.2.3 数字格式化输出
  1. 保留小数

    print(format(123.456,"0.2f"))
    
    Result:
        123.45
    
  2. 千分位分割符

    print(format(123456,","))
    
    Result:
        123,456
    
  3. 货币格式输出

    print(format(123456,"0,.2f"))
    
    Result:
        123,456.00
    
1.3.2.3 数字和字符串格式化输出
print("My name is {} , my weight is {:0.2f}".format("Jack",123.456))

Result:
    My name is Jack , my weight is 123.46
1.3.2.4 早期格式化输出
print("My name is %s , I am %d years old , My weight is %0.2f kg."%("Jack",25,120))

Result:
    My name is Jack , I am 25 years old , My weight is       120.00 kg.

1.4 注释

语言 样式
c/c++/java //注释一行
/* ...... / 注释若干行(编译器可以看懂*)
/*……/文档注释
python #
‘’’……….‘’’
“””………“””

2. Pyhton流程控制语句

2.1 控制语句

python --> if-elif-else
c/c++ --> if-else && if-else if-else && switch-case-defalut
java --> if-else && if-else if-else && switch-case(->)-defalut

2.2 循环控制

python --> while && while-else && for-in && for-in-else
c/c++/java --> while && do-while && for && for(:)

2.3 跳出循环

c/c++/java/python --> 
contiue --> 跳出当前循环
break --> 跳出多重循环

3. 常用运算符的使用

3.1 与c/c++/java不同的运算符

无三目运算符(? :)
**  2**3=8 幂运算,相当于pow(x,y)
/  10/3=3.33333 除法运算,而在c/c++/java中还要看数据类型
//  向下取整的除法 
i++/i-- python中不存在
in  数据是否在其中
is  是否指向同一块内存

4. 列表与字典

4.1 列表(List)

4.1.1 介绍

  1. 列表中数据结构按顺序排列
  2. 列表有正序和倒序两种索引(正序索引从0开始,倒序索引从-1开始)
  3. 列表可储存任意类型的数据,且允许重复

4.1.2 列表的创建

  1. list=[1,2,”3”,”4”]
  2. list=[]

4.1.3 列表的取值

  1. 索引取特定值与范围值

  2. int List.index(string value) --> 传入List中的值,获取第一次出现的位置,如果不存在,则报错

    list=[1,2,3,4,5]
    list[2] --> 3
    list[-3] --> 3
    list.index(2) --> 1
    list.index(0) --> ValueError
    

4.1.4 遍历列表

  1. for(迭代变量)-in(可迭代对象)

    fruits=["apple","banana","orange","apple"]
    for fruit in fruits:
        print("I like ",fruit)
        
    Result:I like  apple
        I like  banana
           I like  orange
           I like  apple   
    
  2. while循环

    i=0
    while i<len(fruits):
        print("I like ",fruits[i])
        i+=1
        
    Result:I like  apple
        I like  banana
           I like  orange
           I like  apple    
    

4.1.5 列表的反转与排序

  1. void List.reverse() -–> 将列表反转并更新列表

    list=[8,7,6,5,4,3,2,1]
    list.reverse()
    list --> [1,2,3,4,5,6,7,8]
    
  2. void List.sort()-->正序排列并更新原列表

    list=[1,4,5,7,4,2,3,6]
    list.sort()
    list --> 1,2,3,4,4,5,6,7
    
  3. void List.sort(reverse=True) -->倒序排列并更新原列表

    list=[1,4,5,7,4,2,3,6]
    list.sort(reverse=True)
    list --> 7,6,5,4,4,3,2,1
    

4.1.6 列表的新增、修改、删除操作

  1. void List.append(new_element) -->列表末尾追加新元素,括号中什么就追加什么

  2. void List.insert(index,new_element) -->指定索引插入新元素

  3. void List[index]=new_element -->更新指定索引位置数据

  4. void List[begin_index:end_index]=NewList -->更新指定范围数据

  5. void List.remove(old_element) -->删除指定元素,只删除一个

  6. Deleted_Element List.pop(index) -->按索引删除指定元素

  7. void List[begin_index:end_index]=[] -->删除

    list=[1,2,3,4,5]
    list.append(6)  #1
    list --> [1,2,3,4,5,6]
    list.insert(0,0)  #2
    list --> [0,1,2,3,4,5,6]
    list[0]=2  #3
    list --> [2,1,2,3,4,5,6]
    list[0,2]=[3,4]  #4
    list --> [3,4,2,3,4,5,6]
    list.remove(3)  #5
    list --> [4,2,3,4,5,6]
    list.pop(0) --> 4  #6
    list --> [2,3,4,5,6]
    list[0:2]=[]  #7
    list --> [4,5,6]
    

4.1.7 列表其它常用方法

  1. int List.count(element) --> List中元素数量

  2. void List.append(append_list) --> 将append_list/element加入到List

  3. void List.extend(append_list) --> 将append_list中元素放入List

  4. boolean element in List --> element是否在List中

  5. newList List.copy() / = --> 复制List,不指向一块内存 / 指向同一块内存

  6. boolean List1 is List2 --> List1、List2是否指向同一块内存

  7. void List.clear() --> 清空List

    list=[1,2,3,4,5,1]
    list.count(1) --> 2  #1
    list.extend([1,2,3])  #3
    list --> [1,2,3,4,5,1,1,2,3]
    list.append([1,2])  #2
    list --> [1,2,3,4,5,1,1,2,3,[1,2]]
    1 in list -->True  #4
    list1=list.copy()  #5
    list1 --> [1,2,3,4,5,1,1,2,3,[1,2]]
    list2=list  #5
    list2 --> [1,2,3,4,5,1,1,2,3,[1,2]]
    list1 is list --> False  #6
    list2 is list --> True  #6
    list.clear()  #7
    list --> []
    

4.1.8 项目中的使用场景:嵌套列表

  1. [[name,age,salary],[name,age,salary],[name,age,salary],[name,age,salary]]

  2. 实例

    empList = []
    while True:
        string = input("Please input info:")
        if string == "":
            print("Exited")
            print(empList)
            break
        else:
            personalList = string.split(",")
            if len(personalList) == 3:
                empList.append(personalList)
            else:
                print("Input info is wrong")
               
    Result:
        Please input info:jack,27,5000
        Please input info:marry,30,5000
        Please input info:
        Exited
        [['jack', '27', '5000'], ['marry', '30', '5000']]
    

4.1.9 列表储存数据的问题

  1. 列表在表达结构化数据时语义不明确
  2. 结构化数据是指有明确属性,明确表示规则的数据
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。