Python 程序总是在解释器中运行。解释器是一个“基于控制台的”应用程序,通常使用命令运行。
python3
Python 3.9.8 (main, Nov 10 2021, 03:55:42)
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
当在终端运行python3
后,就进入了交互模式,即 REPL。
>>>
表示开始新的语句...
表示继续上一条语句_
表示最后的返回值>>> print('hello world')
hello world
>>> 37*42
1554
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>>
python 程序以
.py
结尾,可以直接运行。
# hello.py
print('hello world')
python 程序运行的命令是
python hello.py
$ python hello.py
$ python3 hello.py
问题:一天早上,你出去,在芝加哥西尔斯大厦旁的人行道上放了一张美元钞票。从那以后,你每天出去的账单都会翻倍。这堆钞票超过塔的高度需要多长时间?
解决方法:
# sears.py
bill_thickness = 0.11 * 0.001 # Meters (0.11 mm)
sears_height = 442 # Height (meters)
num_bills = 1
day = 1
while num_bills * bill_thickness < sears_height:
print(day, num_bills, num_bills * bill_thickness)
day = day + 1
num_bills = num_bills * 2
print('Number of days', day)
print('Number of bills', num_bills)
print('Final height', num_bills * bill_thickness)
bash % python3 sears.py
1 1 0.00011
2 2 0.00022
3 4 0.00044
4 8 0.00088
5 16 0.00176
6 32 0.00352
...
21 1048576 115.34336
22 2097152 230.68672
Number of days 23
Number of bills 4194304
Final height 461.37344
每行语句以换行符结束,但是不能以分号结束。
a = 3 + 4
b = a * 2
print(b)
注释以#开始,不会被运行。
a = 3 + 4
# This is a comment
b = a * 2
print(b)
python 属于动态类型语言,变量可以随时变化。python 变量名称可以包含字母、数字、下划线,但不能以数字或关键字开头。对大小写敏感。
height = 442 # An integer
height = 442.0 # Floating point
height = 'Really tall' # A string
# 大小写敏感
name = 'Jake'
Name = 'Elwood'
NAME = 'Guido'
while x < 0: # OK
WHILE x < 0: # ERROR
while num_bills * bill_thickness < sears_height:
print(day, num_bills, num_bills * bill_thickness)
day = day + 1
num_bills = num_bills * 2
print('Number of days', day)
缩进是用来表示一组连在一起的语句:
while num_bills * bill_thickness < sears_height:
print(day, num_bills, num_bills * bill_thickness)
day = day + 1
num_bills = num_bills * 2
print('Number of days', day)
if a > b:
print('Computer says no')
elif a == b:
print('Computer says yes')
else:
print('Computer says maybe')
print('Hello world!') # Prints the text 'Hello world!'
#用户输出
name = input('Enter your name:')
print('Your name is', name)