2. Python Basics
English translation
Contents
2.1 Comments
- Single-line comment: A statement beginning with
#is a comment.
# helloworld
print('hello world')hello world
- Comment block: A block enclosed in
'''(three single quotes) or"""(three double quotes) acts as a comment.
'''
Function name: helloworld()
This function prints 'hello world'
'''
def helloworld():
print('hello world')
helloworld()hello world
2.2 Indentation and code blocks
Indentation plays a very important role in Python, so use it carefully.
Incorrect indentation causes an error.
Indentation ErrorIndentation is determined by the number of spaces or tabs; using tabs is recommended for readability and consistency.
Role 1: Indicates the scope of a loop or control statement.
print('start')
for i in range(10):
if i>5:
print('i = %d > 5' % i)
# The if block ends here.
elif i<5:
print('i = %d < 5' % i)
else:
print('i = %d = 5' % i)
# The for block ends here.
print('end')start i = 0 < 5 i = 1 < 5 i = 2 < 5 i = 3 < 5 i = 4 < 5 i = 5 = 5 i = 6 > 5 i = 7 > 5 i = 8 > 5 i = 9 > 5 end
- Role 2: Indicates the scope of a function or class definition.
def function1():
print(' function start')
print(' function end')
# The function body ends here.
print('script start')
function1()
print('script end')script start function start function end script end
2.3 Input and output
- Input
input()- This function accepts keyboard input through the screen and stores it in a variable.
a = input()
print(a)10 10
- Output
print()- This function displays the desired content on the screen.
- Write the expression to display between
' '. - For content that varies with a variable, use
%d(integer),%f(real number), or%s(string), according to its type.%.1f(display a real number to one decimal place)
- Put
%to the right of' ', then list the variables to substitute into the expression in order inside( ).
i = 4
j = 4.5
k = 'abc'
print('i=%d j=%.1f k=%s' % (i,j,k))i=4 j=4.5 k=abc