The operation methods and properties of bitwise operators in Python
Original code, inverse code, complement code
First, you need to understand the three different expressions of binary codes, original code, inverse code, and complement code.
The prerequisite knowledge is: Sign bit The highest bit is the sign bit, 0 represents a positive number, and 1 represents a negative number. The sign bit also participates in bitwise operations.
The original code is the binary form of a certain number
The complement code is divided into two situations: positive number and negative number. The original code of the positive number is the complement code. The one’s complement code of a negative number means that the sign bit remains unchanged and the other digits are inverted.
The complement code adds one to the complement code.
like:
Original code: 00 00 10 11 -> 11
Negative code: 01 11 01 00 -> -11
Complement code: 01 11 01 01 -> -11
Bitwise operations
One of the ways to represent a collection in python
According to binary calculation, ~1 = 0, ~0 = 1
~Negative operation
~num inverts all complements, including the sign bit
00 00 01 01 -> 5
On request: ~00 00 01 01
Step 1: Find the complement code
11 11 10 11
Step 2: Negate everything
00 00 01 00 -> 4
& amp;Bit-and operation
1 & 1 = 1
0 & 1 = 0
1 & 0 = 0
0 & 0 = 0
|Bitwise OR operation
1 | 1 = 1
0 | 1 = 1
1 | 0 = 1
0 | 0 = 0
^XOR operation
0^0 = 0
0^1=1
1^0=1
0^0 = 0
Properties of XOR operation: satisfy commutative law and associative law
<
num << r
Shift the binary number of num to the left by r bits
00 00 10 11 -> 11 Shift one position to the left
00 01 01 10 -> 22
>>Right shift operation
num >> r
Shift the binary number of num to the right by r bits
00 00 10 11 -> 11 Shift 1 bit to the right
00 00 01 01 -> 2
if statement
if expression:
sentence
The statement in the code will be executed only if the expression after if is true, otherwise the code following it will be executed.
if else statement
Note that in python if else statements are not represented by brackets, but corresponding indentations are used to mark code block boundaries.
Therefore, which if else corresponds to, it is the corresponding condition of that if.
hi = 6
if hi > 2:
if hi > 7:
print('Great! Great!')
else:
print('cut~')
# no output
# This example comes from Alibaba Cloud Tianchi
if-elif-if
This structural statement is used when there are multiple conditions. elif is else if
temp = input('Please enter your score:')
source = int(temp)
if 100 >= source >= 90:
print('A')
elif 90 > source >= 80:
print('B')
elif 80 > source >= 60:
print('C')
elif 60 > source >= 0:
print('D')
else:
print('Input error!')
assert keyword
assert is “assertion”. If the condition behind assert is false, the program crashes and throws an AssertionError exception.
#Create a sequence
my_list = ['lsgogroup']
#Pop the first stack
my_list.pop(0)
#Assert that the length of my_list is greater than 0, but the length of my_list is 0 at this time, so an error will be thrown.
assert len(my_list) > 0
#AssertionError
Assert can be used in unit tests to place checkpoints in the program. Only if the condition is True can it continue to work.
assert 3 > 7
#AssertionError
while loop
The most basic form of a while statement consists of a Boolean expression at the top and one or more indented statements that belong to the while block.
while Boolean expression:
code block
The code in the while statement will continue to execute until the Boolean expression evaluates to false
string = 'abcd'
while string:
print(string)
string = string[1:]
The value in #string is 0 and the loop terminates
while else loop
When the while loop is executed normally, the else output is executed. If a statement that jumps out of the loop, such as break, is executed in the while loop, the contents of the else code block will not be executed.
count = 0
while count < 5:
print("%d is less than 5" % count)
count = 6
break
else:
print("%d is not less than 5" % count)
# 0 is less than 5
#This example comes from Alibaba Cloud Tianchi
for-else loop
When the for loop is executed normally, the else output is executed. If a statement that jumps out of the loop, such as break, is executed in the for loop, the content of the else code block will not be executed, just like the while – else statement.
for num in range(10, 20): # Iterate over numbers between 10 and 20
for i in range(2, num): # Iterate based on factors
if num % i == 0: # Determine the first factor
j = num / i # Calculate the second factor
print('%d equals %d * %d' % (num, i, j))
break # Jump out of the current loop
else: # The else part of the loop
print(num, 'is a prime number')
# 10 equals 2 * 5
# 11 is a prime number
# 12 is equal to 2 * 6
# 13 is a prime number
# 14 is equal to 2 * 7
# 15 is equal to 3 * 5
# 16 is equal to 2 * 8
# 17 is a prime number
# 18 is equal to 2 * 9
# 19 is a prime number
range() function
range([start,] stop[, step=1])
The function of the range BIF is to generate a sequence of numbers starting from the value of the start parameter and ending with the value of the stop parameter. This sequence contains the value of start but does not include the value of stop (closed on the left and open on the right).
for i in range(1, 10, 2):
print(i)
# 1
#3
#5
#7
# 9
enumerate() function
enumerate(sequence, [start=0])
sequence: a sequence, iterator, or other object that supports iteration.
start: the starting position of the subscript.
Returns an enumerate object
for i, language in enumerate(languages, 2):
print(i, 'I love', language)
print('Done!')
#2 I love Python
#3 I love R
#4 I love Matlab
#5 I love C++
#Done!
break statement
The break statement can break out of the loop at the current level.
continue statement
continue terminates this cycle and starts the next cycle.
pass statement
The pass statement means “do nothing”. If you do not write any statement where a statement is required, the interpreter will prompt an error, and the pass statement is used to solve these problems.
pass is an empty statement, which does not perform any operation and only serves as a placeholder. Its function is to maintain the integrity of the program structure. Although the pass statement does not do anything, if you are not sure what kind of code you want to put in a location, you can place a pass statement first so that the code can run normally.
def a_func():
pass
Derivation
List comprehension
a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
print(a)
# [(0, 2)]
Tuple derivation
a = (x for x in range(10))
print(a)
# <generator object <genexpr> at 0x0000025BE511CC48>
print(tuple(a))
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Dictionary derivation
b = {<!-- -->i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}
Set derivation
c = {<!-- -->i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)
# {1, 2, 3, 4, 5, 6}
Others
next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.
e = (i for i in range(10))
print(e)
# <generator object <genexpr> at 0x0000007A0B8D01B0>
print(next(e)) # 0
print(next(e)) # 1
print(next(e)) # 2
for each in e:
print(each, end=' ')
# 2 3 4 5 6 7 8 9
Exception classification
try-expect statement
try:
examination range
except Exception[as reason]:
Handling code after exception occurs
A try statement may contain multiple except clauses to handle different specific exceptions. At most one branch will be executed.
try:
int("abc")
s = 1 + '1'
f = open('test.txt')
print(f.read())
f.close()
except OSError as error:
print('Error opening file\
The reason is:' + str(error))
except TypeError as error:
print('Type error\
The reason is:' + str(error))
except ValueError as error:
print('Value error\
The reason is:' + str(error))
# Numerical error
#The reason is: invalid literal for int() with base 10: 'abc'
An except clause can handle multiple exceptions at the same time, and these exceptions will be placed in parentheses to form a tuple.
try:
s = 1 + '1'
int("abc")
f = open('test.txt')
print(f.read())
f.close()
except (OSError, TypeError, ValueError) as error:
print('An error occurred!\
The reason is:' + str(error))
# error!
# The reason is: unsupported operand type(s) for + : 'int' and 'str'
try-except-finally statement
try: detection scope except Exception[as reason]: handling code after an exception occurs finally: code that will be executed anyway
Regardless of whether an exception occurs in the try clause, the finally clause will be executed.
def divide(x, y):
try:
result = x/y
print("result is", result)
except ZeroDivisionError:
print("division by zero!")
finally:
print("executing finally clause")
divide(2, 1)
# result is 2.0
# executing finally clause
divide(2, 0)
# division by zero!
# executing finally clause
divide("2", "1")
# executing finally clause
# TypeError: unsupported operand type(s) for /: 'str' and 'str'
try-expect-else statement
If no exception occurs when the try clause is executed, Python will execute the statement after the else statement.
try:
examination range
except:
Handling code after exception occurs
else:
If there is no exception, execute this code
Using except without any exception type is not a good way. We cannot identify the specific exception information through the program because it catches all exceptions.
try:
fh = open("testfile.txt", "w")
fh.write("This is a test file, used to test exceptions!!")
exceptIOError:
print("Error: File not found or failed to read file")
else:
print("Content written to file successfully")
fh.close()
#The content is written to the file successfully
raise statement
raise statement
Python uses the raise statement to throw a specified exception.
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
# An exception flew by!
num << r
Shift the binary number of num to the left by r bits
00 00 10 11 -> 11 Shift one position to the left
00 01 01 10 -> 22
>>Right shift operation
num >> r
Shift the binary number of num to the right by r bits
00 00 10 11 -> 11 Shift 1 bit to the right
00 00 01 01 -> 2
if statement
if expression:
sentence
The statement in the code will be executed only if the expression after if is true, otherwise the code following it will be executed.
if else statement
Note that in python if else statements are not represented by brackets, but corresponding indentations are used to mark code block boundaries.
Therefore, which if else corresponds to, it is the corresponding condition of that if.
hi = 6 if hi > 2: if hi > 7: print('Great! Great!') else: print('cut~') # no output # This example comes from Alibaba Cloud Tianchi
if-elif-if
This structural statement is used when there are multiple conditions. elif is else if
temp = input('Please enter your score:') source = int(temp) if 100 >= source >= 90: print('A') elif 90 > source >= 80: print('B') elif 80 > source >= 60: print('C') elif 60 > source >= 0: print('D') else: print('Input error!')
assert keyword
assert is “assertion”. If the condition behind assert is false, the program crashes and throws an AssertionError exception.
#Create a sequence my_list = ['lsgogroup'] #Pop the first stack my_list.pop(0) #Assert that the length of my_list is greater than 0, but the length of my_list is 0 at this time, so an error will be thrown. assert len(my_list) > 0 #AssertionError
Assert can be used in unit tests to place checkpoints in the program. Only if the condition is True can it continue to work.
assert 3 > 7 #AssertionError
while loop
The most basic form of a while statement consists of a Boolean expression at the top and one or more indented statements that belong to the while block.
while Boolean expression:
code block
The code in the while statement will continue to execute until the Boolean expression evaluates to false
string = 'abcd' while string: print(string) string = string[1:] The value in #string is 0 and the loop terminates
while else loop
When the while loop is executed normally, the else output is executed. If a statement that jumps out of the loop, such as break, is executed in the while loop, the contents of the else code block will not be executed.
count = 0 while count < 5: print("%d is less than 5" % count) count = 6 break else: print("%d is not less than 5" % count) # 0 is less than 5 #This example comes from Alibaba Cloud Tianchi
for-else loop
When the for loop is executed normally, the else output is executed. If a statement that jumps out of the loop, such as break, is executed in the for loop, the content of the else code block will not be executed, just like the while – else statement.
for num in range(10, 20): # Iterate over numbers between 10 and 20 for i in range(2, num): # Iterate based on factors if num % i == 0: # Determine the first factor j = num / i # Calculate the second factor print('%d equals %d * %d' % (num, i, j)) break # Jump out of the current loop else: # The else part of the loop print(num, 'is a prime number') # 10 equals 2 * 5 # 11 is a prime number # 12 is equal to 2 * 6 # 13 is a prime number # 14 is equal to 2 * 7 # 15 is equal to 3 * 5 # 16 is equal to 2 * 8 # 17 is a prime number # 18 is equal to 2 * 9 # 19 is a prime number
range() function
range([start,] stop[, step=1])
The function of the range BIF is to generate a sequence of numbers starting from the value of the start parameter and ending with the value of the stop parameter. This sequence contains the value of start but does not include the value of stop (closed on the left and open on the right).
for i in range(1, 10, 2): print(i) # 1 #3 #5 #7 # 9
enumerate() function
enumerate(sequence, [start=0])
sequence: a sequence, iterator, or other object that supports iteration.
start: the starting position of the subscript.
Returns an enumerate object
for i, language in enumerate(languages, 2): print(i, 'I love', language) print('Done!') #2 I love Python #3 I love R #4 I love Matlab #5 I love C++ #Done!
break statement
The break statement can break out of the loop at the current level.
continue statement
continue terminates this cycle and starts the next cycle.
pass statement
The pass statement means “do nothing”. If you do not write any statement where a statement is required, the interpreter will prompt an error, and the pass statement is used to solve these problems.
pass is an empty statement, which does not perform any operation and only serves as a placeholder. Its function is to maintain the integrity of the program structure. Although the pass statement does not do anything, if you are not sure what kind of code you want to put in a location, you can place a pass statement first so that the code can run normally.
def a_func(): pass
Derivation
List comprehension
a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1] print(a) # [(0, 2)]
Tuple derivation
a = (x for x in range(10)) print(a) # <generator object <genexpr> at 0x0000025BE511CC48> print(tuple(a)) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Dictionary derivation
b = {<!-- -->i: i % 2 == 0 for i in range(10) if i % 3 == 0} print(b) # {0: True, 3: False, 6: True, 9: False}
Set derivation
c = {<!-- -->i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]} print(c) # {1, 2, 3, 4, 5, 6}
Others
next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.
e = (i for i in range(10)) print(e) # <generator object <genexpr> at 0x0000007A0B8D01B0> print(next(e)) # 0 print(next(e)) # 1 print(next(e)) # 2 for each in e: print(each, end=' ') # 2 3 4 5 6 7 8 9
Exception classification
try-expect statement
try:
examination range
except Exception[as reason]:
Handling code after exception occurs
A try statement may contain multiple except clauses to handle different specific exceptions. At most one branch will be executed.
try: int("abc") s = 1 + '1' f = open('test.txt') print(f.read()) f.close() except OSError as error: print('Error opening file\ The reason is:' + str(error)) except TypeError as error: print('Type error\ The reason is:' + str(error)) except ValueError as error: print('Value error\ The reason is:' + str(error)) # Numerical error #The reason is: invalid literal for int() with base 10: 'abc'
An except clause can handle multiple exceptions at the same time, and these exceptions will be placed in parentheses to form a tuple.
try: s = 1 + '1' int("abc") f = open('test.txt') print(f.read()) f.close() except (OSError, TypeError, ValueError) as error: print('An error occurred!\ The reason is:' + str(error)) # error! # The reason is: unsupported operand type(s) for + : 'int' and 'str'
try-except-finally statement
try: detection scope except Exception[as reason]: handling code after an exception occurs finally: code that will be executed anyway
Regardless of whether an exception occurs in the try clause, the finally clause will be executed.
def divide(x, y): try: result = x/y print("result is", result) except ZeroDivisionError: print("division by zero!") finally: print("executing finally clause") divide(2, 1) # result is 2.0 # executing finally clause divide(2, 0) # division by zero! # executing finally clause divide("2", "1") # executing finally clause # TypeError: unsupported operand type(s) for /: 'str' and 'str'
try-expect-else statement
If no exception occurs when the try clause is executed, Python will execute the statement after the else statement.
try:
examination range
except:
Handling code after exception occurs
else:
If there is no exception, execute this code
Using except without any exception type is not a good way. We cannot identify the specific exception information through the program because it catches all exceptions.
try: fh = open("testfile.txt", "w") fh.write("This is a test file, used to test exceptions!!") exceptIOError: print("Error: File not found or failed to read file") else: print("Content written to file successfully") fh.close() #The content is written to the file successfully
raise statement
raise statement
Python uses the raise statement to throw a specified exception.
try: raise NameError('HiThere') except NameError: print('An exception flew by!') # An exception flew by!