Hello, this is ricky. This time, I will show you how to make the code as easy as possible and how to shorten it when coding with python. I hope python beginners can write better code.
num.py
# before
num = 10000000
# after
num = 10_00_000
swap.py
# before
a, b = 2, 3
tmp = b
b = a
a = tep
# after
a, b = 2, 3
a, b = b, a
Since python requires code that is easy for anyone to write, it is basically better not to write it. However, since it can be shortened, it is useful in situations where a short number of lines is required.
variable.py
# before
a = 1
b = 2
# after
a, b = 1, 2
# supplement
#It is possible to use different types
a, b = 3, "b"
#Postscript: You pointed out from the comments.
#Writing after may reduce readability.
#Vector x,Better to use for highly relevant variables such as the y coordinate
if.py
a, b = 1, 2
# before
if a < b:
print("A")
else:
print("B")
# after
print("A") if a < b else print("B")
#Postscript: You pointed out from the comments.
#Can be summarized by print
print("A" if a < b else "B")
# and,You can use or to bring the conditional expression forward
print(a < b and "A" or "B")
Summary When I was coding in python, when I reviewed my code later, I felt that it was not readable, so I wrote this article. Personally, how to write an if statement was very helpful. I hope you find this article useful.
Recommended Posts