Magical Operators in Python

1 Problem

In learning Python, we often need to use some operators to make the code logic valid or to run successfully. Different operators have different functions, and we need to distinguish and use them correctly.

2 Methods

Through online research and summarizing daily learning, the following is a summary of some operators that have been encountered:

(1) Relational Operators

== (equal) != (not equal) <> (not equal) > (greater than) < (less than) >= (greater than or equal to) <= (less than or equal to) It is worth mentioning that, unlike conventional usage, in Python “=” is not equal but an assignment operator, and should be read from right to left.

(2) String Operators

Code Listing 1

String Concatenation (+) Print(‘a’ + ‘b’) # Output: ab
Repeat String (*) Print(‘a’ * 3) # Output: aaa
Index String ([]) a = ‘hello’ print(a[1]) # Output: e
Slice String ([:]) Print(a[1:4]) # Output: ell
Format String (%) Print(‘hello%s%s’ % (‘wor’, ‘ld’)) # Output: hello world

3 Conclusion

To avoid improper use of operators, we can summarize and practice more to minimize mistakes. Although this article summarizes some commonly used operators, it is only a part of the whole. In future learning, we should summarize in a timely manner and practice more.

Leave a Comment