Basic grammar
data type
python is a weak data type language. When assigning a value, we do not need to declare the data type first, which is determined by the assigned value. There are several types:
integer float Character string Boolean value Null value None
Conditional statement
age = 3 if age >= 18: print('adult') elif age >= 6: print('teenager') else: print('kid')
Loop statement
names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name)
How do I access list values through indexes like any other programming language?
names = ['Michael', 'Bob', 'Tracy'] for i in range(0,len(names)): print(names[i])
Other cycles
n = 1 while n <= 100: print(n) n = n + 1 print('END')
break and continue are similar to other languages, so we won't repeat them.
list
There is no such noun as array in python. Instead, list and tuple are used. The difference is that list is variable and tuple is immutable. We can use the help function to view the list method
Example
classmate = ['johnw',"jack","tom","michael"] # Last element of pop-up list: michael p = classmate.pop() print("pop Return: ",p) print("pop The following list is: ",classmate) # End element add p1 = classmate.append("mary") print("append Return: ",p1) print("append The following list is: ",classmate) # copy list p3 = classmate.copy() print("copy Return: ",p3) print("copy The following list is: ",classmate) # count returns the number of an element in the list p4 = classmate.count('johnw') print("count Return: ",p4) print("count The following list is: ",classmate) # Index find the index of the element p5 = classmate.index("jack",1) print("index Return: ",p5) # remove element p6 = classmate.remove("johnw") print("p6 Return: ",p6) print("remove The following list is: ",classmate) # reverse and sort a1 = [2,3,51,4,6,2,7,8] a1.sort() print("sort after a1 For:",a1) a1.reverse() print("reverse after a1 by: ",a1) # Clear list elements p2 = classmate.clear() print("clear Return: ",p2) print("clear The following list is: ",classmate)
dict dictionary
Dictionary is a common data structure. Using key value method to search is very fast. It is a data structure that uses space for time. The advantage is that both search and insert are fast, and the disadvantage is that it will occupy a lot of memory
insert values
test = {} test["Hello"] = "world"
lookup
test.get("Hello") test["Hello"]
Key value cycle
for key,value in test.items(): print("key===>",key) print("value===>",value)
Key cycle
for key in test.keys(): print("key: ,key)
Value cycle
for value in test.values(): print("value: ",value)
Key update
>>> a={"a":1,"b":2} >>> a.update({"c":3}) >>> a {'a': 1, 'b': 2, 'c': 3}