Python3 编程第一步

从第一个程序开始,用变量、循环与函数写出斐波那契数列等小例子。

Beginner
Key Points先把「输入 → 处理 → 输出」跑通,再逐步加抽象;`print` 的 `end` 参数可控制换行。

第一个程序

Step one is always making something run and print. print accepts several arguments, separating them with spaces and ending with a newline by default.

Python
print("Hello, Python!")
print("a", "b", "c")
print(1, 2, 3, sep="-")
Output
Hello, Python!
a b c
1-2-3

变量与计算

Variables need no declaration — assignment creates them. Python is dynamically typed, so a name can hold an int and later a string, though changing type usually signals a design problem.

Python
a = 10
b = 3

print(a + b, a - b, a * b)
print(a / b)
print(a // b, a % b, a ** b)

a = "now a string"
print(a, len(a))
Output
13 7 30
3.3333333333333335
3 1 1000
now a string 12

斐波那契数列

The Fibonacci sequence is the classic first exercise: the first two terms are 1 and each later term is the sum of the previous two. Both while and for work; the point is understanding how variables roll forward.

Python
a, b = 0, 1
n = 10
result = []

while len(result) < n:
    result.append(a)
    a, b = b, a + b

print(result)
print(sum(result))
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
88

用函数封装

Wrapping the logic in a function makes it reusable and testable. Default parameters add flexibility, and yield gives a generator version that saves memory.

Python
def fib(n, a=0, b=1):
    out = []
    for _ in range(n):
        out.append(a)
        a, b = b, a + b
    return out

def fib_gen(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

print(fib(8))
print(list(fib_gen(8)))
print(sum(fib_gen(20)))
Output
[0, 1, 1, 2, 3, 5, 8, 13]
[0, 1, 1, 2, 3, 5, 8, 13]
10945

end 关键字

print ends with a newline by default; change end to keep output on one line — handy for progress bars or tables.

Python
for i in range(5):
    print(i, end=' ')
print()

for i in range(3):
    print(i, end='')
print(' done')

print('a', end=' -> ')
print('b')
Output
0 1 2 3 4 
012 done
a -> b

Friends & Partners