学习Python,基本语法不是特别难,有了C的基本知识,理解比较容易。本文的主要内容是Python基础语法,学完后,能熟练使用就好。(开发环境依然是Python2.7,简单使用)
一,基本知识
1,不需要预先定义数据类型(此说法值得商榷,姑且这么说吧),这是与其他语言的最大不同(如C,C++,C#,Delphi等)
>>> x=12
>>> y=13
>>> z=x+y
>>> print z
25
注意:尽管变量不需要预先定义,但是要使用的时候,必须赋值,否则报错:
>>> le
Traceback (most recent call last):
File "
le
NameError: name 'le' is not defined
2,查看变量的类型函数type():
1 >>> type(x)
2
3,查看变量的内存地址函数id():
>>> x=12
>>> y=13
>>> z=x+y
>>> m=12
>>> print 'id(x)=',id(x)
id(x)= 30687684
>>> print 'id(m)=',id(m)
id(m)= 30687684
>>> print 'id(z)=',id(z)
id(z)= 30687528
>>> x=1.30
>>> print 'id(x)=',id(x)
id(x)= 43407128
从上述结果可以发现:变量的指向变,地址不变,换句话说,整数12的地址值始终不变,变化的是变量的指向(如x的地址变化);
4,输出函数print():
>>> x='day'
>>> y=13.4
>>> print x,type(x)
day
>>> print y,type(y)
13.4
逗号运算符(,):可以实现连接字符串和数字型数据。
>>> print 'x=',12
x= 12
格式化控制符:%f浮点数;%s字符串;%d双精度浮点数(这和C的输出是一致的)。
>>> x=12
>>> y=13.0004
>>> z='Python'
>>> print "output %d %f %s"%(x,y,s)
output 12 13.000400 Python
5,输入函数raw_input():
>>> raw_input("input an int:")
input an int:12
'12'
注意:raw_input()输入的均是字符型。
6,查看帮助函数help():
>>> help(id)
Help on built-in function id in module __builtin__:
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
注意:Python的注释,#:仅支持单行注释;另外,Python编程具有严格的缩进格式。
二、函数
1,函数定义及其调用:
#define function:add (函数说明)
def add(x,y): #函数头部,注意冒号,形参x,y
z=x+y #函数体
return z #返回值
#define main function
def main():
a=12
b=13
c=add(a,b) #函数调用,实参a,b
print c
main() #无参函数调用
print 'End1!'
注意:这部分与C的存在的异同在于:
1,形参与实参的用法,无参函数,有参函数,默认参数等规则一致。
如def add(x,y=2),调用可以是add(3)也可以是add(3,4),add(y=34,x)
2,C的形参需要指定数据类型,而Python不需要。
3,Python的返回值允许有多个。如:
def test(n1,n2):
print n1,
print n2
n=n1+n2
m=n1*n2
p=n1-n2
e=n1**n2
return n,m,p,e
print 'Entry programme1'
sum,multi,plus,powl=test(2,10) #这个是C语言所没有的赋值方式
print 'sum=',sum
print 'multi=',multi
print 'plus=',plus
print 'powl=',powl
re=test(2,10)
print re #数据类型为:'tuple'
print re[0],re[1],re[2],re[3]
print 'End1!\n'
运行结果:
Entry programme
2 10
sum= 12
multi= 20
plus= -8
powl= 1024
2 10
(12, 20, -8, 1024)
12 20 -8 1024
End!
2,局部变量:
def f1():
x=12 #局部变量
print x
def f2():
y=13 #局部变量
print y
def f3():
print x #错误:没有定义变量x,这与“不需要预先定义数据类型”不矛盾
print y
def main():
f1()
f2()
#f3()#变量报错
main()
print 'End2!'
3,修改全局变量的值:
def modifyGlobal():
global x #全局变量定义
print 'write x =-1'
x=-1
def main():
# printLocalx()
# printLocaly()
# readGlobal()
modifyGlobal()
x=200
#y=100
print 'before modified global x=',
print x
main()
print 'after modified global x=',
print x
运行结果:
>>>
before modified global x= 200
write x =-1
after modified global x= -1
三、表达式与分支语句
1,表达式:
是由数字,运算符,数字分组符号括号,自由变量和约束变量等以能求得数值的有意义排列方法所得的组合。表示通常有操作数和操作符两部分组成。
分类:算术表达式;关系表达式,逻辑表达式(and/or/not)
2,if分支语句:
1)形式一:(if
>>> sex="male"
>>> if sex=='male':
print 'Man!'
#此处有两次回车键
Man!
>>>
2)形式二:(if
sex=raw_input('Please input your sex:')
if sex=='m' or sex=='male':
print 'Man!'
else:
print 'Woman!'
运行结果:
>>>
Please input your sex:male
Man!
3)形式三:(if
count=int(raw_input('Please input your score:'))
if count>=90:
print'优秀!'
elif count>=80:
print '优良!'
elif count>=70:
print '合格!'
elif count>=60:
print '及格!'
else:
print '不及格!'
运行结果:
>>>
Please input your score:90
优秀!
注意:Python没有switch语句。
四、循环语句:
背景:在程序设计的时候,经常会遇到一些语句被不断的重复执行,这样的代码极长又低效,很不直观,那么应该考虑用循环体来实现。
1,while语句:与C在表达上有区别,c有while与do……while形式;Python下:while与while……else……形式
1)while形式下:
i=1
while i print 'Welcome you!'
i=i+1
2)while……else……形式下:
i=1
while i print 'Welcome you!'
i=i+1
else:
print "While over!" #循环正常结束
注意:如果while非正常状态结束(即不按循环条件结束),则else语句不执行。如下:
i=1
while i print 'Welcome you!'
i=i+1
if i==2:
print 'While……'
break
else:
print "While over!"
运行结果:
1 >>>
2 Welcome you!
3 While……
补充:
continue语句:在while循环体中出现时,本次循环continue之下的语句不被执行,直接进入下一次循环。
i=1
while i if i==2 or i==4:
print 'While……continue'
i=i+1
continue
print 'Welcome you!'
i=i+1
else:
print "While over!"
运行结果:
>>>
Welcome you!
While……continue
Welcome you!
While……continue
Welcome you!
While over!
五,小结:
本文介绍了Python的变量,输入输出函数,表达式,基本语句(分支和循环)等知识的相关使用,通过练习,应该对Python有一个初步的认识。

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools
