Python学习笔记(二)基础语法


Posted in Python onJune 06, 2014

学习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 "<pyshell#8>", line 1, in <module>
     le
 NameError: name 'le' is not defined

2,查看变量的类型函数type():

1 >>> type(x)
2 <type 'int'>

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 <type 'str'>
 >>> print y,type(y)
 13.4 <type 'float'>

逗号运算符(,):可以实现连接字符串和数字型数据。

 >>> 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 <condition>:)

 >>> sex="male"
 >>> if sex=='male':
  print 'Man!'
 #此处有两次回车键
 Man!
 >>>

2)形式二:(if <condition>: else (if <condition>:))

 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 <condition>: elif <condition>: else ))(这是Python有而C没有的形式)

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<5:
     print 'Welcome you!'
     i=i+1

2)while……else……形式下:

 i=1
 while i<5:
     print 'Welcome you!'
     i=i+1
 else:
     print "While over!"  #循环正常结束

注意:如果while非正常状态结束(即不按循环条件结束),则else语句不执行。如下:

i=1
while i<5:
    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<=5:
    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有一个初步的认识。

Python 相关文章推荐
centos 下面安装python2.7 +pip +mysqld
Nov 18 Python
python获取mp3文件信息的方法
Jun 15 Python
分析Python中设计模式之Decorator装饰器模式的要点
Mar 02 Python
30秒轻松实现TensorFlow物体检测
Mar 14 Python
python 实现将txt文件多行合并为一行并将中间的空格去掉方法
Dec 20 Python
对Python中画图时候的线类型详解
Jul 07 Python
一行Python代码过滤标点符号等特殊字符
Aug 12 Python
PyQt5实现登录页面
May 30 Python
python中的错误如何查看
Jul 08 Python
Restful_framework视图组件代码实例解析
Nov 17 Python
Django实现简单的分页功能
Feb 22 Python
python 进阶学习之python装饰器小结
Sep 04 Python
pycharm 使用心得(九)解决No Python interpreter selected的问题
Jun 06 #Python
pycharm 使用心得(八)如何调用另一文件中的函数
Jun 06 #Python
pycharm 使用心得(七)一些实用功能介绍
Jun 06 #Python
pycharm 使用心得(六)进行简单的数据库管理
Jun 06 #Python
pycharm 使用心得(五)断点调试
Jun 06 #Python
pycharm 使用心得(四)显示行号
Jun 05 #Python
pycharm 使用心得(三)Hello world!
Jun 05 #Python
You might like
Terran魔法科技
2020/03/14 星际争霸
微盾PHP脚本加密专家php解密算法
2020/09/13 PHP
用php实现选择排序的解决方法
2013/05/04 PHP
深入php函数file_get_contents超时处理的方法详解
2013/06/03 PHP
支持生僻字且自动识别utf-8编码的php汉字转拼音类
2014/06/27 PHP
PHP实现将上传图片自动缩放到指定分辨率,并保持清晰度封装类示例
2019/06/17 PHP
firefox火狐浏览器与与ie兼容的2个问题总结
2010/07/20 Javascript
Javascript进制转换实例分析
2015/05/14 Javascript
基于jQuery日历插件制作日历
2016/03/11 Javascript
微信小程序 MINA文件结构
2016/10/17 Javascript
利用js获取下拉框中所选的值
2016/12/01 Javascript
Chrome浏览器的alert弹窗禁止再次弹出后恢复的方法
2016/12/30 Javascript
vue2.0 下拉框默认标题设置方法
2018/08/22 Javascript
在AngularJs中设置请求头信息(headers)的方法及不同方法的比较
2018/09/04 Javascript
详解如何写出一个利于扩展的vue路由配置
2019/05/16 Javascript
一篇文章弄懂javascript中的执行栈与执行上下文
2019/08/09 Javascript
javaScript把其它类型转换为Number类型
2019/10/13 Javascript
[01:14]2014DOTA2展望TI 剑指西雅图newbee战队专访
2014/06/30 DOTA
python获取各操作系统硬件信息的方法
2015/06/03 Python
Python之自动获取公网IP的实例讲解
2017/10/01 Python
django开发post接口简单案例,获取参数值的方法
2018/12/11 Python
只需7行Python代码玩转微信自动聊天
2019/01/27 Python
Python图像处理二值化方法实例汇总
2020/07/24 Python
python与c语言的语法有哪些不一样的
2020/09/13 Python
利用Bootstrap实现漂亮简洁的CSS3价格表实例源码
2017/03/02 HTML / CSS
IE10 Error.stack 让脚本调试更加方便快捷
2013/04/22 HTML / CSS
澳大利亚Mocha官方网站:包、钱包、珠宝和配饰
2019/07/18 全球购物
幼儿园园长岗位职责
2013/11/26 职场文书
2014年社区学雷锋活动总结
2014/03/09 职场文书
《黄山奇石》教学反思
2014/04/19 职场文书
企业口号大全
2014/06/12 职场文书
计算机科学技术自荐信
2014/06/12 职场文书
自我推荐信格式模板
2015/03/24 职场文书
小学六年级毕业感言
2015/07/30 职场文书
诚信教育主题班会
2015/08/13 职场文书
Flask使用SQLAlchemy实现持久化数据
2021/07/16 Python