python 语法

    科技2023-11-13  83

    python 语法

    Sharing my notes that I prepared to remember the python syntax from already known language syntax. (Swift 4.2; Python 3.7)

    分享我准备记住的已知语法中的python语法的注释。 (快速4.2; Python 3.7)

    “The Loci method is one of the most ancient memorization tools known, and is based on attaching individual items you need to remember, to individual points on a route you are familiar with, so you can easily recall the items as you “walk” that route in your mind.”

    “ 基因座方法是已知的最古老的记忆工具之一,它基于将您需要记住的单个项目附加到您熟悉的路线上的各个点上,因此您可以在“行走”时轻松回忆这些项目。在你的脑海中前进。”

    Basics

    基本 Collection Types

    集合类型 Class, Struct

    类,结构 Closures

    关闭 Exception Handling

    异常处理 Unit Testing

    单元测试

    导入模块 (Import Modules)

    Swift

    Swift

    import Foundation

    typealias a module

    类型别名模块

    typealias SMSomeStruct = SomeModule.SomeStruct

    Import only parts from a module

    仅从模块导入零件

    import struct­ SomeModule.SomeStructimport class­ SomeModule.SomeClassimport func SomeModule.someFunc

    Python

    Python

    import calculator

    typealias a module

    类型别名模块

    import calculator as calc

    Import only parts from a module

    仅从模块导入零件

    from calculator import multiply# usageresult = multiply(2, 4)

    常数 (Constants)

    Swift

    Swift

    let maximumHeight = 50

    Python

    Python

    Create constant.py file (global file)

    创建constant.py文件(全局文件)

    PI = 3.14GRAVITY = 9.8MAXIMUM_HEIGHT = 50

    Usage:

    用法:

    import constantconstant.MAXIMUM_HEIGHT

    变数 (Variables)

    Swift

    Swift

    var userName = "Sit Bibendum"userName = "Malesuada Mollis"

    Python

    Python

    userName = "Sit Bibendum"userName = "Malesuada Mollis"# Assigning multiple values to multiple variablesa, b, c = 5, 3.2, "Hello"# to assign the same value to multiple variables at oncex = y = z = 1000

    注释 (Comments)

    Swift

    Swift

    // single comment/* multi line comment */

    Python

    Python

    # python comment, no multiline comment

    打印 (Print)

    Swift

    Swift

    let id = 525let name = "Porta Tortor"print(id, name) // 525 Porta Tortorprint(id, name, separator: ", ") // 525, Porta Tortor

    Python

    Python

    id = 525name = "Porta Tortor"print(id, name) # 525 Porta Tortorprint(id, name, sep=', ') # 525, Porta Tortor

    打印终止符用法 (Print Terminator Usage)

    Swift

    Swift

    for i in 1 ..< 10 { print(i, terminator: " ") if i % 3 == 0 { print() }}output: 1 2 3 4 5 6 7 8 9

    Python

    Python

    for i in range(1, 10): print(i, end=' ') if i % 3 == 0: print()output: 1 2 3 4 5 6 7 8 9

    多行字符串 (Multiline Strings)

    Swift

    Swift

    let html ="""<html> <body> </body></html>"""

    Python

    Python

    html = """<html> <body> </body></html>"""

    (or) using single quotes

    (或)使用单引号

    html2 = '''<html> <body> </body></html>'''

    字符串插值 (String Interpolation)

    Swift

    Swift

    let id = 525let name = "Porta Tortor"let msg = "\(id): \(name)" // 525: Porta Tortor

    Python

    Python

    id = 525name = "Porta Tortor"msg = "%d: %s" % (id, name) # 525: Porta Tortormsg = "{}: {}".format(id, name) # 525: Porta Tortormsg = "{0}: {1}".format(id, name) # 525: Porta Tortor

    字符串串联 (String Concatenation)

    Swift

    Swift

    let userID = 525let firstName = "Cursus"let lastName = "Dolor"let text = firstName + " " + lastName + " (" + String(userID) + ")."output:

    Python

    Python

    userID = 525firstName = "Cursus"lastName = "Dolor"text = firstName + " " + lastName + " (" + str(userID) + ")."output:

    如何获取对象类型? (How to get object type ?)

    Swift

    Swift

    let height = 5.7type(of: height) // Double.Typeif height is Int { // ..}

    Python

    Python

    height = 5.7type(height) # <type 'float'>if (type(height) is float): # ..

    字符串到整数 (String to Int)

    Swift

    Swift

    let userIDString = "525"let userID = Int(userIDString)

    Python

    Python

    user_id_string = "525"user_id = int(user_id_string)

    二进制到数字 (Binary to Number)

    Swift

    Swift

    let binary = "11001"let number = Int(binary, radix: 2) // 25

    Python

    Python

    binary = "11001"number = int(binary,2) // 25

    布尔型 (Boolean)

    Swift

    Swift

    var isEnabled = true // false

    Python

    Python

    isEnabled = True # False

    元组 (Tuples)

    Swift

    Swift

    let http404Error = (404, "Not Found")let code = http404Error.0let message = http404Error.1// orlet (statusCode, statusMessage) = http404Error

    Python

    Python

    http404Error = (404, "Not Found")code = http404Error[0]message = http404Error[1]

    无,无 (Nil, None)

    Swift

    Swift

    var email: String? = nil

    Python

    Python

    email = None

    声明 (del Statement)

    Swift

    Swift

    // ??

    Python

    Python

    name = Mattis Ridiculusdel name # object will be deleted completlyprint(name) # NameError: "name 'name' is not defined"

    如果声明 (If Statement)

    Swift

    Swift

    var email: String? = nil// Optional wrapif let email = email { print(email)} else { print("n/a") }// Force unwrapif email != nil { print(email!)} else { print("n/a")}Output: n/a

    Python

    Python

    email = Noneif email is not None: print(email)else: print("n/a")

    or

    要么

    if email != None: print(email)else: print("n/a")Output: n/a

    如果有多个条件 (If with Multiple Conditions)

    Swift

    Swift

    if self.x == other.x && self.y == other.y { return true} else { return false}

    Python

    Python

    if (self.x == other.x and self.y == other.y): return Trueelse: return False

    转义字符 (Escape characters)

    Swift

    Swift

    let text = "one\ntwo\nthree"let regExp = "Language: \"Swift\", version: \"4.2\""

    Python

    Python

    text = "one\ntwo\nthree"regExp = "Language: \"Python\", version: \"3.7\""# one two three#

    计数字符 (Counting Characters)

    Swift

    Swift

    let text = "abc 123"text.count // 7

    Python

    Python

    text = "abc 123"len(text) # 7

    枚举 (Enum)

    Swift

    Swift

    enum Color: Int { case red = 1 case green case blue var name: String { switch self { case .red: return "red" case .green: return "green" case .blue: return "blue" } }}// Usage:Color.greenColor.green.nameColor.green.rawValuelet selectedColor = Color.greenif case Color.green = selectedColor { print("Selected right color")} else { print("Wrong color selected \(selectedColor.name)")}

    Python

    Python

    from enum import Enumclass Color(Enum): red = 1 green = 2 blue = 3Color.green # Color.greenColor.green.name # greenColor.green.value # 2# Usage:selectedColor = Color.greenif selectedColor is Color.green: print("Selected Right color")else: print("Wrong color selected: {}".format(selectedColor.name))

    开关 (Switch)

    Swift

    Swift

    switch input { case 0: //.. case 1: break case 2: //..}

    Python

    Python

    python does not have any switch case statement. Alternatively we use dictionary mapping.

    通过参考 (Pass by reference)

    Swift

    Swift

    func swapInts(a: inout Int, b: inout Int) { let temp = a a = b b = temp}var a = 50var b = 100swapInts(a: &a, b: &b)print(a, b)

    Python

    Python

    There are no variables in Python. There are names and objects in - Python and together they appear like variables

    装饰工 (Decorators)

    Swift

    Swift

    // TODO: ??

    Python

    Python

    def validateInputs(input_function): def validation(a, b): if b == 0: print("Can't divide by 0") return return input_function(a, b) # call input function return validation@validateInputsdef div(a, b): return a / bdiv(10,0)# need to check how to achieve Decorator Pattern using python decorators. (ie.. without modifying the source code file)

    收益(而非回报),下一个 (Yield (instead of return), Next)

    Swift

    Swift

    // achieve using closuresfunc makeIncrementer(_ amount: Int) -> () -> Int { var runningTotal = 0 func incrementer() -> Int { runningTotal += amount return runningTotal } return incrementer}let incrementByTen = makeIncrementer(10)incrementByTen()incrementByTen()for _ in 0..<10 { print(incrementByTen())}

    Python

    Python

    def makeIncrementer(amount): runningTotal = 0 while True: runningTotal += amountyield runningTotalincrementerByTen = makeIncrementer(10)next(incrementerByTen) # 10next(incrementerByTen) # 20for i in range(10): print(next(incrementerByTen)) # 30 40 ... 120

    集合类型 (Collection Types)

    数组 (Array)

    阵列运算 (Array Operations)

    Swift

    Swift

    var hetro: [Any] = ["one", 10, 2.5]hetro[0]// Negative Indexing not allowedhetro[1] = "100"hetro.remove(at: 0)hetro.append("five")hetro.append(4.9)hetro.append("five")// No inbuilt method to remove an element directlyhetro.insert(10000, at: 1)

    Python

    Python

    hetro = ["one", 10, 2.5]hetro[0] # one# reverse indexhetro[-1] # 2.5hetro[-2] # 10hetro[1] = "100"# pop at indexhetro.pop(0)# appendhetro.append("five") hetro.append(4.9)hetro.append("five")# remove first occuranceshetro.remove("five")# insert at indexhetro.insert(1, "100000")

    空数组 (Empty array)

    Swift

    Swift

    var list = [Any]()

    Python

    Python

    list = []

    多维数组 (Multidimensional arrays)

    Swift

    Swift

    let matrix = [[1,2,3], [4,5,6], [7,8,9]]matrix[0][0]matrix[2][2]

    Python

    Python

    matrix = [[1,2,3], [4,5,6], [7,8,9]]matrix[0][0] matrix[2][2]

    阵列长度 (Array Length)

    Swift

    Swift

    let list = ["zero", "one", "two", "three", "four"]list.count

    Python

    Python

    list = ["zero", "one", "two", "three", "four"]len(list)

    阵列切片 (Array Slicing)

    Swift

    Swift

    let list = ["zero", "one", "two", "three", "four"]list[1...4]list[..<2]list[2...]

    Python

    Python

    list = ["zero", "one", "two", "three", "four"]list[1:4] # ['one', 'two', 'three']list[ :2] # ['zero', 'one']list[2: ] # ['two', 'three', 'four']

    list[start: end-1] understanding-pythons-slice-notation

    list [start:end-1] 理解-pythons-slice-notation

    具有默认值的数组 (Array with a Default Value)

    Swift

    Swift

    var countArray = Array(repeating: 0, count: 10) // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    Python

    Python

    countArray = [0] * 10# orcountArray = [0 for i in range(10)] # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    (Set)

    Swift

    Swift

    var basket: Set = ["one", "two", "three"]let isExists = basket.contains("one")basket.insert("four")basket.update(with: "four") // if aleady contains will return `input`; else returns nil;// there is no inbuild method for appending listbasket.remove("four")basket.popFirst()basket.removeAll()

    Python

    Python

    basket = { "one", "two", "three"}# orbasket = set({ "one", "two", "three"})isExists = "one" in basketbasket.add("four")basket.update(["five", "six"])basket.remove("six")basket.discard("six") # If the item to remove does not exist, discard() will NOT raise an error.# take random elementrandom = basket.pop() # threebasket.clear() # set([])

    空集 (Empty Set)

    Swift

    Swift

    var basket = Set<AnyHashable>() // Set([])

    Python

    Python

    basket = set() # set([])

    辞典 (Dictionaries)

    Swift

    Swift

    var info:[String: Any] = [ "name": "Elit Vestibulum", "age": 43]let name = info["name"]info["age"] = 54info["country"] = "Cursus Elit"info.updateValue("Nibh Dapibus", forKey: "city")info.valuesinfo.keysinfo.removeValue(forKey: "age")info.removeAll()

    Python

    Python

    info = { "name" : "Elit Vestibulum", "age": 43}# get name = info["name"] name = info.get("name")# updateinfo["age"] = 54# add new pairsinfo["country"] = "Cursus Elit"info.update({"city": "Nibh Dapibus"}) # get all valuesvalues = info.values() # get all keyskeys = info.keys()# remove pairinfo.pop("age")info.clear() # {}

    空字典 (Empty Dictionary)

    Swift

    Swift

    var info = [String: Any]() // [:]

    Python

    Python

    info = dict() # {}

    (Class)

    你好,世界 (Hello World)

    Swift

    Swift

    class MyClass { init() { print("Hello World") }}let myObject = MyClass()

    Python

    Python

    class MyClass: def __init__(self): print("Hello World")myObject = MyClass()

    基础数学课范例 (Basic Math Class Example)

    Swift

    Swift

    class Math { let pi = 3.14 func areaOfCircle(radius r: Double) -> Double { return pi * (r * r) } func sum(a: Int, b: Int) -> Int { return a + b }}let math = Math()let area = math.areaOfCircle(radius: 10)let sum = math.sum(a: 5, b: 2)

    Python

    Python

    class Math: pi = 3.14 # default initializer; to access `self` is required (ie. self.pi) def areaOfCircle(self, radius: float) -> float: return self.pi * (radius * radius) def sum(self, a, b): return a + b # Function annotations are completely optional metadata information about the types used by user-defined functions def substract(self, a: int, b: int) -> int: return a - bmath = Math()area = math.areaOfCircle(10) # 314.0sum = math.sum(2, 5) # 7result = math.substract(2, 5) # -3

    初始化参数 (Init Params)

    Swift

    Swift

    class Table { let multipler: Int init(input: Int) { self.multipler = input } func printTable(limit: Int = 10) { for i in 1 ... limit { print("\(multipler) * \(i) = \(i * multipler)") } print() }}let table2 = Table(input: 2)table2.printTable()table2.printTable(limit: 5)

    Python

    Python

    class Table: def __init__(self, input): self.multipler = input def printTable(self, limit = 10): for i in range(1, limit): print("%d * %d = %d" % (self.multipler, i, self.multipler * i)) print()table_2 = Table(2)table_2.printTable()table_2.printTable(5)output:2 * 1 = 2 ..... 2 * 9 = 182 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8

    类继承,重写方法 (Class Inheritance, Overriding Methods)

    Swift

    Swift

    class Employee { let id: Int let name: String init(id: Int, name: String) { self.id = id self.name = name } func printDetails() { print("id: \(id)") print("name: \(name)") }}class Technician: Employee { let labId: String init(id: Int, name: String, labId: String) { self.labId = labId super.init(id: id, name: name) } override func printDetails() { super.printDetails() print("labId: \(labId)") }}let technician = Technician(id:

    Python

    Python

    class Employee: def __init__(self, id, name): self.id = id self.name = name def printDetails(self): print("id: %s" % (self.id)) print("name: %s" % (self.name))class Technician(Employee): def __init__(self, id, name, labID): self.labID = labID super().__init__(id, name) # Override method def printDetails(self): super().printDetails() print("labID: %s" % (self.labID))technician = Technician(2693, "Nibh Fringilla", "LAB001")professor.printDetails()output:id: 2693 name: Nibh Fringilla labID: LAB001

    私人的 (Private)

    Swift

    Swift

    class Hacker { private var name = "Amet Lorem" private func details() { print(name) } func publicDetails() { print("random name") }}let hacker = Hacker()hacker.publicDetails() // random name

    Python

    Python

    class Hacker: __name = "Amet Lorem" def __details(self): print(self.__name) def publicDetails(self): print("random name")hacker = Hacker()hacker.publicDetails() # random name# "'Hacker' object has no attribute '..'" -- error for below commandshacker.namehacker.__namehacker.details()hacker.__details()

    结构,数据类 (Structs, Data Classes)

    Swift

    Swift

    struct Center { let x: Float let y: Float}// Equatable ~= __eq__// Hashable ~= __hash__// CustomStringConvertible ~= __repr__

    Python

    Python

    from dataclasses import dataclass@dataclassclass Center: x: float y: floatc1 = Center(4,5)print(c1) # Center(x=4, y=5)

    Adventage of Data Classses: Auto generated _init_, _repr_, _eq_, ..

    数据类的出现:自动生成的_ init _ ,_ repr _ ,_ eq _ ,..

    ref: https://medium.com/mindorks/understanding-python-dataclasses-part-1-c3ccd4355c34

    参考: https : //medium.com/mindorks/understanding-python-dataclasses-part-1-c3ccd4355c34

    @dataclass(frozen = True) # immutable# To control the auto generated methods@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)

    same functionality using class:

    使用类的相同功能:

    class Center: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): if (self.x == other.x and self.y == other.y): return True else: return False def __repr__(self): return 'Point(x=%s, y=%s)' % (self.x, self.y) # .. have to implement all functions manually

    关闭 (Closures)

    基本的 (Basic)

    Swift

    Swift

    var addTen = { $0 + 10 }addTen(5) # 15

    Python

    Python

    lambda arguments: expression

    lambda参数:表达式

    Note: Only one expression (a + 10) is allowed with lambda functions.

    注意: lambda函数只允许使用 一个表达式( a + 10 ) 。

    addTen = lambda a: a + 10addTen(5) # 15# or use `def` if cannot achieve in single expressiondef addTen(a): .. .. return a + 10

    多个输入 (Multiple inputs)

    Swift

    Swift

    var product: ((Int, Int) -> (Int)) = { a, b in return a * b}product(5, 10)

    Python

    Python

    product = lambda a, b: a * bproduct(5, 10) # 50

    Lambda函数 (Lambda function)

    Swift

    Swift

    func makeNTimes(_ n: Int) -> ((Int) -> Int) { return { a in return a * n }}var doubler = makeNTimes(2)doubler(10)var tripler = makeNTimes(3)tripler(10)

    Python

    Python

    def makeNTimes(n): return lambda a: a * ndoubler = makeNTimes(2)doubler(10) # 20tripler = makeNTimes(3)tripler(10) # 30

    地图 (Map)

    Swift

    Swift

    let numbers = [1, 2, 3, 4, 5]let result = numbers.map { $0 * 2 }

    Python

    Python

    map(function, iterables)

    地图(函数,可迭代)

    numbers = [1, 2, 3, 4, 5]multiply2 = lambda x: x * 2result = list(map(multiply2, numbers)) # orresult = list(map(lambda x: x * 2, [1, 2, 3, 4, 5]))output:[2, 4, 6, 8, 10]

    过滤 (Filter)

    Swift

    Swift

    let numbers = [1, 2, 3, 4, 5, 6]let result = numbers.filter { $0 % 2 == 0 }

    Python

    Python

    filter(function, iterable)

    过滤器(功能,可迭代)

    numbers = [1, 2, 3, 4, 5, 6]result = list(filter(lambda x : x % 2 == 0, numbers)) # [2, 4, 6]

    减少 (Reduce)

    Swift

    Swift

    let numbers = [1, 2, 3, 4, 5, 6]let res = numbers.reduce(1) { (result, value) -> Int in return result * value}

    Python

    Python

    reduce(function, iterable)

    减少(功能,迭代)

    from functools import reducenumbers = exp = lambda x: x * 2product = reduce(exp, numbers) # 720

    异常处理 (Exception Handling)

    用户定义的异常 (User-defined Exceptions)

    Swift

    Swift

    enum InputValidationError: Error { case invalidInput(String)}func validateAge(_ age: Int) throws { if age < 0 { throw InputValidationError.invalidInput("Only positive integers are allowed") }}do { try validateAge(-2)} catch InputValidationError.invalidInput(let message) { print("Exception: ", message)}

    Python

    Python

    class InputValidationError(Exception): def __init__(self, message): self.message = messagedef validateAge(age): if age < 0: raise InputValidationError('Only positive integers are allowed')try: validateAge(-1)except InputValidationError as error: print("Exception: ", error.message)except: print("something is wrong")

    (Example)

    Swift

    Swift

    enum CommonError: Error { case divisionByZero}func divide(_ a: Int, by b: Int) throws -> Int { if b == 0 { throw CommonError.divisionByZero } return a / b}var result: Intdo { result = try divide(10, by: 0)} catch CommonError.divisionByZero { print("division by zero!")} catch { //}Note: - In Swift there is no functionality to catch arbitrary runtime errors.- no `finally`make use of `defer`

    Python

    Python

    def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is ", result) finally: print(".. executing finally")>> divide(2, 1)output:result is 2.0.. executing finally>> divide(2, 0)division by zero!.. executing finally

    单元测试 (Unit Tests)

    (Example)

    Swift

    Swift

    import XCTest@testable import AppTargetclass AppHelperTests: XCTestCase { let calculator = Calculator() override func setUp() { super.setUp() // .. } override func tearDown() { // .. super.tearDown() } func testAdd() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5) } func testMultiply() { let result = calculator.multiply(2, 3) XCTAssertEqual(result, 6) }}

    Python

    Python

    calculator.py

    计算器

    def add(a, b): return a + bdef multiply(a, b): return a * bimport unittestimport calculatorclass TestCalculator(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_add(self): result = calculator.add(2, 3) self.assertEqual(result, 5) def test_multiply(self): result = calculator.multiply(2, 3) self.assertEqual(result, 6)

    Running Tests

    运行测试

    if __name__ == '__main__': unittest.main()# Console output:..--------------------------------------------------------------------Ran 2 tests in 0.000sOK

    pass Statement:

    通过声明:

    used when a statement is required syntactically but you do not want any command or code to execute.

    在语法上需要语句但您不希望执行任何命令或代码时使用。

    List of assets: ref: https://docs.python.org/2/library/unittest.html

    资产列表:参考: https : //docs.python.org/2/library/unittest.html

    Corrections are welcome :). Thank You.

    欢迎更正:)。 谢谢。

    翻译自: https://medium.com/@kiran.sarella/syntax-comparison-swift-vs-python-5a3d6231d0fe

    python 语法

    Processed: 0.018, SQL: 8