Python学习笔记(二)基础语法
学习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有一个初步的认识。

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
