Python is a high-level programming language developed by Guido von Rossum, with applications in numerous areas, including web programming, scripting, scientific computing, and artificial intelligence.

Life is short, you need Python – Bruce Eckel

人生苦短,我用Python

You’ll come across especially data Types quite often, so in this article I‘ll give you all you need to work with python basic data types and some more advanced functions.

¶ntroduction

First, let us check the python version which installed on your computer:

1
2
3
4
5
6
7
python -V
## or wordy ==> python --version
## or more complicated

# import sys
# print(sys.version_info)
# print(sys.version)
1
Python 3.8.1

Then, print a code convention 🐱

1
2
3
4
5
6
print('hello, world!')
print('hello,' + \
' world!')
# hello, world!
print('hello', 'world', sep=', ', end='!')
## hello, world!
1
2
3
4
5
6
7
8
9
10
11
def shout(word):
"""
This is a multiline comment to help
explain what the docstrings is.
A comment designed to explain code.
So in this function we wanna print word + !.
"""
print(word + "!")

shout("hello, world")
# hello, world!

Firstly, lemme introduce you python variables, here are some rules:

  • A variable name should be started with a letter or the underscore character(cannot start with a number) and only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

    (Unicode characters can be used but not recommended.)

  • Variable names are case-sensitive.

  • Do not use python built-in keywords:

    1
    2
    import keyword
    print(keyword.kwlist)
      ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
    

Next, Blah Blah Blah, We move on to the next chapter🔌

Prerequisite : Basic computer and python knowledge.

Operators

Operators are special symbols in Python that carry out arithmetic or logical computation.

Python has the capability of carrying out calculations, here arithmetic operators summarized in the following table:

Operators Description
+ OR - plus and minus to perform addition and subtraction or represent such as +1/-1
* asterisk to indicate multiplication
/ forward slash to indicate division.
() parentheses to determine which operations are performed first
** OR pow() exponentiation (raise to the power)
% percent symbol or we say the modulo operator(Modulus), that is the remainder of a division
// two forward slashes or floor division ,that`s the quotient exactly

Basic Math

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1 + 2 - 3 / 4
# 2.25
2 ** (5 / 10) #== 2 ** .5
# 1.4142135623730951
2 ** (5 // 10)
# 1
2 ** 5 % 10
# 2
2 ** (5 % 10)
# 32
3.1415*1000//10/100
# 3.14
-8 % 7
# 6
a, b, c = 1, 2, 3 ## a, b, c = [1, 2, 3]
print(a % c + b // c + b ** c)
# 9

Advanced Math

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# from math import *
import math as m
2e7
# 20000000.0
3.1415e2
# 314.15
m.e
# 2.718281828459045
m.sqrt(pow(10,2)
# 10.0
round(m.pi, 4)
# 3.1416
m.ceil(m.pi)
# 4
m.floor(m.pi)
# 3
m.log(m.exp(1))
# 1.0
m.log10(10)
# 1.0
m.log(1024, 2)
# 10.0
m.factorial(5) ## 5!
# 120
m.modf(pi) ## tuple
# (0.14159265358979312, 3.0)

min(1,5)
# 1
max(1,5)
# 5
hypot(4, 3) ## calculate the hypotenuse
# 5
divmod(8, 2) ## (a // b, a % b)
# (4, 0)
divmod(7, 1.3)
# (5.0, 0.4999999999999998)

triangle functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
degrees(pi)
# 180.0
radians(180)
# 3.141592653589793
abs(m.cos(m.pi))
# 1.0
m.sin(m.pi/2)
# 1.0
m.tan(m.pi/4) ## not 1!!!
# 0.9999999999999999
acos(0)*2
# 3.141592653589793
asin(1)*2
# 3.141592653589793
atan(1)*4
# 3.141592653589793
atan2(1, 1)*4
# 3.141592653589793

eval():evaluate the expression

1
2
3
4
5
6
7
8
9
eval(str(5) + "/2")
# 2.5
for num in range(5):
print(eval(str(num) + '**2'))
# 0
# 1
# 4
# 9
# 16

Random

Generate pseudo-random numbers using python.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import random
random.choice(range(10)) ## [0, 9]
# 7
random.randrange(1, 10, 2) ## odd number from 1 to 9
# 9
random.random() ## [0, 1)
# 0.3568095583272194
random.uniform(1, 10)
# 6.91551724782628

## set a random seed to ensure we got the same random ouput
random.seed(0)
res = random.sample(range(100), 10) ## pick 0-99
res
# [49, 97, 53, 5, 33, 65, 62, 51, 38, 61]
random.shuffle(res) ## shuffle the result
res
# [61, 33, 38, 62, 49, 97, 51, 53, 5, 65]

random.seed(1)
for i in range(5):
value = random.randint(1, 6) # [1, 5]
print(value)
1
2
3
4
5
2
5
1
3
1

Logic

Just like other programming languages, python boolean type has only two values too.

1
2
3
pytbt = True
print(pytbt)
# True
Comparison Operator Description
< less than
<= less than or equal
> greater than
>= greater than or equal
== equal
!= not equal
1
2
3
4
5
6
7
8
9
10
11
import math
round(math.pi, 4) == 3.1416
# True
2020 == '2020'
# False
2020 == 002020.00
# True
0.1 + 0.2 == 0.3
# False
0.1 + 0.2
# 0.30000000000000004

Notes: Computers can’t store floats perfectly accurately, in the same way that we can’t write down the complete decimal expansion of 1/3 (0.3333333333333333…).

Keep this in mind, because it often leads to infuriating bugs!

1
2
3
4
5
6
"C" >= "C++"
# False
"I" != "You"
# True
"Boy" <= "Girl"
# True
Boolean/Logical Operator Description
A and B returns True if both A and B are True
A or B returns True if either A or B is True
not A returns True if A is False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pytbt = True
not pytbt
# False
pytbt is True ## Identity operators
# True
pytbt is not False
# True
not not not not True
# True
(1 >= 2) and (2 >= 1)
# False
(1 >= 2) or (2 >= 1)
# True
True == 1 and False == 0
# True
not []
# True

Bitwise

Bitwise Operator

let x =10, y = 4,Then

Bitwise Operator Meaning Example
& AND x & y = 0 (0000 0000)
| OR x | y = 14 (0000 1110)
~ NOT ~x = -11 (1111 0101)
^ XOR x ^ y = 14 (0000 1110)
>> right shift x >> 2 = 2 (0000 0010)
<< left shift x << 2 = 40 (0010 1000)

Conversion

chr / ord / str / bool / int / float / complex / bin / oct / hex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
int(-5.2)
# -5
str(-5.2)
# '-5.2'
len(str(2 ** 10))
# 4

int('2020')
# 2020
# int('2020.0')
## ValueError: invalid literal for int() with base 10: '2020.0'
int(float('2020.0'))
# 2020

0b100 ## 2**2
int("0b100",2)
int('100', 2)
# 4
0o11 ## 8**0 + 8**1
int("0011",8)
int('11', 8)
# 9
0x11 ## 16**0 + 16**1
int("0x11",16)
int('11', 16)
# 17

eval("hex(255)")
# 0xff
oct(int('0xff',16))
# '0o377'
oct(255)
# '0o377'
bin(255)
# '0b11111111'

complex("1+2j") + complex("2+2j") + complex("j") + complex(1)
# (4+5j)
ord(chr(0x30)) # '0'
# 48
chr(8224)
# '†'

Data Types

Just like other python documents, lemme introduce list to you first.

List

Methods

method description
pop. Remove the item at the given position. If no index is specified, a.pop() removes and returns the last item, equivalent to pop(len(a) - 1).
append add the item x to the end of the list, equivalent to a[len(a):] = [x] or a.insert(len(a), x), just like Stacks
extend Extend the list by appending all the items in the given list L, equivalent to a[len(a):] = L.
insert Insert an item at a given position. a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x)
index Return the index in the list of the first item whose value is x. If there is no such item, will trigger the ValueError.
count Return the number of times x appears in the list.
sort Sort the items of the list in place
reverse Reverse the elements of the list in place.
copy Return a shallow copy of the list. Equivalent to a[:].
remove Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
clear Remove all items from the list. Equivalent to del a[:].
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
nums = [1, 
2, 3,
4, 5]
fruits = ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya']

for i in range(len(nums)):
print('nums[' + str(i) + ']: ' + str(nums[i]))
# nums[0]: 1
# nums[1]: 2
# nums[2]: 3
# nums[3]: 4
# nums[4]: 5


## Math Functions
sum(nums)
# 15
len(nums)
# 5
max(nums)
# 5
min(nums)
# 1

nums + [6, 7, 8]
# [1, 2, 3, 4, 5, 6, 7, 8]
nums[0:-1]
# [1, 2, 3, 4]
nums[slice(0,-1)]
# [1, 2, 3, 4]
nums[-2:]
# [4, 5]
nums[slice(-2,)]
# [1, 2, 3]
nums * 2
# [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

nums.pop(3)
# 4
nums
# [1, 2, 3, 5]
nums.append(2)
nums
# [1, 2, 3, 5, 2]
nums.index(2)
# 1
nums.index(2, 2) ## Find the number 2 starting at the position 2
# 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
nums.count(2)
# 2
if 2 in nums: ## X ValueError
nums.remove(2)
nums
# [1, 3, 5, 2]
nums.insert(0, -1)
nums
# [-1, 1, 3, 5, 2]
del nums[1]
# [-1, 3, 5, 2]
nums.reverse() #== nums = nums[::-1]
nums
# [2, 5, 3, -1]

Notes: Using [::-1] is a common and idiomatic way to reverse a list.

1
2
3
4
5
6
7
8
sorted(nums)
# [-1, 2, 3, 5]
nums.sort()
nums
# [-1, 2, 3, 5]
nums.sort(reverse=True)
nums
# [5, 3, 2, -1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
mix = nums.copy() ## mix = nums only copy a reference
# [-1, 2, 3, 5]
mix.extend(['Berry','almond','banana','orange','Apricot','apple']) #== mix += [...]
mix
# [-1, 2, 3, 5, 'Berry', 'almond', 'banana', 'orange', 'Apricot', 'apple']
# mix.sort() ## '<' not supported between instances of 'str' and 'int'
mix[:4] = []
mix.sort()
mix
# ['Apricot', 'Berry', 'almond', 'apple', 'banana', 'orange']
mix.sort(key=str.lower)
mix
# ['almond', 'apple', 'Apricot', 'banana', 'Berry', 'orange']
mix.clear()
mix
# []

List Comprehensions

Let’s look at some simple examples to explain what the list comprehensions mean.

1
2
3
4
5
6
7
8
9
10
11
[i**2 for i in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

[i**2 for i in range(10) if i**2 % 2 == 0]
# [0, 4, 16, 36, 64]

{x: x**2 for x in range(10) if i**2 % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

[m + n for m in 'ABC' for n in '123']
# ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
1
2
3
[year for year in [1990, 2000, 2007, 2012, 2100] if \
(year % 4 == 0 and year % 100 != 0) or year % 400 == 0]
# [2000, 2012]
1
2
sorted([str(n) * n for n in [1, 4, 2, 8, 5, 7]], key = len)
# ['1', '22', '4444', '55555', '7777777', '88888888']

List Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
scores = [55, 44, 33, 22, 11]

if all([i > 10 for i in scores]):
print("All larger than 10")
# All larger than 10

if any([i % 2 == 0 for i in scores]):
print("At least one is even")
# At least one is even

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
list(enumerate(seasons, start = 1))
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

for v in enumerate(reversed((scores))):
print(v)
# for idx in range(len(scores)):
# print(scores[idx])
# for e in scores:
# print(e)

# (0, 11)
# (1, 22)
# (2, 33)
# (3, 44)
# (4, 55)

Tuples

Tuples can be created without the parentheses, by just separating the values with commas( ,).

Unlike List, it’s immutable.

1
2
3
4
5
6
leche = ()
milk = ("tea",)
lait = "m", "i", "l", "k"
mix = milk,lait
# (('tea',), ('m', 'i', 'l', 'k'))
mix[0] = 'TypeError' # TypeError: 'tuple' object does not support item assignment

Sets

Sets are unordered, which means that they can’t be indexed.
They cannot contain duplicate elements.

Due to the way they’re stored, it’s faster to check whether an item is part of a set, rather than part of a list.

1
2
3
4
5
6
7
8
9
10
11
12
13
num = {1, 2, 3, 4, 5}
num.add(6)
num.pop() # pop 1
num.remove(2)
# num.remove(7) KeyError
num.discard(5)
num.update([6, 7, 8, 8])
print(num)
# {3, 4, 6, 7, 8}

words = set(["spam", "eggs", "sausage"])
print(len(words))
# 3

Membership testing and the elimination of duplicate entries

  • The union operator | combines two sets to form a new one containing items in either.
  • The intersection operator & gets items only in both.
  • The difference operator - gets items in the first set but not in the second.
  • The symmetric_difference operator ^ gets items in either set, but not both.

python sets

1
2
3
4
5
6
7
8
9
10
11
12
13
first = {1, 2, 3, 4, 5, 6}
second = {4, 5, 6, 7, 8, 9}

print(first | second)
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(first & second)
# {4, 5, 6}
print(first - second)
# {1, 2, 3}
print(second - first)
# {8, 9, 7}
print(first ^ second)
# {1, 2, 3, 7, 8, 9}
1
2
3
4
5
6
7
8
9
third = first.union(second)
third <= first
third.issubset(first)
first.issuperset(third)
# False
third >= first
first.issubset(third)
third.issuperset(first)
# True

Dictionaries

Dictionaries are data structures used to map arbitrary keys to values.
Only immutable objects can be used as keys to dictionaries.

1
2
3
4
5
6
fruits = {"apricot": "The bridesmaids wore apricot and white organza",
"guava":"have lots of fruits containing Vitamin C like Guava, Oranges, Gooseberries.",
"orange":"the citrus species ",
"nectarine":"it`s a peach",
None: "True",
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
print(fruits['orange'])
# the citrus species
print(fruits['fruits'])
# KeyError: 'fruits'
print("orange" in fruits) #== print("orange" in fruits.keys())
# True
print("guava" not in fruits)
# False
print("True" in fruits.values())
# True

print(fruits.get("orange")) # return none if not exists
# the citrus species
print(fruits.get("banana", 0)) ## KeyError / return 0 if not exists or it will return none
# 0

print(fruits["avocado"]) if "avocado" in fruits else "not in dictionary"
print(fruits.get("avocado", "not in dictionary"))
# not in dictionary

Dictionaries manipulation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
floras = {1: "Violet", 2: "Daisy", 3: "Primrose",
4: "Ivy", 5: "Tulup", 6: "Marigold", 7: "thorn", 8: "carnation"}
floras.popitem()
floras.pop(6)
# 'Marigold'
floras.pop(100, "This flower does not exist!")
# 'This flower does not exist!'
floras.pop(7, "This flower does not exist!")
floras
# {1: 'Violet', 2: 'Daisy', 3: 'Primrose', 4: 'Ivy', 5: 'Tulup'}

# floras.update(8="Carnation",18= "Lilac") ## SyntaxError: keyword can't be an expression
floras.update(Carnation=8, Lilac=18) #== floras.update({"Carnation":8, "Lilac":18})
floras
# {1: 'Violet',
# 2: 'Daisy',
# 3: 'Primrose',
# 4: 'Ivy',
# 5: 'Tulup',
# 'Carnation': 8,
# 'Lilac': 18}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
floras[5] = "Rose"
floras[10] = "chrysanthemum"
for flora in floras.items():
print(flora)
# (1, 'Violet')
# (2, 'Daisy')
# (3, 'Primrose')
# (4, 'Ivy')
# (5, 'Rose')
# ('Carnation', 8)
# ('Lilac', 18)
# (10, 'chrysanthemum')

floras.setdefault(1, 'Lily')
if 1 not in floras:
floras[1] = 'Lily'
floras.setdefault("END", None)
floras
# {1: 'Violet',
# 2: 'Daisy',
# 3: 'Primrose',
# 4: 'Ivy',
# 5: 'Rose',
# 'Carnation': 8,
# 'Lilac': 18,
# 10: 'chrysanthemum',
# 'END': None}

floras.fromkeys(floras, "NA")
# {1: 'NA',
# 2: 'NA',
# 3: 'NA',
# 4: 'NA',
# 5: 'NA',
# 'Carnation': 'NA',
# 'Lilac': 'NA',
# 10: 'NA',
# 'END': 'NA'}
floras.clear()
floras
# {}

.

1
2
3
4
5
6
7
8
def printPicnic(itemsDict, leftWidth, rightWidth, Symbol1='.',Symbol2='-'):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, Symbol2))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, Symbol1) + str(v).rjust(rightWidth))

picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 6, "*", "/")
1
2
3
4
5
6
7
8
9
10
---PICNIC ITEMS--
sandwiches.. 4
apples...... 12
cups........ 4
cookies..... 8000
///////PICNIC ITEMS///////
sandwiches********** 4
apples************** 12
cups**************** 4
cookies************* 8000

None

The None object is used to represent the absence of a value.
It is similar to null,nil,undefined in other programming languages.
Like “empty” values, such as 0,(), [] and the empty string

1
2
3
4
5
6
7
8
9
def some_func():
print("Hi!There!")

var = some_func()
print(var)
# Hi!
# None
None == print(some_func())
# True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import random
letters = [chr(x) for x in range(ord('a'), ord('z') + 1)]

def para(d = None):
if d is None:
d = {}
idx = random.randint(0,25)
item = {letters[idx]:idx + 1}
d.update(item)
print(d)
para()
para()
para({"d":4})

# {'j': 10}
# {'d': 4}
# {'d': 4, 'x': 24}

Conversion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
list(range(1,10))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
tuple(range(1, 10))
# (1, 2, 3, 4, 5, 6, 7, 8, 9)
set(range(1, 10))
# {1, 2, 3, 4, 5, 6, 7, 8, 9}

list("apple")
# ['a', 'p', 'p', 'l', 'e']
list(("apple","juice"))
# ['apple', 'juice']
list(tuple("apple"))
# ['a', 'p', 'p', 'l', 'e']
list(set("apple"))
# ['l', 'e', 'a', 'p']
list({"apple": 1, "juice": 2})
# ['apple', 'juice']

tuple("apple")
# ('a', 'p', 'p', 'l', 'e')
tuple(["apple", "juice"])
# ('apple', 'juice')
tuple({"apple", "juice"})
# ('juice', 'apple')
tuple({"apple": 1, "juice": 2})
# ('apple', 'juice')

set("apple")
# {'a', 'e', 'l', 'p'}
set(tuple("apple"))
# {'a', 'e', 'l', 'p'}
set({"apple": 1, "juice": 2})
# {'apple', 'juice'}
frozenset("apple")
# frozenset({'a', 'e', 'l', 'p'})

To create a dictionaries in some not normal ways:

1
2
3
4
5
6
7
8
9
10
11
12
13
fruits = {}
fruits["apple"] = 1
...

## keys should be a str (keyword can't be an expression)
dict(apple = 1, peach = 2, pear = 3) == dict(peach = 2, pear = 3, apple = 1)
# True
dict(zip(['apple', 'peach', 'pear'], [1, 2, 3]))
dict(zip(['apple', 'peach', 'pear'], '123'))
dict([('apple', 1), ('peach', 2), ('pear', 3)])
# {'apple': 1, 'peach': 2, 'pear': 3}
dict.fromkeys(['apple','peach','pear'],[1,2,3])
# {'apple': [1, 2, 3], 'peach': [1, 2, 3], 'pear': [1, 2, 3]}

fruits dictionaries

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
print(fruits.keys())
# dict_keys(['apricot', 'guava', 'orange', 'nectarine', None])
list(fruits.keys())
['apricot', 'guava', 'orange', 'nectarine', None]
print(fruits.values())
# dict_values(['The...',... , 'True'])
print(fruits.items())
# dict_items([('apricot', 'The bridesmaids wore apricot and white organza'), ..., (None, 'True')])

for k, v in fruits.items():
print(k,': ' + v, sep = "")
for item in fruits:
print(f'{item}: {fruits[item]}')

# apricot: The bridesmaids wore apricot and white organza
# guava: have lots of fruits containing Vitamin C like Guava, Oranges, Gooseberries.
# orange: the citrus species
# nectarine: it`s a peach
# None: True

Type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
type(ord('A'))
# int
type(chr(65))
# str
type(65.0)
# float
type(complex("65 + j"))
# ValueError: complex() arg is a malformed string
type(complex("65+j"))
# complex
type((ord('A') > ord('C'))) ## False
# bool
type(None)
# NoneType
type(abs)
# builtin_function_or_method
type([])
# list
type(int)
# <class 'type'>


isinstance(b'a', bytes)
isinstance(b'A', bytes)
isinstance([], (list, tuple))
isinstance([1, 2, 3], (list, tuple))
isinstance((1, 2, 3), (list, tuple))
## ALL True
1
print(dir("ABC"))
1
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Strings

Strings are one of the most basic immutable data types in Programming which used to represent textual data.

In Python, strings are denoted with either single or double quotes or three quotes for explanation.

Strings in Python are immutable. They cannot be modified after being created.

1
2
3
4
5
6
7
8
9
## quotes by Confucius

s1 = 'I hear and I forget. I see and I remember. I do and I understand.'
s2 = "I hear and I forget. I see and I remember. I do and I understand."
s3 = """
I hear and I forget. I see and I remember. I do and I understand.
"""
('\n' + s1 + '\n') == ('\n' + s2 + '\n') == s3
# True

In Chinese:

不闻不若闻之,闻之不若见之,见之不若知之,知之不若行之。学至于行之而止矣。
– 《荀子·儒效》

If the strings delimited with single or double quotes within the string, you need to be escaped with a backslash (\) or with the other type of quotes .

1
2
3
4
5
s4 = 'je t\'aime'
s5 = "je t'aime"
s6 = "je " + "t\'" + 'aime' # '+' for string concatenation
s4 == s5 == s6
# True

Using * to generate multiple copies

1
2
'\n'  -->  Leaves a line
'\t' --> Leaves a space
1
2
3
4
print((s6 + "\n\t") * 2) 
# je t'aime
# je t'aime
#

But in certain cases, we don’t want the characters escaped, you can use repr() instead.

1
2
print(repr((s6 + "\n\t")) * 2)
# "je t'aime\n\t""je t'aime\n\t"

Also, we can add r or R before your strings to stop them from the resolution of escape characters.

1
2
print((s6 + r"\n\t") * 2)
# je t'aime\n\tje t'aime\n\t

String Methods

Python provides a number of methods to make string manipulation very cool and easy.

Case

1
2
3
4
5
6
7
8
9
10
11
12
"ascII".lower()
# 'ascii'
"ascII".upper()
# 'ASCII'
"ascII".swapcase()
# 'ASCii'
"ascII ascii".capitalize()
# 'Ascii ascii'
"ascII ascii".title()
# 'Ascii Ascii'
"ascII ascii".casefold()
# 'ascii ascii'
1
2
3
4
5
6
7
8
'ß'.capitalize()
# 'SS'
'ß'.casefold()
'ss'
u'\xb5'.swapcase()
# 'Μ'
"He's not perfect".title()
# "He'S Not Perfect"

Strip

The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
text = "    blank space   "

## Leading and trailing whitespaces are removed
text.strip()
# 'blank space'

## All whitespaces in the left are removed
text.lstrip()
# 'blank space '
text.rstrip()
' blank space'

## All b,l,a,n,k characters in the left and right of string are removed
text.strip().strip("blank")
# ' space'

## one line AI code for Chinese Users
text.strip("吗?") + "!"

Slicing

Let’s look at an example to make this a bit clearer.

1
letters = "abcdefghijklmnopqrstuvwxyz"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
len(letters)
# 26
'abc' in letters and 'σ' not in letters
# True

letters[0:7]
# 'abcdefg'
letters[-5:]
# 'vwxyz'
letters[-6:-1]
# 'uvwxy'
letters[:21:4]
# 'aeimqu'
letters[::-4]
# 'zvrnjfb'

Now, we define some letters in different python data types to do some string manipulation easier.

1
2
3
list_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
dict_letters ={'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10,'K':11,'L':12,'M':13,'N':14,'O':15,'P':16,'Q':17,'R':18,'S':19,'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26}
alphabet = "Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz"

Notes:

alphabet can be generated from Python

" ".join([l.upper() + l for l in letters]),

or from R, paste(LETTERS,letters,collapse = " ",sep = "")

Split & Join

  • split(): use a blank space as a default delimiter to split a sentence into individual words list.
  • join(): combine a list of strings into a single string
1
2
3
4
alphabet.split()
# ['Aa', 'Bb', 'Cc', 'Dd', 'Ee', 'Ff', 'Gg', 'Hh', 'Ii', 'Jj', 'Kk', 'Ll', 'Mm', 'Nn', 'Oo', 'Pp', 'Qq', 'Rr', 'Ss', 'Tt', 'Uu', 'Vv', 'Ww', 'Xx', 'Yy', 'Zz']
'-'.join(alphabet.split())
# 'Aa-Bb-Cc-Dd-Ee-Ff-Gg-Hh-Ii-Jj-Kk-Ll-Mm-Nn-Oo-Pp-Qq-Rr-Ss-Tt-Uu-Vv-Ww-Xx-Yy-Zz'
1
2
3
4
5
6
"*".join(list_letters)
# a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z
"*".join(dict_letters)
# 'A*B*C*D*E*F*G*H*I*J*K*L*M*N*O*P*Q*R*S*T*U*V*W*X*Y*Z'
"*".join(alphabet)
# 'A*a* *B*b* *C*c* *D*d* *E*e* *F*f* *G*g* *H*h* *I*i* *J*j* *K*k* *L*l* *M*m* *N*n* *O*o* *P*p* *Q*q* *R*r* *S*s* *T*t* *U*u* *V*v* *W*w* *X*x* *Y*y* *Z*z'
1
2
3
4
5
6
alphabet.rpartition(" ")
# ('Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy',' ','Zz')
alphabet.split(maxsplit=5)
# ['Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu', 'Vv','Ww','Xx' 'Yy', 'Zz']
''.split('n')
# ['']
1
2
3
4
5
6
7
8
url = "https://cn.bing.com/th?id=OHR.LochLeum_ZH-CN9620588759_UHD.jpg&rf=LaDigue_UHD.jpg&pid=hp&w=1920&h=1080&rs=1&c=4"
url.rsplit(".")
# ['https://cn', 'bing', 'com/th?id=OHR', 'LochLeum_ZH-CN9620588759_UHD', 'jpg&rf=LaDigue_UHD', 'jpg&pid=hp&w=1920&h=1080&rs=1&c=4']
url.rsplit(".", 1)
# ['https://cn.bing.com/th?id=OHR.LochLeum_ZH-CN9620588759_UHD.jpg&rf=LaDigue_UHD', 'jpg&pid=hp&w=1920&h=1080&rs=1&c=4']
valid_extensions = ['jpg', 'jpeg','gif','png']
url.rsplit(".", 1)[1].split("&")[0].lower() in valid_extensions
# True

splitlines

Split a string into a list where each line is a list item.

1
2
3
4
5
6
7
8
9
10
"".splitlines()
# []
'\r\n'.splitlines()
# []
'\r\n'.splitlines(keepends=True)
# ['\r\n']
'Aa\nBb\rCc\n\rDd\nEe'.splitlines()
# ['Aa', 'Bb', 'Cc', '', 'Dd', 'Ee']
'Aa\nBb\rCc\n\rDd\nEe'.splitlines(keepends=True)
# ['Aa\n', 'Bb\r', 'Cc\n', '\r', 'Dd\n', 'Ee']

Using python like the function paste in R

1
2
3
4
5
6
num = [1,2,3,4,5]
alpha = ['a', 'b', 'c', 'd', 'e']
[print(num[i],alpha[i],sep='-',end=":") for i in range(5)]
# 1-a:2-b:3-c:4-d:5-e:
[print(list(dict_letters.keys())[i],list(dict_letters.values())[i],sep='-',end=":") for i in range(len(dict_letters))]
# A-1:B-2:C-3:D-4:E-5:F-6:G-7:H-8:I-9:J-10:K-11:L-12:M-13:N-14:O-15:P-16:Q-17:R-18:S-19:T-20:U-21:V-22:W-23:X-24:Y-25:Z-26:

Find

Searches the string for a specified value and returns the position of where it was found.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
text = "Can you can a can as a canner can can a can? "
text.count('can')
# 6
text.count('can', 1, 4)
# 0
text.index('can') ## ValueError if not exists
text.find('can') ## -1 if not exists
# 8
text.rfind('can', 5, 20)
# 14

text = "I wish to wish the wish you wish to wish, but if you wish the wish the witch wishes, I won't wish the wish you wish to wish. "

## 5 means 5 times
text.replace("wish", "hope", 5)
# "I hope to hope the hope you hope to hope, but if you wish the wish the witch wishes, I won't wish the wish you wish to wish. "

startswith endswith

Returns true if the string starts or ends with the specified value.

1
2
3
4
5
6
7
text = '''How many cookies could a good cook cook
if a good cook could cook cookies\nA good cook could cook
as much cookies as a good cook who could cook cookies'''
text.endswith('cookies', 0, 16) ##
# Ture
text.startswith(('How',"cookies"),0, 16)
# True

Trans

Returns a translated string.

1
2
3
4
5
6
7
8
9
"PYTHON".translate(str.maketrans("N","C","PY"))
# {78: 67, 80: None, 89: None}
# 'THOC'
table = str.maketrans(dict_letters)
text="FewFreeFruitFliesFlyFromFlames".upper().translate(table)
# '\x06\x05\x17\x06\x12\x05\x05\x06\x12\x15\t\x14\x06\x0c\t\x05\x13\x06\x0c\x19\x06\x12\x0f\r\x06\x0c\x01\r\x05\x13'
up = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
print(b'abcdefghijklmnopqrstuvwxyz'.translate(up, b'abcde'))
# b'FGHIJKLMNOPQRSTUVWXYZ'

ASCII & Unicode

asciii

1
2
3
4
5
6
7
8
9
chr(111)
# 'o'
'\x6f' ## hex(ord('o'))
# o
'\157' ## oct(ord('o'))
# o
## bin(ord('o'))
'ABC'.encode('ascii')
# b'ABC'

unicode

1
2
3
4
5
6
7
8
9
10
11
12
13
str = "月"
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")

print(hex(ord("月"))) # 26376
# '0x6708'
print('\u6708')
# 月
print(str_utf8)
# b'\xe6\x9c\x88'
print(str_utf8.decode('UTF-8','strict'))
# 月

1
2
3
4
5
6
print('2' + '\u00B2')
# 2²
print('\u4e2d\u6587')
# 中文
'中文'.encode('utf-8')
# b'\xe4\xb8\xad\xe6\x96\x87'

IsTypes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"ABC".isalpha()
# True

"ABC12345".isupper()
# True
"ABC".islower()
# False
"ABC".istitle() ## "Abc".istitle() True
# False
'12306'.isdecimal() ## train
# True
'4869'.isdigit() ## Sherlock APTX4869
# True
'221'.isnumeric() ## 221B
# True
" ".isspace()
# True

"if".isidentifier()
# True
isdigit isdecimal isnumeric
True False True
False False True
壹贰叁零陆 False False True
½¼ False False True
0.142857 False False False
1
2
3
4
5
6
## isalnum(): whether a character string is 'alphanumeric'.
"月bloomings".isalnum()
# TRUE

'影shadow'.isalpha()
# TRUE

Formatting

Print

Options

%[(name)][flags][width].[precision]typecode

Special characters

character Decimal Description
\ statement continues on next line
\ 92 backslash
\’ 39 Single quote
\” 34 Double quote
\a 7 Bell
\b 8 Backspace
\f Formfeed
\n 10 newline
\r 13 carriage return
\t 9 tabulation
\v 11 vertical tabulation
\0 \000 null value
\ooo octal value o in (0…7)
\xhh hexadecimal value (0…9, a…f; A…F)
\uxxxx Unicode character value

Conversion types

character Description
b Converts to a signed binary
c Converts to a single character
d,i Converts to a signed decimal integer or long integer
u Converts to an unsigned decimal integer
e,E Converts to a floating point in exponential notation
f,F Converts to a floating point in fixed-decimal notation
g Converts to the value shorter of %f and %e
G Converts to the value shorter of %f and %E
o Converts to an unsigned integer in octal
r string generated with repr()
s Converts to a string using the str() function
x,X Converts to an unsigned integer in hexadecimal

Flags

character Description
0 pad numbers with leading weros
- left align the results (default is right)
space add a space before a positive number or string
+ Always begin a number with a sign (+or-)
# display numbers in alternate form.

Format

1
2
3
4
5
6
7
8
9
10
11
12
13
print("%.*f" % (5, 1.2))
# 1.20000
print("%d" % (int(math.pi)))
print("{:d}" .format(int(math.pi)))
# 3
print("%04X" % 100)
print("{:04X}".format(100))
# 0064
print("{:b}".format(100))
# 1100100
print("%o" % 100)
print("{:o}".format(100))
# 144
1
2
3
4
5
6
7
8
import math
print("{:+.2f}".format(math.pi))
print("%+.2f" % math.pi)
# +3.14
print("{:.2%}".format(math.e))
# 271.83%
print("{:,}".format(1e10))
# 10,000,000,000.0
1
2
3
4
5
6
7
8
print("{:*>4d}".format(10))
#**10
print("{:*<4d}".format(10))
#10**
print("{:*^4d}".format(10))
#*10*
print("{:*^9d}".format(10))
#***10****

Let us now look at the key option.

1
2
print("It's %(name)s. I'm %(age)d year old" % {'name':'Bran Stark', 'age':99})
# It's Bran Stark. I'm 99 year old

String

Alignment

1
2
3
4
5
6
7
8
9
10
11
12
'trumpet'.center(10, '$')
# '$trumpet$$'
'It\'s an awful day!'.ljust(25, ':')
# It's an awful day!:::::::

## rjust in the opposite way
'It\'s an awful day!'.rjust(25, ':')
":::::::It's an awful day!"

'It\'s an awful day!'.zfill(25)
#== 'It\'s an awful day!'.rjust(25, '0')
# "0000000It's an awful day!"
1
2
3
4
5
6
7
tab = '*\t**\t***\t****\t\t*****'
tab.expandtabs()
# * ** *** **** *****
# 123456781234567812345678123456789ABCDEFG12345
tab.expandtabs(4)
# * ** *** **** *****
# 12341234123412341234123412341

str.format()

1
2
3
4
"dog:{0}, color: {1}".format("huskey", "black and white")
# 'dog:huskey, color: black and white'
"dog:{1}, color: {0}".format("huskey", "black and white")
# 'dog:black and white, color: huskey'
1
2
3
4
5
6
7
8
"dog:{name}, color: {color}".format(name="huskey", color="black and white")
# dog:huskey, color: black and white
poodle = {"name":"puddle","color":"brown"}
"dog:{name}, color: {color}".format(**poodle)
# dog:puddle, color: brown
dogs = ["Golden Retriever", "Dachshund","shepherd dog","Samoyed"]
"dog:{0[1]}, color: {0[2]}".format(dogs)
# dog:Dachshund, color: shepherd dog

f-strings

1
2
3
poodle = {"name":"puddle","color":"brown"}
f"dog:{poodle['name']}, color: {poodle.get('color')}, age: {poodle.get('age',7)}"
# 'dog:puddle, color: brown, age: 7'

format_map

1
2
3
Lights = {'North': 'aurora borealis', 'South': 'aurora australis'}
'{North} colours the night sky through a silhouetted forest'.format_map(Lights)
# 'aurora borealis colours the night sky through a silhouetted forest'

Squares and cubes table

1
2
3
4
5
for x in range(1, 11):
print(str(x).rjust(2), str(x*x).rjust(3), end=' ')
print(str(x*x*x).rjust(4))
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
1
2
3
4
5
6
7
8
9
10
 1   1    1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

9X9 Table

1
2
3
4
5
for i in range(1, 10):
for j in range(1, i + 1):
print('{1}x{0}={2}\t'.format(i, j, i * j), end='')
# print('%d*%d=%d' % (i, j, i * j), end='\t')
print()
1
2
3
4
5
6
7
8
9
1x1=1	
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81

Advanced functions

You’re already familiar with the basic python , and now we’re adding some complicated things such as Higher-order function into your python learning mix soups.

Higher-order functions

filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.

We say simplistic, because python functions quickly get very complicated, and giving it a full treatment now would probably confuse more than help.

1
2
3
4
5
6
7
8
9
10
11
filter(None, (True, 1, 0, -1, False)) 
# (True, 1, -1)
list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
# ['1', '2', '3', '4', '5', '6', '7', '8', '9']

list(map(lambda x: x ** 2, filter(lambda x: x % 2, range(1, 10))))
# [1, 9, 25, 49, 81]
def char2num(s):
return {'0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6, '6': 7, '7': 8, '8': 9, '9': 10}[s]
print(list(map(char2num, '13579')))
# [2, 4, 6, 8, 10]

Lambda

Functional programming seeks to use pure functions.

Pure functions have no side effects, and return a value that depends only on their arguments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
nums = [11, 22, 33, 44, 55]

list(map(lambda x: x + 5, nums))
# [n + 5 for n in nums]
# [16, 27, 38, 49, 60]

list(filter(lambda x: x % 2 == 0, nums))
# [x for x in nums if x % 2 == 0]
# [22, 44]

list(filter(lambda x: x and x.strip(), ['A', '', 'B', None, 'C', ' ']))
# ['A', 'B', 'C']

list(filter(lambda s: s and s.strip(), ['A', '', 'B', None, 'C', ' ']))
# ['A', 'B', 'C']

def prod(L):
return reduce(lambda x, y : x * y, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
# 3 * 5 * 7 * 9 = 945

def str2float(s):
return reduce(lambda x, y: x*10+y, map(int, s.replace('.', '')))/10**(len(s)-s.find('.')-1 if s.find('.') + 1 else 0)
print(str2float('13579.25441'))
# 13579.25441
print(str2float('13579.'))
# 13579.0

zip

1
2
3
4
5
6
7
8
9
10
11
12
animals = ['cat', 'ox', 'dog', 'Tiger', 'Lion', "leopard", "bear", "whale", "kangaroo", "chicken"]
dict_animals = dict(zip(animals, range(10)))
lst_animals = list(zip(animals, range(10)))

sorted(animals, key=str.lower, reverse=True)
# ['whale', 'Tiger', 'ox', 'Lion', 'leopard', 'kangaroo', 'dog', 'chicken', 'cat', 'bear']

dict(sorted(dict_animals.items(), key = lambda item: len(str(item[0])), reverse = True))
# {'kangaroo': 8, 'leopard': 5, 'chicken': 9, 'Tiger': 3, 'whale': 7, 'Lion': 4, 'bear': 6, 'cat': 0, 'dog': 2, 'ox': 1}

sorted(lst_animals,key=lambda x:x[0])
sorted(lst_animals,key=lambda x:x[1])

Parameters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def monsters(name, hp, mp = 5, *args, **kw):
if 'ruby' in kw:
print("The %s has %s rubies" % (name, kw["ruby"]))
print('name:', name, 'hp:', hp, "mp:", mp,
"attributes:", args, 'other:', kw)

monsters('Goblin', 50, 20, 10, 20, ruby=10, exp=5, desc="a pathetic creature")
# The Goblin has 10 rubies
# name: Goblin hp: 50 mp: 20 attributes: (10, 20) other: {'ruby': 10, 'exp': 5, 'desc': 'a pathetic creature'}

kw = dict(ruby = 10, exp = 5, desc = "a pathetic creature")
args = [10, 20, 30] #== args = (10, 20, 30)
monsters('Goblin', 50, *args, **kw) ## mp = 10 !!!
# The Goblin has 10 rubies
# name: Goblin hp: 50 mp: 10 attributes: (20, 30) other: {'ruby': 10, 'exp': 5, 'desc': 'a pathetic creature'}
1
2
3
4
def monsters(name, hp, *, exp, desc="a common rpg creature"):
print(name, hp, exp, desc)
monsters('Goblin', 50, exp = 5, desc = "a pathetic creature")
# Goblin 50 5 a pathetic creature
1
2
3
4
5
6
7
8
from math import sqrt

def same(x, *fs):
s=[f(x) for f in fs]
return s

print(same(2, str, sqrt, abs))
# ['2', 1.4142135623730951, 2]

Iterators & Generators

Iterators

We can use for statement for looping over a list - [] 、dict - {}、string - “”, they are Iterable, so these are called iterable objects.

1
2
3
4
5
6
7
8
9
from collections import Iterable
## Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated
from collections.abc import Iterable
isinstance([], Iterable)
isinstance({}, Iterable)
isinstance('abc', Iterable)
isinstance((x for x in range(10)), Iterable)
isinstance(100, Iterable)
# False

The built-in function iter takes an iterable object and returns an iterator, so you can give them iter() function, once added they are becoming Iterator.

1
2
3
4
5
6
7
8
9
10
list = [1, 2, 3, 4]
it = iter(list)
for i in range(2):
print (next(it))
# 1
# 2
for x in it:
print (x, end=" ")
# 3 4
next(it) ## raises a StopIteration.

Generators

Generators are a type of iterable, like lists or tuples.
but unlike lists, they don’t allow indexing with arbitrary indices, although they can be iterated through with for loops.

1
2
3
4
5
6
7
8
9
10
def meow(n):
i = 1
while i < n:
yield 'meow ' * i
i += 1
cat = meow(3)
print(next(cat))
print(next(cat))
# meow
# meow meow

Generator Expressions

1
2
3
4
(ord(s) for s in "jupyter-lab")
# <generator object <genexpr> at 0x000000000503FF48>
sum(ord(s) for s in "jupyter-lab")
# 1135

A triplet (x, y, z) is called pythogorian triplet if x*x + y*y == z*z.

REFERENCES