python 基础教程之语法篇章——一小时入门python__对比python与C语言的语法异同

概述,本文档中所有的程序内容都在linux下的Vim下面进行编辑,然后在解释器中运行
#!/usr/bin/python
#the following is code
…...

#the end


1.Hello world!——如何print输出


Print “hello world”
格式化输出:
>>> print "%s is number %d" % ("python",100)
python is number 100
重定向输出:
>>> import sys
>>> logfile=open('/tmp/mylog.txt','a')
>>> print >> logfile, 'fatal error :invalid input!'

2.计算面积——语句分隔符+变量定义+数值运算+操作符


  1 #!/usr/bin/python
  2 wide=10
  3 length=20
  4 area=wide * length
  5 print "hello world"

  6 print area

算术运算:+ - * / ** % ,比较运算:> < <= == ;逻辑运算:and or not

3.输入与动态函数input&&raw_input


  1 #!/usr/bin/python
  2 wide=10

  3 length=input("the length of something")

   length=raw_input("the length of something")

  4 area=wide * length
  5 print "hello world"
  6 print area
foo = input

foo("I can input now")

二者的区别:

数字输入

当输入为纯数字时

  • input返回的是数值类型,如int,float
  • raw_inpout返回的是字符串类型,string类型

字符串为表达式

input会计算在字符串中的数字表达式,而raw_input不会。

如输入 “57 + 3”:

  • input会得到整数60
  • raw_input会得到字符串”57 + 3”


4.分支,循环,跳转与内建函数range


4.1分支

  1 #!/usr/bin/python
  2 tem=input("input a num")
  3 if tem > 50:
  4   print "more than 50"
  5 else:
  6   print "no more then 50"
注意:没有括号,要加冒号
# Area calculation program
print "Welcome to the Area calculation program"
print "---------------------------------------"
print
# Print out the menu:
print "Please select a shape:"
print "1 Rectangle"
print "2 Circle"
#Get the user's choice:
shape = input(">; ")
#Calculate the area:
if shape == 1:
      height = input("Please enter the height: ")
      width = input("Please enter the width: ")
      area = height *width
      print "The area is ", area
else:
      radius = input("Please enter the radius: ")
      area = 3.14 * (radius**2)
      print "The area is ", area
1. 只使用print本身将打印出一个空行 
2. ==检查两个值是否相等,与=不同,后者把表达式右侧的值赋给左侧的变量。这是一个非常重要的差别! 
3. **是python的幂运算符--因此半径的平方被写成radius**2 

4. print能够打印出不止一个东西。只要用逗号把它们分开就可以了。(它们在输出时会用单个空格分开。)


4.2for循环

注意,for循环不同于C语言的计数器循环,他是一种迭代器循环,接受可迭代对象作为参数。
for food in "spam", "eggs", "tomatoes":
      print "I love", food
数组:
for number in range(1, 100):
      print "Hello, world!"
      print "Just", 100 - number, "more to go..."
time模块中的sleep:
# Spam-cooking program
# Fetch the function sleep
from time import sleep
print "Please start cooking the spam. (I'll be back in 3 minutes.)"
# Wait for 3 minutes (that is, 3*60 seconds)...
sleep(180)
print "I'm baaack :)"
# How hot is hot enough?
hot_enough = 50
temperature = input("How hot is the spam?")
while temperature < hot_enouth:
      print "Not hot enough... Cook it a bit more..."
      sleep(30)
      temperature = input("OK, How hot is it now?")
print "It's hot enough - You're done!"


4.3while循环


def floor(number)://注意,这个地方的冒号
      result = 0
      while result <= number:
            result = result + 1
      result = result - 1
      return result
函数定义与while循环,注意利用严格的缩进而不是括号来传达层次关系
两个变量可以象这样一起赋值:x, y = y, y+1

5.复杂的数据结构


#!/usr/bin/python
  2 # Calculate all the primes below 1000
  3 import math//类include语句
  4 result = [2]
  5 for test in range(3,1000):
  6   bound=(int)(math.sqrt(test))//引用与数字类型转化
  7   for i in range(2,bound+2):
  8     if test%i==0:
  9       break
 10   if i==bound+1:
 11     result.append(test)
 12 print result

内建函数range事实上返回一个列表,可以象所有其它列表那样使用。(它包括第一个数,但是不包括最后一个数。) 
列表可以当作逻辑变量使用。如果它非空,则为true,否则为false。因此,while candidates意思是“while名称为candidates的列表非空时”或者简单的说“while存在candidates时”。 
你可以用if someElement in somelist来检查一个元素是否在列表中。 
你可以用someList.remove(someElement)来删除someList中的someElement。 
你可以用someList.append(something)为一个列表添加元素。事实上,你也可以使用“+”(象someList = someList+[something])。但是效率不是太高。 
你可以通过在列表名之后加上用括号括起来的表示某元素位置的数字(很奇怪,列表的第1个元素,位置是0)来获得列表的某个元素。因此someList[3]是someList 列表的第四个元素(依次类推)。 

你可以使用关键字del删除变量。它也可以用来删除列表中的元素(就象这里)。因此del someList[0]删除someList 列表中的第一个元素。如果删除前列表是[1, 2, 3],删除后就变成了[2, 3]。 


6.继续抽象——对象和面向对象编程 与函数定义


class Oven:
    def insertSpam(self, spam):
        self.spam = spam
    def getSpam(self):
        return self.spam
对象的类用关键字class定义。 
类的名称通常以大写字母开始,而函数和变量(还有属性和方法)的名称以小写字母开始。 
方法(也就是让对象知道如何去做的函数和操作)的定义没有特别,但是要在类的定义里面。 
所有对象的方法应当有的第一个参数叫做self(或者类似的……)原因很快就清楚了。 
对象的属性和方法可以这样来访问:mySpam.temperature = 2 或者dilbert.be_nice()。 
我能猜到上面例子中的某些东西你仍然不清楚。例如,什么是self?还有,现在我们有了对象菜谱(也就是类),我们怎样事实上构造一个对象呢? 

我们先颠倒一下顺序。对象通过象引用函数那样引用类名来创建: 

myOven = Oven()

myOven包含了一个Oven对象,通常叫做Oven类的一个实例。假设我们也构造好了一个Spam类,那么我们可象这样做: 
mySpam = Spam()
myOven.insertSpam(mySpam)

myOven.spam现在将包含mySpam。怎么回事?因为,我们调用一个对象的某个方法时,第一个参数,通常称为self,总是包含对象本身。(巧妙,哈!)这样,self.spam =spam这一行设置当前Oven对象的spam属性的值为参数spam。于是,这就象当于一个构造函数的作用。注意它们是两个不同的事物,尽管在这个例子中它们都被称为spam。 


另外,类中有一个特殊函数__init__(),这个函数是每个类都会默认定义的,我们也可以自己定义来覆盖这个函数。


注意,可以在函数定义的接下来的首句,用一句话来进行文档说明;同时函数在定义的时候可以指定默认参数,这样就可以在调用函数的时候不用指定函数。

def foo(debug=false):

     'this is a document line'

      if debug:

          print 'fsdfds'

      print 'done'

引用函数:foo()即可。


7.python与C的一些对比


数据类型:python是一种动态类型语言,即不同声明数据类型。

7.1逻辑运算


python使用or and not来进行逻辑运算,而C语言使用&& || ~

python使用True,False;c语言使用true,false


7.2字符串

python中字符串没有结束符;C语言有


7.3字符运算

C语言中字符可以和整数直接进行加减运算,在python中,字符和整数的互相转化需要借助两个函数ord()和chr()


8.python 中的字符串


python字符与字符串

 

word="abcdefg"
a
=word[2]
print 
"a is: "+a
b
=word[1:3]
print 
"b is: "+b # index 1 and 2 elements of word. index 3 is not included here
c
=word[:2]
print 
"c is: "+c # index 0 and 1 elements of word.
d
=word[0:]
print 
"d is: "+d # All elements of word.
e
=word[:2]+word[2:]
print 
"e is: "+e # All elements of word.
f
=word[-1]
print 
"f is: "+f # The last elements of word.
g
=word[-4:-2]
print 
"g is: "+g # index 3 and 4 elements of word.
h
=word[-2:]
print 
"h is: "+h # The last two elements.
i
=word[:-2]
print 
"i is: "+i # Everything except the last two characters
l
=len(word)
print 
"Length of word is: "+ str(l)

 

9.列表和元组


对比:

1)列表,使用【】,个数与数值可变

2)元组,使用(),个数与数值不可变


10.字典


类似与hash表,是一个key:value的模式

>>> adic={'doc':10}
>>> adic['excel']=20
>>> adic
{'doc': 10, 'excel': 20}
>>> adic.keys()
['doc', 'excel']


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


 看例子:

fobj=fopen('text.txt','r')

for eachline in fobj:

    print eachline,

fobj.close()


12.异常处理


try:
  filename=raw_input('enter file name')
  fobj=open(filename,'r')
  for eachline in fobj:
    print eachline,
  fobj.close()
except IOError,e:
  print 'file open err:',e


13.一些实用的内建函数


函数               描述

 

dir([obj])       显示对象的属性,如果没有提供参数, 则显示全局变量的名字

 

help([obj])     以一种整齐美观的形式 显示对象的文档字符串, 如果没有提供任何参数, 则会进入交互式帮助。

 

int(obj)          将一个对象转换为整数

 

len(obj)          返回对象的长度

 

open(fn, mode)  以 mode('r' = 读, 'w'= 写)方式打开一个文件名为 fn 的文件

 

range([[start,]stop[,step])  返回一个整数列表。起始值为 start, 结束值为 stop - 1; start默认值为 0,

    step默认值为1。

raw_input(str) 等待用户输入一个字符串, 可以提供一个可选的参数 str 用作提示信息。

 

str(obj) 将一个对象转换为字符串

 

type(obj) 返回对象的类型(返回值本身是一个type 对象!)


如果直接输出dir,显示的是dir的信息;如果输入dir()显示的是这个文档的相关信息;如果输入dir(sys)那么显示的是sys这么模块的相关信息
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值