Python3 Programming First Step
In the previous tutorial, we have learned some basic syntax of Python3. Next, let's try some examples.
Print a string:
Example
The output result is:
Hello, world!
Output variable value:
Example
print('The value of i is:', i)
The output result is:
i 的值为: 65536
Define variables and perform simple mathematical operations
Example
y = 2
z = x + y
print(z)
The output result is:
5
Define a list and print out its elements:
Example
print(my_list[0]) # Output "google"
print(my_list[1]) # Output "example"
print(my_list[2]) # Output "taobao"
The output result is:
google example taobao
Use a for loop to print numbers 0 to 4:
Example
print(i)
The output result is:
0 1 2 3 4
Output different results based on conditions:
Example
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
The output result is:
x 小于或等于 10
Next, let's try to write a Fibonacci sequence.
The Fibonacci sequence is a classic mathematical problem, where each number is the sum of the previous two numbers.
Example (Python 3.0+)
Among them, the codea, b = b, a+bis calculated by first evaluating the right-hand expression, then assigning to the left side simultaneously, equivalent to:
n=b m=a+b a=n b=m
Execute the above program, the output result is:
1 1 2 3 5 8
This example introduces several new features.
The first line contains a compound assignment: variables a and b simultaneously get new values 0 and 1. The last line uses the same method again. You can see that the right-hand expression is executed before the assignment changes. The execution order of the right-hand expression is from left to right.
You can also use a for loop to achieve it:
Example
a, b = 0, 1
for i in range(n):
print(b)
a, b = b, a + b
end keyword
The keyword end can be used to output results to the same line, or to add different characters at the end of the output, as shown in the example below:
Example (Python 3.0+)
Execute the above program, the output result is:
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,Other Extensions