首页 > 编程 > Python > 正文

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

2020-02-23 05:26:38
字体:
来源:转载
供稿:网友

学习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编程具有严格的缩进格式。

二、函数

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表