Python Basics
This article will introduce the most basic processing and operations in Python.
1. Variables
In Python, variables do not need to be declared; they can be assigned directly, as follows:
Python | |
---|---|
1 2 3 |
|
2. Output Variables
There are multiple ways to output variable contents, as follows:
2.1 Using the print()
Method
The print()
method outputs the content of a variable directly, as follows:
Python | |
---|---|
1 2 |
|
Output:
Text Output | |
---|---|
1 |
|
2.2 Using the type()
Method
The type()
method returns the type of a variable and can be used with print()
, as follows:
Python | |
---|---|
1 2 |
|
Output:
Text Output | |
---|---|
1 |
|
2.3 Using the repr()
Method
The repr()
method returns detailed information about the variable and can be used with print()
, as follows:
Python | |
---|---|
1 2 |
|
Output:
Text Output | |
---|---|
1 |
|
Using the repr()
method outputs strings with quotes, which helps distinguish between numbers and string numbers.
2.4 Output Multiple Values
print()
can output multiple variable values at once, making it convenient to display key program information, as follows:
Python | |
---|---|
1 2 3 4 |
|
Output:
Text Output | |
---|---|
1 |
|
It is also possible to use the format "title, content" for output, which makes it easier to check each variable's value, as follows:
Python | |
---|---|
1 2 |
|
Output:
Text Output | |
---|---|
1 |
|
3. Basic Data Types
In Python, the following basic data types are included:
Data Type | Description | Example |
---|---|---|
None |
Null Value | a = None |
int |
Integer | a = 100 |
float |
Float | a = 100.0 |
str |
String | a = 'Hello, World! |
bool |
Boolean | a = True b = False |
When writing Python code, avoid using data type names directly as variables, such as:
Python | |
---|---|
1 |
|
3.1 Null Value None
None
is also a value used to indicate "nothing", and can be checked using is
or is not
, as follows:
Python | |
---|---|
1 2 3 4 |
|
Output:
Text Output | |
---|---|
1 2 |
|
3.2 Integer int
, Float float
int
, float
can perform mathematical operations and comparisons, as follows:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Output:
Text Output | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
3.3 Strings str
str
can concatenate strings, format them, compare equality/size (i.e., letter ordering), and check inclusion, as follows:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Output:
Text Output | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Generally, it is recommended to use formatting to generate strings (in Python called f-string
), as this makes the code more intuitive compared to simple concatenation.
The f-string
syntax structure is as follows:
3.4 Booleans bool
bool
can perform logical operations, as follows:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 |
|
Output:
Text Output | |
---|---|
1 2 3 4 5 6 |
|
4. Common Data Types
Besides basic data types, Python also includes some very commonly used data types.
4.1 Lists list
A list is an ordered collection of several elements, similar to arrays Array
in other programming languages.
Elements in a Python list can be of any type and do not require the same type, such as:
Python | |
---|---|
1 2 |
|
When writing Python code, avoid using data type names directly as variables, such as:
Python | |
---|---|
1 |
|
Commonly supported list operations are as follows:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
|
Output:
Text Output | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
4.2 Tuples tuple
Tuples are similar to lists and are also ordered collections of several elements, but tuples cannot be modified once created.
Elements in a Python tuple can be of any type and do not require the same type, such as:
Python | |
---|---|
1 2 |
|
When writing Python code, avoid using data type names directly as variables, such as:
Python | |
---|---|
1 |
|
Since parentheses representing tuples might confuse with ordinary parentheses, when defining a tuple with only one element, an extra comma must be added, as follows:
Python | |
---|---|
1 2 |
|
Output:
Text Output | |
---|---|
1 |
|
4.3 Dictionaries dict
Dictionaries are unordered collections of several elements organized in Key-Value pairs, similar to Map
in other programming languages.
In Python dictionaries, Keys are generally strings, while Values can be of any type and do not require the same type, such as:
Python | |
---|---|
1 2 3 4 5 6 |
|
When writing Python code, avoid using data type names directly as variables, such as:
Python | |
---|---|
1 |
|
Commonly supported dictionary operations are as follows:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
Output:
Text Output | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
4.4 Sets set
Sets are unordered collections of unique elements.
Elements in a Python set can be of any type and do not require the same type, such as:
Python | |
---|---|
1 2 |
|
When writing Python code, avoid using data type names directly as variables, such as:
Python | |
---|---|
1 |
|
Commonly supported set operations are as follows:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
Output:
Text Output | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
4.5 Mutual Nesting
Lists, dictionaries, and sets can be mutually nested to create complex data structures, such as:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Complex data composed of basic data types, lists, tuples, and dictionaries can be converted into JSON strings using Python's built-in json
library, such as:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Output:
Text Output | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
5. Conditional Handling with if-elif-else
Syntax
In Python, use if ... elif ... else
for conditional handling, such as:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 |
|
Output:
Text Output | |
---|---|
1 |
|
Conditional handling can also be nested to achieve more complex control, such as:
Python | |
---|---|
1 2 3 4 5 6 7 |
|
Output:
Text Output | |
---|---|
1 2 |
|
6. Loop Handling with for
and while
Syntax
In Python, you can use for ...
or while ...
for loop handling.
6.1 for
Loop
for
loops are generally used for known iteration counts, such as traversing lists, like:
Python | |
---|---|
1 2 3 |
|
Output:
Text Output | |
---|---|
1 2 3 |
|
You can also use range(...)
to directly specify the number of iterations, such as:
Python | |
---|---|
1 2 |
|
Output:
Text Output | |
---|---|
1 2 3 |
|
You can also use enumerate(...)
to loop through lists and simultaneously obtain indices, such as:
Python | |
---|---|
1 2 3 |
|
Output:
Text Output | |
---|---|
1 2 3 4 |
|
6.2 while
Loop
while
loops are generally used for known conditions, executing the loop while the condition is met and ending it when the condition is no longer satisfied, such as:
Python | |
---|---|
1 2 3 4 5 |
|
Output:
Text Output | |
---|---|
1 |
|
Be cautious when using while
loops, ensuring that the condition eventually becomes false to prevent infinite loops.
6.3 Skipping, Interrupting Loops
During the loop process, you can use the continue
statement to immediately jump to the next iteration, or use the break
statement to terminate the entire loop, such as:
Python | |
---|---|
1 2 3 4 5 6 7 |
|
Output:
Text Output | |
---|---|
1 |
|
7. Functions
Functions are reusable code segments that reduce coding complexity, such as:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Output:
Text Output | |
---|---|
1 2 3 |
|
7.1 Function Parameters
In the above example, the plus
function contains a
and b
as two parameters for input. These input parameters can be directly used within the function.
Additionally, function parameters support default values. Parameters with default values do not need to be specified during function calls, such as:
Python | |
---|---|
1 2 3 4 5 |
|
Output:
Text Output | |
---|---|
1 2 |
|
Function parameters can also be called using parameter=value
without strictly adhering to the order, such as:
Python | |
---|---|
1 2 3 4 5 6 |
|
Output:
Text Output | |
---|---|
1 2 3 4 |
|
7.2 Function Return Values
The return
statement is used to return function results. Besides returning a single value, functions can also return multiple values at once, such as:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Output:
Text Output | |
---|---|
1 2 |
|
8. Import Modules with import
Statement
In more complex projects, it is often necessary to place code in multiple different scripts for easier maintenance and management.
When calling code between scripts, the import
statement is required.
Imported Script Location | Import Method |
---|---|
Python script in the same directory | import {script name} |
Python script in a subdirectory | import {directory name}.{script name} |
Import specific content | from {script name} import {object 1}, {object 2}, ... |
Moreover, for external scripts with long names, you can use import xxx as yyy
to assign aliases, such as:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 |
|
Python | |
---|---|
1 2 3 |
|
Python | |
---|---|
1 2 3 4 5 6 7 8 9 |
|
Output:
Text Output | |
---|---|
1 2 3 4 |
|
The description of import
here is only the simplest and most common part. For complete and detailed import
introduction, please refer to professional tutorials.
8.1 Scripts in DataFlux Func
Due to the special mechanism of script management in DataFlux Func, scripts in the system are not stored as files but saved in the database. Therefore, importing other scripts in DataFlux Func differs somewhat from standard Python.
In DataFlux Func, Python scripts are organized in two layers: the first layer is "script sets," and the second layer is "scripts." A script set is merely a collection of scripts and is not a "folder".
Script sets and scripts each have their own ID and are associated. The ID of a script under a certain script set is always {associated script set ID}__{script name}
(with two underscores in between), as shown in the figure below:
8.2 Importing Scripts in DataFlux Func
Assume the following script sets and scripts exist:
Then, the import methods are as follows:
Imported Script Location | Import Method |
---|---|
Python script in the same script set | import __{script name} or import {script ID} |
Python script in another script set | import {script ID} |
Import specific content | from {script name} import {object 1}, {object 2}, ... |
For Python scripts in the same script set, it is recommended to use import __{script name}
to ensure the reference path remains correct after cloning the entire script set.
9. Code Comments
Adding comments in scripts is a good habit.
Comments can be used to explain the written code or annotate special treatments, allowing others or yourself to quickly understand the details of the code when reviewing it later.
The level of detail in comments can be chosen reasonably based on the actual project, code, and complexity of the treatment.
Example | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
10. Object-Oriented Programming
In the examples above, all are based on procedural programming, where the code consists entirely of functions.
Python is a multi-paradigm programming language. It can be fully written procedurally, but it can also incorporate object-oriented techniques, making the code more concise and easier to maintain.
For simple treatments, procedural programming can suffice without forcing the use of object-oriented techniques. This is merely a simple demonstration of object-oriented programming in Python.
10.1 Classes and Inheritance
A "class" refers to a collection of objects with common or similar functionalities and data. What a class represents mainly depends on the individual's specific implementation approach, with no strict unified rules.
Classes can have inheritance relationships, where the inherited class is called the "parent class," and the inheriting class is called the "child class." Inheritance relationships are similarly written based on the individual's specific implementation approach, with no strict unified rules.
Generally speaking:
- The parent class writes some common methods possessed by all child classes. Child classes inheriting from the parent class do not need to rewrite these methods and automatically gain all methods from the parent class.
- Child classes can write additional methods, which can only be invoked on child class objects.
- If a method in the parent class is not applicable to the child class, the child class can rewrite the method with the same name to change its behavior when invoked on child class objects.
10.2 Typical Example
Suppose there is a "school personnel management system," with the following main business objects:
Personnel | Description |
---|---|
Teacher | Has a name, access card, conducts teaching activities |
Student | Has a name, access card, conducts learning activities |
It can be seen that different personnel all have access cards, but the activities they conduct differ. Thus, in the specific code implementation, access card-related functions can be handled uniformly, while activity-related functions need separate handling.
Sample code is as follows:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
Output:
Text Output | |
---|---|
1 2 3 4 |
|
11. Error Handling
For uncertain places where problems may occur (such as calling interfaces from other systems), the program may crash if errors occur during execution, such as:
Python | |
---|---|
1 2 3 4 5 6 7 8 |
|
Output:
Text Output | |
---|---|
1 2 3 4 5 6 |
|
At this point, we need to handle potentially problematic code separately.
Since program crashes themselves output useful error messages, it is not mandatory to handle every piece of code for errors. This is just a simple demonstration of Python error handling.
11.1 Error Handling with try-except
Syntax
You can use try...except
to handle potential errors, such as:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Output:
Text Output | |
---|---|
1 2 |
|
11.2 Throwing Errors with raise
Statement
When writing your own code, if encountering non-conforming input parameters, you can also actively throw errors, such as:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Output:
Text Output | |
---|---|
1 2 |
|