- Variable Declaration and Assignment
Variables in Python are essentially references to objects in memory. An empty object still represents an actual object.
Variable names must consist of letters (letters form valid identifiers), cannot start with digits, and cannot conflict with reserved keywords.
Multiple assignments are supported: x, y = 1, 2 is equivalent to:
x = 1
y = 2
Sequential assignment works too: x = y = 1 equals:
x = 1
y = 1
1.1 Memory Allocation
Every value in Python is an object. After allocation, the reference address (or label) is stored in the variable.
text1 = "ivan"
text2 = text1
print(id(text1))
print(id(text2))
print('text1 = ' + text1)
print('text2 = ' + text2)
text1 = "yzg"
print(id(text1))
print(id(text2))
Output:
When assigning a string to a variable, Python places it in shared memory, and the variable holds just the reference address.
Assigning a list to the same variable updates the reference.
Assigning one variable to another copies the reference, making both point to the same object.
- Primitive Data Types
2.1 Numbers
Integer, floating-point, and complex types are available.
a, b, c = 10, 3.14, 1+2j
print(a, b, c)
print(a+c)
print(c, type(c))
2.2 Strings
Both single and double quotes work identically.
text = 'hello baby'
print(text, text[1], text[2:4], text[6:])
name = "good"
print(text + name)
Strings are immutable.
2.2.1 String Creation
str1 = 'Hello World!'
print('String creation...')
print(str1)
2.2.2 Accessing Characters
print('Character access...')
print("str1[0]: ", str1[0])
print("str1[1:5]: ", str1[1:5])
2.2.3 String Operations
print('String operators...')
a = "Hello"
b = "Python"
print("a + b: ", a + b)
print("a * 2: ", a * 2)
print("a[1]: ", a[1])
print("a[1:4]: ", a[1:4])
if "H" in a:
print("H is in a")
else:
print("H is not in a")
if "M" not in a:
print("M is not in a")
else:
print("M is in a")
print(r'\n')
print(R'\n')
2.2.4 String Formatting
print('String formatting...')
print("My name is %s and weight is %d kg!" % ('Asher Gu', 90))
print("format method: My name is {name} and weight is {weight} kg!".format(
name="Asher Gu", weight=90))
Triple quotes:
'''
Python triple quotes allow multiline strings and special characters like newlines and tabs.
'''
print('Triple quotes...')
hi = '''hi
i am Asher Gu'''
print(hi)
2.3 Boolean Values
result = 2 > 1
print(result)
result = False
if result:
print('this is true')
else:
print('this is false')
- Composite Data Types
3.1 Dictionary
Dictionaries store key-value pairs.
3.1.1 Dictionary Initialization
data = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
data = {
'Name': 'Zara',
'Age': 7,
'Class': 'First'
}
print("data['Name']: ", data['Name'])
print("data['Age']: ", data['Age'])
3.1.2 Modifying Dictionary Values
print("Before modification:", data['Age'])
data['Age'] = 8
print("After modification:", data['Age'])
3.1.3 Removing Elements
del data['Age']
data.clear()
print(data)
del data
print(data)
3.1.4 Adding Elements
obj = {}
obj['name'] = 'yzg'
obj['age'] = 28
print(obj['name'], type(obj))
3.1.5 Dictionary Assignment
Similar to lists:
person = {'name': 'ivan', 'age': 30}
obj = {}
obj['name'] = 'yzg'
obj['age'] = 28
person = obj
obj['age'] = 10
print(person)
3.2 List
Lists are ordered collections with indexed elements.
3.2.1 Creating Lists
print("Creating list...")
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
print(max(list2))
print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])
3.2.2 Updating Lists
print("Updating list...")
print("Index 2 value:")
print(list1[2])
list1[2] = 2001
print("Index 2 updated value:")
print(list1[2])
Adding elements:
a = [2, 5, 9]
print(a)
a.append(9)
print(a)
a.extend(['lili', 9])
print(a)
Inserting elements:
a.insert(1, 'i')
print(a)
a.insert(-2, '-i')
print(a)
3.2.3 Deleting Elements
print("Deleting from list...")
print("Before deletion:")
print(list1)
del list1[2]
print("After deletion:")
print(list1)
a.pop()
print(a)
a.remove(5)
print(a)
3.2.4 List Operations
Combining lists:
list4 = list1 + list2
print("list1 + list2:", list4)
Repeating:
list5 = ['hello'] * 4
print("['hello'] * 4:", list5)
Slicing:
L = ['I', 'want', 'to pass!']
print(L[2])
print(L[-2])
print(L[1:])
Sorting:
age = [13, 10, 15, 50, 22]
age.sort()
print(age)
stu = ['lili', 'ivan', 'ara11111', '1ciga']
print(stu)
stu.sort()
print(stu)
age.reverse()
print(age)
3.2.5 List Assignment
train = [50, 20, 'apple']
print(train)
list_ref = train
train[2] = 'tv'
print(train)
print(list_ref)
i = 1
j = i
print(i)
i = 2
print(j)
3.2.6 Non-Destructive List Methods
arr = [1, 2, 2, 3]
print(len(arr))
print(arr.count(2))
print(max(arr))
print(min(arr))
print(arr.index(2))
print(2 in arr)
sum_val = 0
for v in [40, 20, 10, 30]:
sum_val += v
print(sum_val)
name = ['ivan', 'yzg', 'lili']
print(" ".join(name))
print([v*10 for v in [1, 2, 5, 7, 9] if v > 5])
age1 = [13, 10, 15]
age2 = [10, 5]
age = age1 + age2
print(age)
print(age2 * 2)
print((name + age1) * 2)
print(age1 == age2)
ret = map(lambda x: x - 2, [1, 2, 3])
print([v for v in ret])
def custom_map(func, lst):
result = []
for item in lst:
result.append(func(item))
return result
print(custom_map(lambda x: x - 2, [1, 2, 3]))
3.3 Set
Sets are unordeerd collections with unique elements.
3.3.1 Creating Sets
s1 = set('good good study')
s2 = set([1, 2, 3, 4, 5])
s3 = frozenset("ggs")
print(type(s1))
print(type(s3))
print(s2)
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
print('banana' in basket)
3.3.2 Set Operations
s2 = set([1, 2, 3, 3, 4, 5])
print("Original:", s2)
s2.add("j")
print("After add:", s2)
s2.remove(3)
print("After remove:", s2)
s2.update([6, 7, 8, 9])
print("After update:", s2)
Set operations:
s1 = set('abcdde')
s2 = set([1, 2, 3, 4, 5])
print("Union:", s1 | s2)
print("Intersection:", s1 & s2)
print("Difference:", s1 - s2)
print("Difference method:", s1.difference(s2))
3.4 Tuple
Tuples are immutable sequences.
3.4.1 Creating Tuples
tup0 = ()
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = ("a", "b", "c", "d")
tup4 = (50,)
print("tup0: ", tup0)
print("tup1: ", tup1)
print("tup2[1:5]: ", tup2[1:5])
3.4.2 Tuple Operations
print(tup4 * 4)
print("tup4: ", tup4)
print(tup2 + tup3)
print(tup1[1:])
print(tup1[-2])
- Nested References
Lists can contain dictionaries, which can contain tuples.
train = [50, 20, 'apple']
train[1] = {'name': 'lili', 'age': 30}
print(train)
def gogo():
print("i can gogogo")
train[1]['teach'] = gogo
print(train)
train[1]['teach']()