First Steps in Python3 Programming
In the previous tutorials, we have learned some basic syntax of Python3. Now, let's try to write a Fibonacci sequence.
Example (Python 3.0+)
#!/usr/bin/python3
# Fibonacci series: Fibonacci sequence
# The sum of two elements defines the next number
a, b = 0, 1
while b < 10:
print(b)
a, b = b, a+b
The code a, b = b, a+b
calculates the right-hand side expressions first, then assigns them to the left-hand side simultaneously, which is equivalent to:
n=b
m=a+b
a=n
b=m
Executing the above program, the output 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, showing that the expressions on the right are evaluated before any assignments take place. The execution order of the right-hand side expressions is from left to right.
Output variable value:
>>> i = 256*256
>>> print('i 的值为:', i)
i 的值为: 65536
The end Keyword
The keyword end
can be used to output results on the same line or to add different characters at the end of the output, as shown in the following example:
Example (Python 3.0+)
#!/usr/bin/python3
# Fibonacci series: Fibonacci sequence
# The sum of two elements defines the next number
a, b = 0, 1
while b < 1000:
print(b, end=',')
a, b = b, a+b
Executing the above program, the output is:
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,