Python Basic Syntax Elements
December 20, 2024 · 3 min read · Page View:
Generated by DALL 3
If you have any questions, feel free to comment below. And if you think it's helpful to you, just click on the ads which can support this site. Thanks!
Sometimes you may forget about the basic of Python, so let us take a look at the summary of Python basic summary. The content of this review is as follows: data type
, variable
, control flow
, input & output
, PEP8 format
.
CH1 Basic Syntax Elements #
1 Data Type #
Basic Type: Number, String, Boolean #
Number Type
- int
- float
- complex (a+bj)
String Type
- str: use
" "
or' '
Boolean Type
- bool
y = 2 < 1
y
# False
Composite Type: List, Tuple, Dictionary, Set #
List Type, ordered
a = [1, 2, 3, 4, 5]
a[4]
# 5
Tuple Type, ordered, elements are not modifiable
b = (1, 2, 3, 4, 5)
b[0]
# 1
Dictionary Type, key-value mapping, unordered
student = {201901: "john", 201902: "howe", 201903: "timerring"}
student[201902]
# 'howe'
Set Type, a collection of unique elements, unordered
s = {"john", "howe", "timerring", "john"}
s
# {'john', 'howe', 'timerring'}
2 Variable #
Variable Naming #
What can be used as variable names?
- uppercase letters, lowercase letters, numbers, underscores, and Chinese characters.
- strictly case-sensitive
What is not allowed?
- the first character cannot be a number
- there cannot be spaces in the middle of the variable name
- cannot be the same as the 33 Python reserved words
Variable Name Definition Techniques
- underscore (variable and function name) variable name consists of multiple words: use _ to connect multiple words
age_of_students = [17, 18, 19]
- Camel Case (class name) variable name consists of multiple words: capitalize the first letter of each word
AgeOfStudents
- Constant (e.g. $\pi$, e) variable name all letters are uppercase
MAX_ITERATION = 1000
Variable Assignment #
x, y = 1, 2 # separated by ","
print(x, y)
x, y = y, x
print(x, y)
3 Control Flow #
Loop (for) #
res = 0
for i in [1,2,3,4,5]:
res += i
res
# 15
Loop (while) #
i = 1
res = 0
while i <= 5:
res += i
i += 1
res
# 15
Branch (if) #
if condition:
execute statement
else:
execute statement
4 Input & Output #
Data Input #
External File Import
- from local disk, network, etc. See File, Exception, and Module.
Dynamic Interactive Input
x = input("please input: ")
type(x)
# str, so the addition is string concatenation
Use eval()
to remove the quotes
x = eval(input("please input: "))
type(x)
# int
Data Output #
Print #
Each print() defaults to a newline
print("timerring")
# timerring
print(1)
# 1
Line Break Control end= #
print(123,end=" ")# also can customize the end content
print(456)
# 123 456
Combined Output #
PI = 3.1415926
E = 2.71828
print("PI = ", PI, "E = ", E)
Formatting Output #
# one-to-one correspondence
print("PI = {0},E = {1}".format(PI, E))
# PI = 3.1415926,E = 2.71828
print("PI = {0},E = {0}".format(PI, E))
# PI = 3.1415926,E = 3.1415926
# default order
print("PI = {},E = {}".format(PI, E))
# PI = 3.1415926,E = 2.71828
Decorative Output #
Padding Output
print("{0:_^20}".format(PI)) # 0 is the variable PI, : is the modifier output, _ is the modifier character, ^ is centered, 20 is the output width
# ____3.1415926_____ padding
print("{0:*<30}".format(PI)) # < is left-aligned
# 3.1415926*********************
Thousands Separator
print("{0:,}".format(10000000))
# 10,000,000
Simplified Floating Point Output #
- keep 2 decimal places
print("{0:.2f}".format(PI))
# 3.14
- Output as a percentage
print("{0:.1%}".format(0.818727))
# 81.9%
- Scientific Notation Output
print("{0:.2e}".format(0.818727))
# 8.19e-01
Integer Base Conversion Output
- Decimal to Binary, Unicode, Decimal, Octal, Hexadecimal
"Binary {0:b}, Unicode {0:c}, Decimal {0:d}, Octal {0:o}, Hexadecimal {0:x}".format(450)
# Binary 11100010, Unicode \u1b6, Decimal 450, Octal 702, Hexadecimal 1c2
Summary #
Formatting Output:
"character{0:modifier}character{1:modifier}character".format(v0, v1)
Modifier Output: must be strictly in order.
5 Program Format (PEP8 Format) #
Line Maximum Length #
All lines are limited to a maximum of 79 characters
Indentation #
- Use indentation to represent the logical relationship between statements, indentation: 4 characters
Use Spaces #
- Add a space on both sides of the binary operator
- Add spaces around different priority operators
x = x*2 - 1
c = (a+b) * (a-b)
- Use spaces after commas
Avoid Using Spaces #
- Do not add spaces around = when specifying keyword arguments or default parameter values
def fun(n=1, m=2):
print(n, m)
Comments #
Single-line comment
# comment content
Multi-line comment
"""comment content, can be split into multiple lines"""
If you find this blog useful and want to support my blog, need my skill for something, or have a coffee chat with me, feel free to: