I have been learning Python for some time. The whole learning process is not systematic and there is no route. At first, I watched some Python courses from the mooC, but I didn’t finish half of the courses and didn’t write any serious programs. This lasted for nearly a year, but I never touched Python.
I kept wondering why everyone thought Python was so easy and easy to get started with. Why am I such a mess?
It wasn’t until February of this year that I wrote my first crawler in Python and posted it on a blog. Although not many people read it, it gave me my first taste of the fun of Python. After that, I gradually compiled my first small game, including snake, crawler for barrage, small video made by Python, and pictures…
As I experimented with examples, I learned more about Python, realized how powerful and interesting the language is, and of course learned a lot about my own shortcomings.
Because I did not systematically learn the syntax of Python, I often made various errors in programming. For example, I also wrote a blog about collection errors before. Later, when I saw it in the rookie tutorial, the first sentence of collection was that {} could not be used to create empty collections. It was very uncomfortable…
So, this blog post was born.
First, target readers
To make this blog formal, LET me say something about the target audience:
Readers who have no knowledge of Python but have some background in other languages
Readers who know some of python’s basic syntax, but have not had programming practice
Readers who have no knowledge of Python at all, but know part of program theory
Completely unprogrammed, ready to start Python (not recommended)
Of course, if you’re the big cheese in Python, ask the big cheese to help you figure out what’s wrong with your program.
What does this example look like
Write it before the program
The whole program contains 138 knowledge points, ha ha, do not look at the knowledge points, in fact, each knowledge point in the code I wrote a sentence. So that’s 138 lines of code.
In Python, you can comment with # signs, and I use # signs in my programs to explain what the code means. At the same time, give the number of knowledge points.
Also, Python uses indentation between codes to indicate membership, which is simply as follows:
Getting started with Python, you’ll enjoy this 300-line example. Ok, let’s give you my 300-line example
Note: If you are a beginner, you can read and run each function individually. Of course, you can’t just read code, you have to do it
Note: In Python you need to pay attention to indentation between codes. Membership is usually expressed as a TAB distance
Math,copy,random,time from collections import Counter #2, from… import …. Def hello_world() def hello_world() def hello_world(): #4: create a function using the def keyword. Simply put: A function is a block of code with independent functions organized into a module, which is called when needed
Def name(argument 1, argument 2....) : Print (' Welcome to the Python world,',yourname) print(), To print multiple objects, use comma-separated print(' Let's get started ~')Copy the code
def hello_twice():
Global yourname, yourheight yourweight # 7, using the global keyword to define a global variable, in the process operation cycle can be called yourname = input (" please input your name: ') yourheight = input(' please enter yourheight :') yourweight = input(' please enter yourweight :')Copy the code
Def deviding_line() def deviding_line():
Word1 = 'I am line' #8, string creation, using single quotation marks' or double quotation marks "word2 = word1. Upper () #9, string function, using the operator. Word3 = word1.lower() #10, lower(); word4 = word1.title() #11, title(); Can string title change # above three functions only as part of the string function words = [word1 word2, word3, word4] # 12, [] can create a list, the list can hold a lot of object line = '-' 40 # 13, the use of * * operator to create a string, EndReturn = line+words[random. Randint (0,3)]+line #14 Random.randint () creates a random integer, with 0 and 3 being the upper and lower bounds for random numbersCopy the code
Def study_number():
Num1 = input(' %s'%num1 ') print(' %s'%num1 ') ',type(num1)) #18,type(num2) can return the type of the value num2 = int(input(' a second number :')) Print (' you entered a number %s' % num2, 'which is of type: ', type(num2)) num3 = float(input(' num3 ')) #20, float() print(' %s' % num3, '%s') ', type(num3)) print('num1+num2={}'. Format (int(num1)+num2)) print('num1+num2={}'. Print ('num1*num2={}'. Format (int(num1)-num2)) print('num1*num2={}'. Format (num1*num2)) Num1 *num2 will not be the data you want because the input() function, Print ('num1*num2={}'. Format (int(num1) *num2)) print('num2//num3={:.3f}'. Print ('num2/num3={:.4f}'. Format (num2/num3)) print('num2/num3={:.4f}'. Print ('num2%num3={:.4f}'. Format (num2%num3)) print('num2%num3={:.4f}'. Print ('num1**num2={}'. Format (int(num1)**num2)) print('This is the {a},and {b}'. Format (a='numbers',b='some operations') Print (one,two,three) print('and operator :',one and two,one and three) Print ('or :',one or two,one or three) print('or :',one or two,one or three) Print ('not operator :',not one,not two,not three) #35 print('not operator :',not one,not two,not threeCopy the code
Def study_list(length): l1 = [1,2,3,4,5,9.0]
L2 = list(range(10,10+length)); l2 = list(range(10,10+length)); l2 = list(10,10+length); Print ('l1 ': Print (l1[1],l2[1]) print(l1[1],l2[1]) Print (id(l1),id(l2),id(l3)) print(id(l1),id(l2),id(l3)) print(id(l1),id(l2),id(l3)) Print ('l2==l3 ') print('l2==l3 ') print('l2==l3 ') print('l2==l3 ') print('l2==l3 ') print('l2==l3 ') ', l2 = = l3) # 44, update after the l3 is still equal to l2, l3 and l2 is an object, but to change a name l4 = l2. The copy () # 45, copy a l2 to l4, Print ('l4==l2 ') print('l4==l2 ') ',l4==l2) #46, l2 ==l2 Extend (l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) #49, extend(l1) Reverse () #50 print(' reverse :',l4) #50 print(' reverse :',l4) #50 print(' reverse :',l4) #50 print(' reverse :',l4) #50 print(' reverse :',l4) #50Copy the code
Def study_tuple(length:int)->bool
Tuple1 = (1,2,3,4) Print (tuple1.count(1)) print(tuple1.count(1)) print(tuple1.count(1)) print(tuple1.count(1)) print(tuple1.count(1) Print (tuple1. Index (1)) # 56, tuple function index (), can be in accordance with the index value of the try: Except TypeError: tuple1[0] = 9 except TypeError: tuple1[0] = 9 Try: print(id(tuple1),id(tuple2)) except: print(id(tuple1),id(tuple2)) except: Print (tuple3,id(tuple3)) return True. Print (tuple3,id(tuple3)) return TrueCopy the code
Def study_dict(): # learn python’s dictionary model, where dictionaries are key -> value mappings
Dict1 = {1: 'a', 2, '2', 3: '3', 4: 'four'} # 61, the following five methods for creating a dictionary dict2 = dict (one = 1, two = 2, three = 3) dict3 = Dict (zip (,7,8,9 [6], [' Six 'and' Seven ', 'Eight', 'says'])) dict4 = dict ([(' One', 1), (" Two ", 2), (" Three ", 3)]) dict5 = Dict ({1: 'a', 2, '2', 3: '3', 4: 'four'}) print (type (dict1), dict1 = = dict5) # 62, you can see, Dict1 [1],dict2['one'],dict3[6],dict4[' one'], dict5[1] Dict1 [1] = 'dict1', dict2 [5] = 'dict1', dict2 print(1 in dict1, 6 in dict1) 7) #67, in and not in, Dict6 [1] = 'One' print(dict1,'<dict1------------dict6>',dict6) dict1. Clear () # 69, dictionary of clear print (dict1) del dict1, dict2, dict3, dict4, dict5, dict6 # 70, delete the dictionary, you can also use del dict [key] way to delete a keyCopy the code
Def study_set(): #python sets that do not have equal values
Characters = set ([' You 'and' Are ', 'Not', 'Beautiful']) # 71, using the set () function to create the collection set2 = {' You ', 'Are', 'So', 'Beautiful'} # 72, use {} to create a collection, Create an empty set of time can't use {}, because a dictionary set3 = {} said set2. Copy (# 73), a collection of copy print (type (characters) print (characters, set2) print (characters | set2) # 74, collections, or operator, Print (set1^set2) print(set1^set2) print(set1^set2) print(set1^set2) print(set1^set2) Print (set1<=set2,set3<=set2,set3< =set2) print(set1<=set2,set3<=set2) Print ('is ',set3==set2,set3 is set2,set1 is not set2) #80, is, is not Print (set3) del set3 print(set3) del set3 print(set3) del set3 print(set3) del set3 print(set3) del set3 print(set3) del set3Copy the code
Def study_Some_functions(): # some functions in Python
List1 = [1,2,3,4,5,6] Tuple1 = (11,12,13,14,15,16) # tuple1 = set(list1) # set dict1 = Dict (zip ([1, 2, 3, 4, 5], [' one ', 'Two', 'Three', 'Four', 'Five'])) # print dictionary (Max (list1), Max (tuple1), Max (characters), Max (dict1)) Print (min(list1),min(tuple1),min(set1),min(dict1)) Print (sum(list1),sum(tuple1),sum(set1),sum(dict1)) Print (len(list1),len(tuple1),len(set1),len(dict1)) Print (divmod(list1[0],tuple1[0])) #86 divmod(list1[0],tuple1[0]) Print (list(tuple1)); print(list(tuple1)); print(tuple1); Dict3 = list(set1) list4 = list(dict1) tuple2 = tuple(list1) Print (list2,list3,list4) for I in range(len(list1)): Print () for I in dict1: print(list1[I],end= ") print(list1[I],end= ") Print (I,dict1[I],end= ") list5 = list(reversed(list1)) Print ('\n',list5) #94, \n, newline testStr = "The mountains and rivers are different, The wind and the moon are the same" words = teststr.split (") #95, split(); Print (words) words.sort(key=len) #96, sort() Print (' sort by length :',words) words.sort(key=len, reverse=True) Print (' sort by length and reverse :', Print (' print in lexicographic order :',words) ct = Counter(testStr) Print (ct) ct.update(' eeeexXXXXlllll ') print(ct) Print (ct.most_common(5)) #101 print(ct.most_common(5)) #101Copy the code
Def study_Slice(): # Python slicing to get part of the sequence
str1 = 'I hope one day, I can find you, Print (str1[:]) print(str1[:]) print(str1[:]) print(str1[:]) Before closed after open, step can be plus or minus, the default step 1 print (str1] [: : - 1) # 103, when the step is negative, reverse print (str1 [15]) # 104, but only the end, End print(str1[15:]) #105 Print (str1[::2]) print(list1[:]) #107 print(list1[:]) Print (list1[:2]) print(list1[::-1]) list1[1:5] = [10] # print(list1[::-1]) list1[1:5] =Copy the code
Def study_loop_select(): # loops and select statements in python
List1 = [1,2,3,4,5] num = int(input('while ')) I = 1 while I <=num: If I <5: #109, if... elif... Else select statement. If there are only two results, use if... Else print(' I ', 'I ') elif I <10: print(' I ',' I ', 'I ') elif I <10: print(' I ',' I ', 'I ') elif I <15: print(' I ',' I ', 'I ') elif I <10: print(' I ',' I ', 'I ',' I ') ') elif i<20: print('continue... Print (' I don't think I can print anything 'else: print(' I'm exhausted, rest. I +=1 time. Sleep (0.5) #112, the time library is a python time library, and the time library is a python time library. Time. Sleep (second) can pause the program running second else: Print ('while finished ') for I in list1: print('while finished ') for I in list1: print('while finished ') for I in list1: Print (I,end= ") print() for I in range(5): print(I)Copy the code
Def study_expression_deduction()
List2 = [x for x in range(20) if x%2==0] list2 = [x for x in range(20) if x%2==0] Print (list1,'<list1--------------list2>',list2) print(deviding_line()) List3 = [['_'] * 3 for I in range(3)] print(list3) fruits = ['Apple','Banana','Pear'] colors = ['Red','Yellow','Green'] Suitcolor = [(color,fruit) for color,fruit in zip(colors,fruits)] # Cartesian = [(color,fruit) for color in colors for fruit in fruits] #119, two tables of cartesian product print(cartesian) dict1 = {fruit:color A dictionary can be derived from any sequence with key-value pairs.Copy the code
Def study_files(): filepath= input(‘ please enter your filepath (enter quit): ‘) if filepath==’quit’: return True
try: File = open(filepath,'w') #121, file = open(filepath,'w') #121, file = open(filepath,'w') Close () #123, close file = open(filepath,'r') #122, print(' r') \n',file.read()) #123 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =Copy the code
Class Users(): #125, object-oriented programming, python create class, class contains properties and methods, including private variables, common variables, etc
def __init__(self,name,height,weight): Self.name = name self.height = height self.weight = weight self.yanzhi = 100 def display(self): self.name = name self.height = height self.weight = weight self.yanzhi = 100 def display(self): self.name = name self.height = height self.weight = weight self.yanzhi = 100 def display(self): Print # 127, class method (' hello, I am {}, {} height, weight, {}, ultra-high {} 'appearance level. The format (self. The name, the self. The height, the self weight, the self, yanzhi))Copy the code
If name==”main”: #128
Hello_world () #129, so this is the first sentence to run, call deviding_line() try: Hello_world () = yourname = yourname = yourname = yourname = yourname = yourname = yourname = yourname = yourname = yourname Print (' yourname ')#131 print(' yourname ')#131 Only exists inside hello_world() deviding_line() hello_twice() #132 So the function of the variables in the following applications can use the user = Users (yourname, yourheight, yourweight) # 133, instantiate objects, In Python, it is possible to use triple quotes for multiple lines of comments, but it is also possible to receive comments as a formatted string using variables. Chooseinformation = "Input the number of the function you want to Run(quit is exit): 1, study_number 2, study_list 3, study_tuple 4, dict 5, study_set 6, study_Some_functions 7, study_Slice Third third of class (); third of class (); third of class () The while loop executes the program, and only exits when you type quit (you can force it to exit, of course). Print (chooseinformation) num = input(' input ') #138, if... elif... Elif num=='quit': break elif num=='1': study_number() elif num=='2': study_list(10) elif num=='3': study_tuple(10) elif num=='4': study_dict() elif num=='5': study_set() elif num=='6': study_Some_functions() elif num=='7': study_Slice() elif num=='8': study_loop_select() elif num=='9': () elif num=='10': study_files() deviding_line() print('Copy the code
This program I wrote for a long time, it contains some basic grammar, python, for example, there are several kinds of common data structures: a list of tuples, dictionary, collection, string, and have their basic operation, with the object-oriented classes, looping statements, select statement, the function is the creation of a package of import, read files, slice, expression is derived.
But it’s still the most basic part of Python, and you can’t master a language without doing it yourself, typing line by line, and looking for bugs.
Of course, there is too much I don’t know yet, which is why I only wrote such a basic introductory example. And some may not stand up to scrutiny.
I’m not sure if this code can get you started, but if you find it useful, please leave your comments or suggestions in the comments section
Finally, I will give you a Python study, which is also the learning material I used before, and I feel very good. I have shared it in the previous article, but I think if some friends read this article, you may need it, so I will share it with you again today. Free to share with you, I hope you forward collection, remember to pay attention to xiaobian, thank you for your support. Thank you!
Learn Python with 757.6MB videos
1. Python readme
2. Build the Python development environment
3. Use of print function
4. Escape characters and original characters
5. Binary and character encoding
6. Reserved _ identifiers _ variables and their use
7. data types
8. Comments in Python
10. Use of the input function
11. Arithmetic operators
12. The assignment operator
13. Comparison operators
14. Boolean operators
15. Bit operators
16. The precedence of the operator
17. Program organization _ Object Boolean
18. Single branch _ double branch _ multi branch structure
19. A nested if
20. Conditional expression _pass statement
Python Basics
Python757.6 MB video
6 Slides to learn Python
The PDF technical documentation required to learn Python
From learning path to video, to PPT, to PDF technical document, Python has all been organized here, you can forward this article, pay attention to the small editor, scan the qr code below, add assistant, get free ~~