python基础一,,1.输出:>>> p


1.输出:

>>> print (‘Hello World!‘)


2.输入:

>>> user = input(‘Enter login name: ‘)
Enter login name: oyzhx
>>> user
‘oyzhx‘

3注释:

#从 # 开始,直到一行结束的内容都是注释。


4.运算符:+ - * / // % ** < <= > >= == != <>(不等于) and or not

"//":用作浮点除法(对结果进行四舍五入)

"**":乘方

5.数字 int,long,bool, float,complex(复数)

bool:True,False


6.字符串

加号( + )用于字符串连接运算,星号(* )则用于字符串重复

>>> tmpStr =‘hello‘
>>> tmpStr2= ‘world‘

>>> tmpStr + tmpStr2
‘helloworld‘
>>> tmpStr*3
‘hellohellohello‘


7.列表和元组

列表:列表元素用中括号( [ ])包裹,元素的个数及元素的值可以改变。(aList=[1,2,3,‘haha‘])

元组:元组元素用小括号(( ))包裹,不可以更改 (aTuple = (1,2,3,‘try‘))


8.字典

由键-值(key-value)对构成,值可以是任意类型的Python 对象,字典元素用大括号({ })包裹。

>>> aDict ={‘name‘:‘oy‘}
>>> aDict[‘school‘] =‘csu‘
>>> aDict
{‘name‘: ‘oy‘, ‘school‘: ‘csu‘}


9.代码块及缩进对齐

代码块通过缩进对齐表达代码逻辑而不是使用大括号,因为没有了额外的字符,程序的可读性更高。而且缩进完全能够清楚地表达一个语句属于哪个代码块。

if语句

if expression1:
if_suite
elif expression2:
elif_suite
else:
else_suite


while 循环:

while expression:
while_suite


for循环:

Python 中的for 循环与传统的for 循环(计数器循环)不太一样, 它更象shell 脚本里的foreach 迭代。Python 中的for 接受可迭代对象(例如序列或迭代器)作为其参数,每次迭代其中一个元素。

>>> for item in[‘name‘,‘age‘,‘school‘]:
print (item)


name
age
school


enumerate():

>>> foo = ‘abc‘
>>> for i,ch in enumerate(foo):
print (ch,‘%d‘ %i)

a 0
b 1
c 2


10.列表解析:

可以在一行中使用一个for 循环将所有值放到一个列表
当中:
>>> squared = [x ** 2 for x in range(4)]
>>> for i in squared:
... print i
0
1
4
9


11.文件和内建函数open() 、file()

handle = open(file_name, access_mode = ‘r‘)


12.错误和异常try-except

try:
filename = input(‘Enter file name: ‘)
fobj = open(filename, ‘r‘)
for eachLine in fobj:
print (eachLine, fobj.close())
except IOError, e:
print (‘file open error:‘, e)


13.函数:

def function_name([arguments]):
"optional documentation string"
function_suite

python基础一

评论关闭