All Posts All Posts

Python Syntax Fundamentals

April 11, 2017·
Software Engineering
·3 min read
Tecker Yu
Tecker Yu
AI Native Cloud Engineer × Part-time Investor

Records fundamental Python knowledge points that differ from other programming languages

Boolean Type

True

False

Division

/ Default division is precise division

// This is the typical operation to get the integer part of quotient

Characters (Similar to C ASCII codes)

ord() Character corresponding to encoding

chr() Encoding to character

'aaa'.encode('utf-8') Convert to corresponding encoding format as bytes

'aaa'.decode('utf-8') Convert from bytes to utf-8 encoding

Formatted Output

r = 18.0555
'%.2f%%' %r
# '18.06%'

Data Type: List (Analogous to Array)

Get number of list elements: len(variable_name)

Accessing element with negative index means counting from the end

Append element to end: vary.append(...)

Insert at specified position: vary.insert(1, 'Jack')

Remove last element: vary.pop()

Remove specified position: vary.pop(2)

Elements can have different data types

Data Type: Tuple

Compared to list, arrays defined this way have elements that are not directly mutable, making data more secure

Indirect change principle: tuple keeps the element reference unchanged, but the content being referenced may be mutable, for example when the element is a list

t = ('A', 'B', 'C')

If Statement

: Replaces curly brace blocks

elif Equivalent to else if in other languages

Loops

for-in loop for x in ...:

continue Break current iteration and proceed to next iteration

break Exit the loop body

Dict Key-Value Pairs

d = {'A':11,'B':22,'C':33}
d['B']
# 22

When key is not found, an error occurs, so check key in d return value before searching

Or

d.get('B', -1) Second parameter specifies the value to return when not found

key in dict must be immutable

Delete: d.pop(key)

Set Key Collection

Initialization requires passing a list, input elements cannot have duplicates

s = set([5,5,6,7,7,6,7])
# {5, 6, 7}

Add: add(key)

Remove: remove(key)

String Object

str.replace('a', 'A') Replace a with A but the method returns a new string, the original str is immutable!

Basic Functions

abs()

max() Can accept any number of parameters and only returns the maximum

a = abs Assign abs function reference to a, calling a() has the same effect

Type Conversion

int(variable_to_convert)

Others similar

Function Definition

def Replaces function

Empty Indented Block

pass

Function Return Values

Can actually have multiple!! My worldview…

def goBack(x,y)
	return x,y

a,b = goBack(1,2) 

Reason: Returns tuple

Type Checking

def goBack(x,y)
	if isinstance(x, (int, float)):
		return x,y
# Allows int and float types

Parameters

def power(x, n=2):
# n defaults to 2

Default parameters must point to immutable objects

Parameters can be list or tuple, using variable parameters

Variable parameters def calc(*numbers): Multiple parameters automatically assembled into tuple

Keyword parameters def person(name, age, **kw): Convenient for extending function parameters

The order of parameter definition must be: required parameters, default parameters, variable parameters, named keyword parameters, and keyword parameters

Tail Recursion Optimization for Recursive Functions

Refers to calling itself when returning from a function, and the return statement cannot contain expressions

Note: Standard interpreter does not support this usage

Views