The purpose of this article is not to compare the two languages, but to compare and learn, suitable for students who want to learn Python Go or master Go to learn Python reference.
Golang and Python are currently among the most popular development languages in their respective fields.
Golang, with its efficient and friendly syntax, has won the favor of many backend developers and is one of the most suitable languages for highly concurrent network programming.
Python needless to say, TIOBE’s top ten resident residents are now firmly in the top five. It has become a must-learn language in machine learning, AI and data analysis.
Both programming languages have their own syntax and are easy to learn and use.
Go is a static language and Python is a dynamic language, which are fundamentally different from each other in many ways. Therefore, we will not Go into much depth in this article. We will only compare the syntax that is most intuitive to programmers.
For ease of reading, the code is presented in simple statements
A character encoding
Python
The default encoding format in Python2 is ASCII. If the program file contains Chinese characters (including comments), you need to add # -* -coding: UTF-8 -*- or #coding= UTF-8 at the beginning of the file
Python3 supports Unicode by default
Golang
Native Unicode support
Reserved Words (keywords)
Python
30 keywords
and exec not assert finally or break for pass class from print continue global raise def if return del import try elif Copy code in while else is with except lambda yieldCopy the code
Golang
25 keywords
break default func interface select case defer go map struct chan else goto package switch const fallthrough if range Type Continue for Import Return var Copies codeCopy the code
annotation
Python
# Single-line comment "" Multi-line comment """ multi-line comment """ Copy codeCopy the code
Golang
// Single line comment /* multiple line comment */ copy codeCopy the code
Variable assignment
Python
Python is a dynamic language, so you do not need to declare the type when defining variables. Python determines the type based on the value.
Name = "Zeta" # string variable age = 38 # integer income = 1.23 # float number copy codeCopy the code
Multivariable assignment
A,b =1,2; b=2 c = d = 3 # c=3; D =3 copy the codeCopy the code
Golang
Go is a static language and strongly typed, but the Go language also allows you to determine the type when assigning a variable.
So Go has a variety of ways to declare variables
Var a int a = 1 // 2. Var a int = 1 // 3. Var a = 1; var a = 1Copy the code
Note that the new keyword in Go does not declare a variable, but returns a pointer to that type
A := new(int) // a is a *int pointer variable copy codeCopy the code
Standard data types
The standard Python data types are:
- Boolean (Boolean)
- Number = Number
- String (String)
- List (List)
- Tuple (Tuple)
- Set
- The Dictionary
Golang
- Boolean (Boolean)
- Numeric (number)
- String (string)
- Array (array)
- Slice: an indefinite array
- Map (dictionary)
- Struct (structure)
- Pointer
- Function = function
- Interface (s)
- Channel
conclusion
The List List in Python corresponds to the Slice in Go
The Dictionary in Python corresponds to the Map in Go
There are a few things to note:
- Go is a language that supports functional programming, so a function is a type in Go
- Go language is not object-oriented language, there is no definition of the Class keyword Class, OOP style programming is to achieve through struct, interface type
- Both tuples and collections in Python are absent in Go
- A channel is a type unique to Go that communicates between multiple threads
Data type conversion
Python
Python type conversions are very simple, using the type name as the function name.
Int (n) # Converts the number n to an integer float(n) # Converts the number n to a floating point STR (o) # Converts the object obj to a string tuple(s) # Converts the sequence s to a tuple list(s) # Converts the sequence s to a list Set (s) # converts sequence S to a set copy codeCopy the code
Golang
Go’s basic type conversions are similar to Python’s, using type names as function names
I := 1024 f := FLOAT32 (I) I = float32(f) Duplicates the codeCopy the code
Alternatively, it is possible to convert numeric strings and numbers directly in Python:
Print (int(s), STR (I)Copy the code
But Go is not ok.
String () can only be converted to a string from []byte. Other basic conversions require the Strconv package. In addition, other conversions to string can be made using the ftm.sprintf function:
package main import ( "fmt" "strconv" ) func main() { s := "123" i, _ := strconv.atoi (s) println(I) s2 := fmt.sprintf ("%d", 456) println(s2)} Copy codeCopy the code
The interface type in Go cannot be directly converted to any other type, requiring assertion
Package main func main() {var itf interface{} = 1 I, ok := itf.(string) println(" value :", I, "; The assertion results ", ok) j, ok: = itf. (int) println (" value: "j,"; Assert result ", OK)} copy codeCopy the code
The output is:
Value:; Predicate result false value: 1; Assert the result true copies the codeCopy the code
Conditional statements
Python
Python’s traditional judgment statement is as follows
Zeta print('Welcome boss') else: print('Hi, '+ nameCopy the code
Python does not support ternary expressions, but a similar alternative is available
Title = "boss" name = "zeta" if title == "boss" else "chow" print(name) copy codeCopy the code
Logic and use and, logic or use or
Golang
Go’s if syntax is similar to Java, but expressions do not need to use ()
If a > b{println("a > b")} else {println("a <= b")} copy codeCopy the code
Go also has no ternary expression, and there are no alternatives.
In addition, Go allows variables to be defined in if expressions, defined and assigned expressions, and evaluated expressions. The common case is to get the function to return error, and then determine whether error is null:
if err := foo(); err ! = nil {println(" something went wrong ")} copy codeCopy the code
Unlike Python, logic and use &&, logic or use the | |
Looping statements
Python
Python has two types of loops, while and for, both of which can be used to break out of the loop and continue immediately into the next loop. In addition, Python’s loop statements can be used to execute the code after the loop is complete with an else, which is not executed after the break
While conditional loop,
count = 0 while (count < 9): print('The count is:', count) count = count + 1 if count == 5: Pass else: print('loop over') copies the codeCopy the code
For iterates through a loop that iterates over all the children of a sequence object
names = ['zeta', 'chow', 'world'] for n in names: print('Hello, ' + n) if n == 'world': break pass else: print('Good night! ') copy the codeCopy the code
We can also use else in the for loop (try commenting out the break in the code).
Golang
The Go language has only one loop statement, for, but it behaves differently depending on the expression
For preexpression; Conditional expression; After expression {//... } Duplicate codeCopy the code
Pre-expressions run before each loop and can be used to declare variables or call functions to return; If the conditional expression satisfies this expression, the next loop is executed; otherwise, the loop exits. The post-expression is executed after the loop completes
Classic usage:
for i := 0; i < 10; I ++ {println(I)} copies the codeCopy the code
We can ignore the pre – and post-expressions
Sum = 1 for sum < 10 {sum += sumCopy the code
Set to ignore all expressions, i.e., loop indefinitely
For {print(".")} copies the codeCopy the code
The for loop of Go can also use break to exit the loop and continue to proceed to the next loop immediately.
In addition to working with expression loops, for can also be used for traversal loops, using the range keyword
Names := []string{"zeta", "chow", "world"} for I, n := range names {println(I,"Hello, "+ n)} copy codeCopy the code
function
Python
Functions are defined with the def keyword, and in Python, as a scripting language, functions must be called after the function is defined.
Def foo(name): print("hello, "+name) pass foo("zeta"Copy the code
When Python defines a function parameter, you can set a default value. If the parameter is not passed when called, the default value is used in the function. The default value parameter must be placed after the non-default parameter.
Def foo(name="zeta"): print("hello, "+name) pass foo(Copy the code
Generally, when a function passes its arguments, it must pass them in the order in which they are specified. However, Python allows the use of keyword arguments, so that by specifying the arguments, the arguments are not passed in the order in which the function defines them.
def foo(age, name="zeta"): print("hello, "+name+"; Age ="+ STR (age)) pass foo(name="chow", age=18) Copy codeCopy the code
Variable arguments, Python supports variable arguments. Use * to define parameter names. Multiple arguments are passed into a function as a meta-ancestor when called
Def foo(*names): for n in names: print("hello, "+n) pass foo("zeta", "chow", "world") copy codeCopy the code
Return Returns the result of the function.
Golang
Go defines functions with func, no default value arguments, no keyword arguments, but many other features.
func main() { println(foo(18, "zeta")) } func foo(age int, name string) (r string) { r = fmt.Sprintf("myname is %s , Age %d", name, age) return} Copy codeCopy the code
Functions can be defined and called in any order.
The function of Go can not only define the return value type of the function, but also declare the return value variable. When the return value variable is defined, the return statement in the function does not need to have the return value, and the function will use the return value variable to return by default.
Variable parameter
The use of… A type defines mutable parameters, and the parameters obtained inside the function are actually slice objects of that type
Func main() {println(foo(18, "zeta", "chow", "world"))} func foo(age int, names... String) (r string) {for _, n := range names {r += fmt.sprintf (" myName is %s, age %d \n ", n, age)} return} Copy codeCopy the code
Defer sentence
The defer statement specifies a function that will be deferred until the return of this function.
The defer statement is very useful in the Go language, and you can check out another article in this column, Golang Studies: How to Master and Use defer well.
Func foo() {defer fmt.println ("defer run") fmt.println ("Hello world") return} duplicate the codeCopy the code
Running results:
Hello World defer run copies the codeCopy the code
In addition, functions in Go are also types that can be passed as arguments to other functions
func main() { n := foo(func(i int, j int) int { return i + j }) println(n) } func foo(af func(int, Int) int) int {return af(1, 2)} copy codeCopy the code
The above example, which uses function types directly in parameter definitions, looks a bit confusing
Take a look at a clear and complete example. The instructions are all in the comments.
Package main type math func(int, int) int // Define a function type, two int arguments, one int return value // define a function add, which takes two int arguments and one int return value, Func add(I int, j int) int {return I + j} Multiply (I, j int) int {return I * j} //foo () {return I * j} //foo (); Func foo(m math, n1, n2 int) int {return m(1, N := foo(add, 1, 2) println(n) Count n = foo(multiply, 1, 2) println(n)} copy the codeCopy the code
The results of
3 2 Copy the codeCopy the code
The module
Python
- The module is a.py file
- The module executes the first time it is imported
- One underscore defines protected variables and functions, and two underscores define private variables and functions
- Import modules are customary, but not mandatory, at the top of scripts
Golang
- The first line of each file defines the package name with package, regardless of the file name or file name
- The variable in the package is initialized when it is referenced for the first time, or if the package contains init (after the variable is initialized).
- Take care that functions and variables that begin with uppercase letters are common and lowercase letters are private. Golang is not object-oriented, so there is no protection level.
- Import modules must be written after the Package and before any other code.
Import packages
Python
In Python, use import to import modules.
#! /usr/bin/python # -* -coding: utF-8 -*- # Import module import support support.print_func(" Runoob ") copy codeCopy the code
You can also specify parts by importing modules using from Import
From modname import name1[, name2[,... nameN]] copy codeCopy the code
Alias the imported package with the AS keyword
Import datetime as DT copy codeCopy the code
Golang
The import package specifies the path of the package. By default, the package name is the last part of the path
Import "net/ URL "// Import url package copy codeCopy the code
Multiple packages can be imported as a combination of ()
Import (" FMT ""net/ URL") copies the codeCopy the code
Set aliases for imported packages. When importing packages, add aliases in front of the registration directly, separated by Spaces
Import (f "FMT" u "net/ URL ") copy codeCopy the code
Errors and exceptions
Python
Python catches exceptions with the classic try/except method
Try: < statement > # run other code except < exception name >: < statement > # except < exception name >, < data >: < statement > # Get additional data copy code if an exception with the specified name is raisedCopy the code
Else and finally are also provided
If no exception occurs, the finally block’s code executes whether or not an exception is caught
Python has a comprehensive built-in exception type name and the ability to customize the exception type
Golang
Golang does not use the classic try/except method to catch exceptions.
Golang offers two ways to handle errors
- The function returns
error
Type object error panic
abnormal
In general, only the error type is used to detect errors in Go. Go officials expect developers to be able to clearly control all exceptions and return or determine the existence of errors in every possible exception.
Error is a built-in interface type
Type Error interface {error () string} Copies codeCopy the code
In general, exception handling with error looks something like this:
Package main import "FMT" func foo(I int, j int) (r int, err Error) {if j == 0 {err = FMT.Errorf(" parameter 2 cannot be %d", } return I/j, err // If no error is assigned to the err variable, N, err := foo(100, 0) if err! Println (err.error ())} else {println(n)}} copy the codeCopy the code
Panic can be called manually, but Golang officially advises against using Panic as much as possible and that every exception should be caught with an error object.
The Go language can trigger a built-in panic in some cases, such as 0 division, array out of bounds, etc. To modify the above example, we let the function cause 0 division panic
Package main foo(I int, j int) (r int) {return I/j} func main() { N := foo(100, 0) println(n)} copy the codeCopy the code
Will appear after running
panic: runtime error: integer divide by zero goroutine 1 [running]: main.foo(...) /lang.go:4 main.main() /lang.go:9 +0x12 exit status 2 Copies the codeCopy the code
Manual Panic can do this:
Func foo(I int, j int) (r int) {if j == 0 {panic("panic: j = 0")} return I/j} copy codeCopy the code
After running, you can see the first sentence of the error message:
Panic: Panic Description: j is 0 to copy the codeCopy the code
object-oriented
Python
Python is fully object-oriented.
Golang
Although the Go language allows object-oriented style programming, it is not itself object-oriented
Official FAQ
Is Go an object-oriented language?
Yes and no. Although Go has types and methods and allows an object-oriented style of programming, There is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to Use and in some ways more general. There are also ways to embed types in other types to provide something analogous — but Not identical — to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, Integers. They are not restricted to structs (classes).
multithreading
Python
- use
thread
In the modulestart_new_thread()
function - use
threading
Module creation thread
Golang
Create the coroutine Goroutine with the key Go
Specifying a function after the go keyword opens a coroutine to run the function.
package main import ( "fmt" "time" ) func foo() { for i := 0; i < 5; i++ { fmt.Println("loop in foo:", i) time.Sleep(1 * time.Second) } } func main() { go foo() for i := 0; i < 5; I ++ {FMT.Println("loop in main:", I) time.sleep (1 * time.second)} time.sleep (6 * time.second)} copy the codeCopy the code
In Go, communication between coroutines is implemented through channels:
Package main import (" FMT ""time") // accept a chan parameter c func foo(c chan int) {time.sleep (1 * time.second) // wait 1 Second c <- Func main() {c := make(chan int) c go foo(c) C fmt.Println("wait chan 'c' for 1 second") fmt.Println(<-c) // Fetch chan 'c' valueCopy the code
conclusion
Python and Go are among the most easy-to-learn and easy-to-use programming languages in both dynamic and static languages, respectively.
There is no substitute relationship between them, but each plays its own role in its own field.
Python’s syntax is simple and intuitive, making it easy for programmers to use in other fields.
Go and have a grammar is simple and efficient operation of have a little, in a multithreaded processing is very good, very suitable for have a certain programming basis and a mainstream language students learning, however, Go is not to support object-oriented, for most users support object-oriented language at the time of learning the language, and need to keep in mind that conversion programming ideas.