Python语法学习

安装相关

"如果尚未安装 PIP,可以从此页面下载并安装:https://pypi.org/project/pip/"
"pip install numpy"
"pip install matplotlib"
"pip install camelcase"
"pip uninstall camelcase"
"pip list"

python基本语法

def python基本语法():
    x, y, z = "Orange", "Banana", "Cherry"
    x = y = z = "Orange"
    "(多行)字符串,没有被赋值使会被忽略"
    # 如果要在函数内部更改全局变量,请使用 global 关键字。
    global gx
    gx = "global value fixed"
    # 随机数(整数:0,1,2,3,4,5,6,7,8,9)
    import random
    print(random.randrange(0, 10))
    # 多行字符串,也可以用三个单引号'''
    a = """Python is a widely used general-purpose, high level programming language. 
It was initially designed by Guido van Rossum in 1991 
and developed by Python Software Foundation. 
It was mainly developed for emphasis on code readability, 
and its syntax allows programmers to express concepts in fewer lines of code."""
    print(a[0])  # 字符串是数组
    a.strip()  # strip()方法删除开头和结尾的空白字符:
    a.lower()
    a.upper()
    a.replace("Python", "Java")
    a.split(" ")
    print("My name is {}, and I am {}".format("Alex", 100))
    print("My name is {1}, and I am {0}".format(100, "Alex"))

    if 5 > 2 and 9 > 0:
        pass  # 各种语句不能为空时,可以用pass
    elif 5 < 4:
        print("case2")
    else:
        print("case3")
    a = 10
    if 5 > 2: print("case1")  # if简写
    print("case1") if 5 > 2 else print("case2")  # if-else简写

    i = 1
    while i < 7:
        print(i)
        if i == 5:
            break
        i += 1

    for x in range(10):
        print(x)
    for x in range(3, 10):
        print(x)
    for x in range(3, 50, 6):
        print(x)
    else:
        print("for end")

    try:
        print(x)
    except:
        print("An exception occurred")

    try:
        print(x)
    except NameError:
        print("Variable x is not defined")
    except:
        print("Something else went wrong")

    try:
        print("Hello")
    except:
        print("Something went wrong")
    else:
        print("Nothing went wrong")

    try:
        print(x)
    except:
        print("Something went wrong")
    finally:
        print("The 'try except' is finished")

    # x = -1
    # if x < 0:  # 抛出异常。
    #     raise Exception("Sorry, no numbers below zero")
    # x = "hello"
    # if not type(x) is int:
    #     raise TypeError("Only integers are allowed")

    quantity = 3
    itemno = 567
    price = 52
    myorder = "I want {0} pieces of item number {1} {1} for {2:.2f} dollars."
    print(myorder.format(quantity, itemno, price))

    myorder = "I have a {carname}, it is a {model}."
    print(myorder.format(carname="Porsche", model="911"))

    print("Enter your name:")
    x = input()
    print("Hello ", x)

python数据类型

def python数据类型():
    x = "Hello World"  # 文本类型:	str
    x = 29  # 数值类型:int
    x = 29.5  # 数值类型:float
    x, a, b, c = 1j, 27e4, 15E2, -49.8e100  # 数值类型:complex
    x = ["apple", "banana", "cherry"]  # 序列类型:list
    x = ("apple", "banana", "cherry")  # 序列类型:tuple
    x = range(6)  # 序列类型:range
    x = {"name": "Bill", "age": 63}  # 映射类型:dict
    x = {"apple", "banana", "cherry"}  # 集合类型:set
    x = frozenset({"apple", "banana", "cherry"})  # 集合类型:frozenset
    x = True  # 布尔类型:bool
    x = b"Hello"  # 二进制类型:bytes
    x = bytearray(5)  # 二进制类型:bytearray
    x = memoryview(bytes(5))  # 二进制类型:memoryview
    # 类型转换
    print(8 > 7)
    print(bool("Hello"))  # false: ()、[]、{}、""、0、None,其它都是true
    print(type(x))
    a = float(1)
    b = int(2.2)
    c = complex(3.0)
    d = str(4)

python字符串方法

def python字符串方法():
    string = ""
    string.capitalize()  # 把首字符转换为大写。
    string.casefold()  # 把字符串转换为小写。
    string.center("")  # 返回居中的字符串。
    string.count("")  # 返回指定值在字符串中出现的次数。
    string.encode()  # 返回字符串的编码版本。
    string.endswith()  # 如果字符串以指定值结尾,则返回 true。
    string.expandtabs()  # 设置字符串的 tab 尺寸。
    string.find("")  # 在字符串中搜索指定的值并返回它被找到的位置。
    string.format()  # 格式化字符串中的指定值。
    string.format_map()  # 格式化字符串中的指定值。
    string.index("")  # 在字符串中搜索指定的值并返回它被找到的位置。
    string.isalnum()  # 如果字符串中的所有字符都是字母数字,则返回 True。
    string.isalpha()  # 如果字符串中的所有字符都在字母表中,则返回 True。
    string.isdecimal()  # 如果字符串中的所有字符都是小数,则返回 True。
    string.isdigit()  # 如果字符串中的所有字符都是数字,则返回 True。
    string.isidentifier()  # 如果字符串是标识符,则返回 True。
    string.islower()  # 如果字符串中的所有字符都是小写,则返回 True。
    string.isnumeric()  # 如果字符串中的所有字符都是数,则返回 True。
    string.isprintable()  # 如果字符串中的所有字符都是可打印的,则返回 True。
    string.isspace()  # 如果字符串中的所有字符都是空白字符,则返回 True。
    string.istitle()  # 如果字符串遵循标题规则,则返回 True。
    string.isupper()  # 如果字符串中的所有字符都是大写,则返回 True。
    string.join("")  # 把可迭代对象的元素连接到字符串的末尾。
    string.ljust("")  # 返回字符串的左对齐版本。
    string.lower()  # 把字符串转换为小写。
    string.lstrip()  # 返回字符串的左修剪版本。
    string.maketrans()  # 返回在转换中使用的转换表。
    string.partition()  # 返回元组,其中的字符串被分为三部分。
    string.replace("", "")  # 返回字符串,其中指定的值被替换为指定的值。
    string.rfind()  # 在字符串中搜索指定的值,并返回它被找到的最后位置。
    string.rindex()  # 在字符串中搜索指定的值,并返回它被找到的最后位置。
    string.rjust("")  # 返回字符串的右对齐版本。
    string.rpartition()  # 返回元组,其中字符串分为三部分。
    string.rsplit()  # 在指定的分隔符处拆分字符串,并返回列表。
    string.rstrip()  # 返回字符串的右边修剪版本。
    string.split()  # 在指定的分隔符处拆分字符串,并返回列表。
    string.splitlines()  # 在换行符处拆分字符串并返回列表。
    string.startswith()  # 如果以指定值开头的字符串,则返回 true。
    string.strip()  # 返回字符串的剪裁版本。
    string.swapcase()  # 切换大小写,小写成为大写,反之亦然。
    string.title()  # 把每个单词的首字符转换为大写。
    string.translate()  # 返回被转换的字符串。
    string.upper()  # 把字符串转换为大写。
    string.zfill()  # 在字符串的开头填充指定数量的 0 值。

python运算

def python运算():
    a = 1 + 1
    a = 1 - 1
    a = 1 * 1
    a = 1 / 1
    a = 102 % 10  # 取余 = 2
    a = 2**10  # 取幂 = 1024
    a = 67 // 10  #整除 = 6

    x = 10
    a = x > 3 and x < 10
    a = x > 3 or x < 4
    a = not (x > 3 and x < 10)

    a = "Python" in "Python is a language"
    a = "Python" not in "Python is a language"

python数组

def python数组():
    thislist = [
        "apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"
    ]
    print(thislist)
    print(len(thislist))  # 数组长度
    print(thislist[1])
    print(thislist[-1])
    print(thislist[2:5])  # 数组裁剪,包括2不包括5
    print(thislist[-5:-1])  # 数组裁剪从后面计算,包括-1不包括-5
    for x in thislist:
        print(x)
    if "apple" in thislist:
        print("Yes, 'apple' is in the fruits list")

    thislist[1] = "mango"  # 替换元素
    thislist.append("orange")  # 添加元素
    thislist.insert(1, "orange")  # 插入元素
    thislist.remove("cherry")  # 删除元素
    thislist.pop()  # 删除最后一项
    del thislist[0]  # 删除指定项
    list1 = thislist.copy()  # 复制列表
    list2 = list(thislist)  # 复制列表
    list1.extend(list2)  # 也可以一个个 append,也可以 list3 = list1 + list2
    thislist.clear()  # 清除列表
    del thislist  # 删除列表
    print(list1)
    # append()在列表的末尾添加一个元素
    # clear()删除列表中的所有元素
    # copy()返回列表的副本
    # count()返回具有指定值的元素数量。
    # extend()将列表元素(或任何可迭代的元素)添加到当前列表的末尾
    # index()返回具有指定值的第一个元素的索引
    # insert()在指定位置添加元素
    # pop()删除指定位置的元素
    # remove()删除具有指定值的项目
    # reverse()颠倒列表的顺序
    # sort()对列表进行排序

python方法

def python方法():
    def 默认参数(country="China"):
        print("I am in " + country)

    默认参数()
    默认参数("England")
    默认参数("USA")

    # 您还可以使用 key = value 语法发送参数。参数的顺序无关紧要。
    # my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")

    def 多个参数(*values):
        for value in values:
            print(value)

    多个参数("A", "B", "C", "D")

    x = lambda a, b, c: a + b + c  # lambda 函数 参数:abc, 返回:a + b + c
    print(x(1, 2, 3))

    def myfunc(n):
        return lambda a: a * n

    mydoubler = myfunc(2)
    mytripler = myfunc(3)
    print(mydoubler(11))
    print(mytripler(11))

python类

def python类():
    class MyClass:
        x = 5

    p1 = MyClass()
    print(p1.x)

    class Person:  # 所有类都有一个名为 __init__() 的函数,它始终在启动类时执行。
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def myfunc(self):  # 它不必被命名为 self,您可以随意调用它,但它必须是类中任意函数的首个参数:
            print("Hello my name is " + self.name)

    p1 = Person("Bill", 63)
    print(p1.name + ":" + str(p1.age))
    p1.myfunc()
    del p1.age  # 删除类的属性
    del p1

    class Student(Person):  # 继承Person
        def __init__(self, name, nickName):
            #当您添加 __init__() 函数时,子类将不再继承父的 __init__() 函数。
            super().__init__(name, 10)
            self.nickName = nickName
            pass

        def welcome(self):
            print("Welcome", self.name, self.nickName, "to the class of",
                self.age)

    s1 = Student("Alex", "大A")
    s1.welcome()

python迭代器

def python迭代器():
    mytuple = ("apple", "banana", "cherry")
    myit = iter(mytuple)
    print(next(myit))
    print(next(myit))
    print(next(myit))

    mystr = "banana"
    myit = iter(mystr)
    print(next(myit))
    print(next(myit))
    print(next(myit))
    print(next(myit))
    print(next(myit))
    print(next(myit))

    class MyNumbers:
        def __iter__(self):
            self.a = 1
            return self

        def __next__(self):
            if self.a <= 20:
                x = self.a
                self.a += 1
                return x
            else:
                raise StopIteration

    myclass = MyNumbers()
    myiter = iter(myclass)
    print(next(myiter))
    print(next(myiter))
    print(next(myiter))
    print(next(myiter))
    print(next(myiter))

    for x in myiter:
        print(x)

python模块

def python模块():
    import Utils
    Utils.printNumber()

    import Utils as util
    util.printNumber()

    import platform  # 内建模块
    x = platform.system()
    print(x)

    x = dir(util)  # dir() 函数可用于所有模块,也可用于您自己创建的模块。
    print(x)

    from Utils import person1  # 仅从模块导入 person1 字典:
    print(person1["age"])

python时间

def python时间():
    import datetime
    x = datetime.datetime.now()
    print(x)
    print(x.year)
    print(x.strftime("%A"))  # 星期

    x = datetime.datetime(2020, 5, 17)  # 创建日期:年、月、日。
    print(x)
    # datetime 对象拥有把日期对象格式化为可读字符串的方法。
    # %a Weekday,短版本 Wed
    # %A Weekday,完整版本 Wednesday
    # %w Weekday,数字 0-6,0 为周日 3
    # %d 日,数字 01-31 31
    # %b 月名称,短版本 Dec
    # %B 月名称,完整版本 December
    # %m 月,数字01-12 12
    # %y 年,短版本,无世纪 18
    # %Y 年,完整版本 2018
    # %H 小时,00-23 17
    # %I 小时,00-12 05
    # %p AM/PM PM
    # %M 分,00-59 41
    # %S 秒,00-59 08
    # %f 微妙,000000-999999 548513
    # %z UTC 偏移 +0100
    # %Z 时区 CST
    # %j 天数,001-366 365
    # %U 周数,每周的第一天是周日,00-53 52
    # %W 周数,每周的第一天是周一,00-53 52
    # %c 日期和时间的本地版本 Mon Dec 31 17:41:00 2018
    # %x 日期的本地版本 12/31/18
    # %X 时间的本地版本 17:41:00
    # %% A % character %

pythonJSON

def pythonJSON():
    import json

    # 一些 JSON:
    x = '{ "name":"Bill", "age":63, "city":"Seatle"}'
    # 解析 x:
    y = json.loads(x)
    # 结果是 Python 字典:
    print(y["age"])

    # Python 对象(字典):
    x = {"name": "Bill", "age": 63, "city": "Seatle"}
    # 转换为 JSON:
    y = json.dumps(x)
    # 结果是 JSON 字符串:
    print(y)  # 无格式
    y = json.dumps(x, indent=4)  # 格式化Json,缩进=4
    print(y)
    y = json.dumps(x, indent=4, separators=("; ", " = "))  # 替换默认分隔符
    print(y)
    y = json.dumps(x, indent=4, sort_keys=True)  # 按照Key排序
    print(y)

    # print(json.dumps({"name": "Bill", "age": 63}))
    # print(json.dumps(["apple", "bananas"]))
    # print(json.dumps(("apple", "bananas")))
    # print(json.dumps("hello"))
    # print(json.dumps(42))
    # print(json.dumps(31.76))
    # print(json.dumps(True))
    # print(json.dumps(False))
    # print(json.dumps(None))

python文件操作

def python文件操作():
    # 文件处理: r读取a追加w写入x创建  t文本b二进制
    filePath = "Python学习/fileTest.txt"
    f = open(filePath, "xt")
    f.write("我是测试文件中的内容")
    f.close()

    f = open(filePath, "rt")
    # print(f.read())
    # print(f.readline())
    for x in f:
        print(x)

    import os  # 删除文件夹(空):os.rmdir()
    if os.path.exists(filePath):
        os.remove(filePath)
        print("delete file")
    else:
        print("The file does not exist")

pythonNumpy

def pythonNumpy():
    "NumPy 是用于处理数组的 python 库。"
    "NumPy 旨在提供一个比传统 Python 列表快 50 倍的数组对象。"
    "NumPy 是一个 Python 库,部分用 Python 编写,但是大多数需要快速计算的部分都是用 C 或 C ++ 编写的。"

    import numpy as np

    print(np.__version__)
    arr = np.array([1, 2, 3, 4, 5])
    print(type(arr))
    print(arr)
    arr = np.array((1, 2, 3, 4, 5))
    print(type(arr))
    print(arr)

    arr = np.array(1)  # 0D数组
    arr = np.array([1, 2, 3])  # 1D数组
    arr = np.array([[1, 2, 3], [1, 2, 3]])  # 2D数组
    arr = np.array([[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]])  # 3D数组
    print(arr)
    print('number of dimensions :', arr.ndim)

    import matplotlib.pyplot as plt
    # x = numpy.random.normal(5.0, 1.0, 100000)
    # plt.hist(x, 100)
    # plt.show()

主函数调用

# gx = "global value"
# python基本语法()
# print(gx)
# python数据类型()
# python字符串方法()
# python运算()
# python数组()
# python方法()
# python类()
# python迭代器()
# python模块()
# python时间()
# pythonJSON()
# python文件操作()
# pythonNumpy()

Utils.py

def printNumber():
    print("1,2,3,4,5,6,7,8,9,0")
person1 = {"name": "Bill", "age": 63, "country": "USA"}
value1 = 123
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值