Python basic syntax for beginners
This article is for beginners, mainly to explain the basic syntax of Python. If you already have a Python foundation, then congratulations on having mastered this simple and efficient language. You can skip this article, follow our follow-up articles, or treat this article as a review.
Ok, now do you have a problem in your heart? Do I need to master Python to learn data analysis? My answer is that if you want to learn data analysis, you’d better master the Python language. Why say that?
First, in a survey of programming languages, 80% of developers who have used Python will use Python as their primary language. Python has become the fastest growing mainstream programming language. Second, in the field of data analysis, the developers who use Python are the most, far beyond the sum of other languages. Finally, the Python language is simple, with a large number of third-party libraries, powerful, and can solve most of the problems of data analysis.
The biggest advantage of the Python language is its simplicity. Although it is written in C, it eliminates the pointers of the C language, which makes the code very concise. The same line of Python code, even equivalent to 5 lines of Java code. Reading Python code is similar with reading English, which allows programmers to focus more on problem solving than on the language itself.
Of course, in addition to the features of Python itself, Python has powerful developer tools. In the field of data science, Python has many well-known tool libraries: the scientific computing tools NumPy and Pandas libraries, the deep learning tools Keras and TensorFlow, and the machine learning tool Scikit-learn.
In short, if you want to make a difference in data science, such as data analysis and machine learning, it is very necessary to master a language, especially the Python language. Master the tools we just mentioned. It will make you do more with less.
First of all, this picture tells you what we are going to learn today.
Installation and IDE environment
In order to write python codes, let’s first understand how to install and build an IDE environment.
-Python version selection
There are two main versions of Python: 2.7.x and 3.x. There are some differences between the two versions, but not large, and their grammar is not the same as less than 10%.
Another fact is that most Python libraries support both Python 2.7.x and 3.x versions. Although the official said that Python 2.7 is only maintained until 2020, but I want to tell you: Do not ignore Python2.7, its life is far more than 2020, and Python2.7 still occupies the Python version dominance in the past two years.
According to a survey, the 2.7 version of the commercial project in 2017 is still the mainstream, accounting for 63.7%. Even though the Python 3.x version used to grow faster in the past two years.
Then you may ask: How do you choose these two versions?
The standard for version selection is to see if your project will depend on the Python 2.7 package. If you have dependencies, you can only use Python 2.7, otherwise you can start a new project with Python 3.x.
-Python IDE
After determining the version issue, how do you choose the Python IDE? There are many excellent options, and several are recommended here.
1. PyCharm
This is a cross-platform Python development tool that helps users improve efficiency when using Python, such as: debugging, syntax highlighting, code jumping, auto-completion, smart prompts, and more.
2. Sublime Text
SublimeText is a famous editor, Sublime Text3 can basically start in 1 second, and the response speed is very fast. At the same time, its support for Python is also in place, with code highlighting, syntax prompts, auto-completion and more.
3. Vim
Vim is a simple, efficient tool that is fast. However, Vim has some difficulty compared to Sublime Text, and it is a bit cumbersome to configure.
4. Eclipse+PyDev
Those who are used to Java must be familiar with the Eclipse IDE, then using the Eclipse+PyDev plugin is a good choice, so developers familiar with Eclipse can easily get started.
If you haven’t used these IDEs before, Sublime Text may be a good choice, which is easy to use and fast.
Python basic syntax
Once the environment is configured, let’s quickly learn a few basic grammars that Python must have. I assume you are Python zero
Basic, but there are already some basics of other programming languages. Let us look at it one by one.
Input and output
name = raw_input(“What’s your name?”)
sum = 100+100
print (‘hello,%s’ %name)
print (‘sum = %d’ %sum)
raw_input is an input function of Python2.7. In python3.x, you can use input directly, assign it to the variable name, print is the output function, and %name represents the value of the variable. Because it is a string type, it is replaced by %s in the front.
This is the running result:
What’s your name? python
hello, python
sum = 200
Judgement: if…else…
If … else … is a classic judgment statement, it should be noted that there is a colon after the if expression, and there is also a colon after else.
It’s also worth noting that Python doesn’t use {} or begin…end to separate code blocks like other languages, instead using code indentation and colons to distinguish hierarchical relationships between code. Thus code indentation is a syntax in Python. If the code indentation is not uniform, for example, some are tab some are space, it will generate an error or an exception.
Loop:for…in
Running result:
55
For loop is an iterative looping mechanism that iterates over the same logical operations. If we specify the number of loops, we can use the range function, which is more common in for loops. Range(11) stands for 0 to 10, does not include 11, and is equivalent to range(0,11). Range can also conclude the step size. For example, range(1,11,2) represents [1,3,5,7,9].
Loop: while
Running result:
55
The sum of 1 to 10 can also be written with a while loop, where while controls the number of loops. The while loop is a conditional loop, and the way variables are calculated in a while loop is more flexible. Therefore, the while loop is suitable for loops with an indeterminate number of loops, while the condition of the for loop is relatively deterministic and suitable for a fixed number of loops.
Data type:list、tuple、dictionary、set
-[list]
lists = [‘a’,’b’,’c’]
lists.append(‘d’)
print lists
print len(lists)
lists.insert(0,’mm’)
lists.pop()
print lists
Running result:
[‘a’, ‘b’, ‘c’, ‘d’]
4
[‘mm’, ‘a’, ‘b’, ‘c’]
List is a commonly used data structure in Python, equivalent to arrays, with the ability to add, delete, and modify. We can use the len() function to get the number of elements in the list; use append() to add elements at the end; use insert() to insert an element in the list. and use pop() to remove the element at the end.
-(tuple)
tuples = (‘tupleA’,’tupleB’)
print tuples[0]
Running result:
tupleA
Tuple is very similar to list , but tuple cannot be modified once it is initialized. Because it can’t be modified, there is no such method like append() or insert(). It but can be accessed like an array, such as tuples[0], but cannot be assigned.
-{dictionary}
score = {‘gary’:95,’tom’:96}
# add an element
score[‘john’] = 98
print score
# delete an element
score.pop(‘tom’)
# check if the key exsits
print ‘gary’ in score
# View the value corresponding to the key
print score.get(‘gary’)
print score.get(‘yase’,99)
Running result:
{‘john’: 98, ‘tom’: 96, ‘gary’: 95}
True
95
99
Dictionary is actually {key, value}, and multiple times put the value into the same key, the latter value will flush the previous value, and dictionary also has additions, deletions and changes. Adding a dictionary element is equivalent to assigning, such as score[‘john’] = 98, deleting an element using pop, query using get, if the value of the query does not exist, we can also give a default value, such as score.get(‘yase ‘,99).
-set
s = set([‘a’, ‘b’, ‘c’])
s.add(‘d’)
s.remove(‘b’)
print s
print ‘c’ in s
Running result:
set([‘a’, ‘c’, ‘d’])
True
Set is similar to the dictionary, but it’s just a collection of keys and doesn’t store value. You can also add, delete and query, add use add, delete use remove, query to see if an element is in this collection, use in.
Comment:#
Comment use # in python. If it is a multi-line comment, use three single quotes, or three double quotes, such as:
# I love python
‘‘‘
I love python
I love python
I love python
’’’
import module/package: import
# import a module
import model_name
# import many modules
import module_name1, module_name2
# import module specified in the package
from package_name import moudule_name
# import all modules in the package
from package_name import *
The use of import in the Python language is straightforward and can be imported directly using the import module_name statement. What is the nature of import here? The essence of import is path search. The import reference can be a module module, or a package.
For module, it actually references a .py file. For package, you can use the method of from … import …, which actually refers to the module from a directory, in which case the directory structure must have a __init__.py file.
def
Running result:
100
The function code block begins with the def keyword, followed by the function identifier name and parentheses, the parameters passed in parentheses, and feedback from the function result via return.
For the basic syntax above, we can run Python code with the Sumlime Text editor. In addition, to tell you a fairly efficient method, you can make full use of an advanced website: LeetCode (https://leetcode.com/problemset/all/).
This website has different difficulty topics, you can use a variety of language to answer, many people looking for work will accumulate experience on this website. Don’t underestimate such problems, sometimes compilation errors, memory overflows, run timeouts, etc. can lead to incorrect answers. Therefore, the quality requirements of the code are still quite high.
Conclusion
Now we know that Python is undoubtedly the most mainstream language in data analysis. Today we have learned so much about the basic syntax of Python, you may have not experienced its simplicity. If you have other programming language foundations, I believe that it will be very easy to convert to Python syntax. At this point, Python is just getting started. Is there any way to quickly improve the level of Python programming on this basis? Share my thoughts with you.
In daily work, the problems we solve are not difficult problems. Most people do development work rather than research projects. So mainly we want to improve is proficiency, and the only path to proficiency is practice, practice, and practice!
If you are using Python for the first time, don’t worry, the best way is to do it directly. Run all of the above examples and I believe you will know.
If you want to improve your programming foundation, especially the algorithms and data structure related capabilities, because this will be used in later development. Then LeetCode is a very good choice, bravely open this door and use it as a good tool for your advancement.
You can start with the easy topic. The more questions you solve, the higher you will be ranked, which means your programming skills, including algorithms and data structures, have improved.
Ok, this tutorial is over. In the following articles, I will mainly introduce the use of several important libraries. For example, NumPy, Pandas, if you want to continue learning, please follow my Facebook page: Data Analysis Enthusiast, thank you!!