内容正文:
第2章 Python基础
Chap2 Python Basic
Nanjing University
1
Python程序
基本构成与风格
2.1
2
Python
Nanjing University
2.1.1 Python程序基本构成
3
Python
Nanjing University
一个小程序
4
# Filename: prog2-1.py
# For loop on a list # 第1行
num = [1, 2, 3, 4, 5] # 第2行
prog = int(input('please input the value of prog: ')) # 第3行
for number in num: # 第4行
prog = prog * number # 第5行
print('The prog is: ', prog) # 第6行
File
Python
Nanjing University
4
程序基本要素
变量
01
表达式
02
语句
03
Python
Nanjing University
Python输入:input()函数
>>> price = input('input the stock price of Apple: ')
input the stock price of Apple: 109
>>> price
'109'
>>> type(price)
<class 'str'>
>>> price = int(input('input the stock price of Apple: '))
>>> price = eval(input('input the stock price of Apple: '))
Source
6
input()
返回的类型是字符型
Python
Nanjing University
6
Python输出: print函数
Python使用print函数实现输出:
print(变量)
print(字符串)
>>> myString = 'Hello, World!'
>>> print(myString)
Hello, World!
Source
7
Python
Nanjing University
7
2.1.2 Python程序设计风格
8
Python
Nanjing University
Python 风格(一)
>>> # For loop on a list # 第1行
>>> print('The prog is: ', prog) # 第6行
Source
注释
#
9
Python
Nanjing University
9
Python 风格(二)
缩进
03
01
02
增加缩进表示语句块的开始
Python用相同的缩进表示同级别语句块
减少缩进表示语句块的退出
# prog2-1.py
# For loop on a list # 第1行
num = [1, 2, 3, 4, 5]
prog = int(input("please input the value of prog: "))
for number in num:
prog = prog * number
print("The prog is: ", prog)
Source
10
Python
Nanjing University
10
Python 风格(二)
缩进
# prog2-1.py
# For loop on a list # 第1行
num = [1, 2, 3, 4, 5]
prog = int(input("please input the value of prog: "))
for number in num:
prog = prog * number
print('The prog is: ', prog)
Source
11
Python
Nanjing University
11
Python 风格(三)
>>> # long sentence
>>> if (signal == 'red') and\
(car == 'moving'):
car = 'stop'
elif (signal == 'green') and\
(car == 'stop'):
car = 'moving'
Source
>>> #