`
tmj_159
  • 浏览: 700104 次
  • 性别: Icon_minigender_1
  • 来自: 永州
社区版块
存档分类
最新评论

Python 基本语法入门

 
阅读更多

Python是一种脚本语言,和其它语言Java,C,C++不一样的是,不需要编译就可以直接运行。

而且这种语言很简单,这里这尝试一些入门的东西,详细的东西自己再找资料吧。

下面学习的东西来自下面的英文学习网站

http://www.afterhoursprogramming.com/tutorial/Python/Introduction/

 

1.简单输出

#!/usr/bin/python
print("good luck");

 

2.注释

单行注释#井号,多行注释用‘’‘三个单引号

 

#Am a comment
,,,
Am a comment too
'''

 

3.变量

python是弱类型的变量,也就是说不需要声明的变量的类型,编译器会自动识别

a=0
b=2
print(a+b) #2

a="0"
b="2"
print(a+b) #02

a="0"
b=2
print(int(a)+b) #2

 下面是牵扯到类型转换的函数

int(variable)
str(variable)
float(variable)

 

4.基本操作符

+ 加法
- 减法
* 乘法
/ 除法
% 取余数
**  幂数
//  小于除结果的最大整数

 

5.if 条件

a=20
if a >= 22:
    print("if")
elif a >= 21:
    print("elif")
else:
    print("else")

 

6. 函数

Python中也是先声明再调用的

def someFunction(a,b):
    print(a+b)
someFunction(11,22)

 方法中声明的变量,方法外面是无法使用的。

 

7.循环

Python中的循环是很神奇的东西

for循环

for a in range(1,3)
    print (a)

#1,2

 上面相当于从1到3但是不包括3

while循环,下面的while循环和上面的for循环等价

a=1
while a<3:
    print (a)
    a+=1

 

8.字符串

myString=""
print(type(myString))

#<class 'str'>

 常用的字符串函数

stringVar.count('x')
stringVar.find('x')
stringVar.lower()
stringVar.upper()
stringVar.replace('a','b')
stringVar.strip() //去掉前后空格

 字符串截取,和其它很多脚本语言一样,负数表示从后面开始

a="string"
print(a[1:3])
print(a[:-1])

#tr
#strin

 

9.List

Python没有数据,只有列表

sampleList=[1,2,3,4,5,6,7,8]
print(sampleList[1])

#2

 循环迭代List

sampleList=[1,2,3,4,5,6,7,8]
for a in sampleList:
    print (a)

 常用List方法

.append(value)
.count('x')
.index('x')
.insert(y,'x')
.pop()
.remove('x')
.reverse()
.sort()

 

10. Tuple

Tuple和List基本一样,但是有一点是Tuple里面的元素不允许添加,修改和删除

myList = [1,2,3]
myList.append(4)
print (myList)

myTuple = (1,2,3)
print (myTuple)

myTuple2 = (1,2,3)
myTuple2.append(4)
print (myTuple2)

 上面代码如果执行到myTuple2.append(4)的时候会出错。

但是某些情况下你可能需要修改,也只能转成List之后再修改

myTuple = (1,2,3)
myList = list(myTuple)
myList.append(4)
print (myList) 

 

11.Dictionaries

myExample = {'someItem': 2, 'otherItem': 20}
print(myExample['otherItem']) 

#20

 类似Map,一个键值对的数据结构,下面代码只输出key

myExample = {'someItem': 2, 'otherItem': 20}
myExample['newItem'] = 400
for a in myExample:
    print (a)

 以键值对的形式输出呢

myExample = {'someItem': 2, 'otherItem': 20,'newItem':400}
for a in myExample:
    print (a, myExample[a])

 dictionaries 看起来有序,其实它是无序的,并且大小写敏感,而且可以混用数据类型,而且提供了删除和清空方法

del d["key"]
d.clear()

 

12 格式化

格式化数字

print('The order total comes to %f' % 123.44)
print('The order total comes to %.2f' % 123.444) 

'''结果
The order total comes to 123.440000
The order total comes to 123.44 
'''

 格式化字符串

a ="abcdefghijklmnopqrstuvwxyz"
print('%.20s' % a) 

 取前面20个字符

 

13. 异常处理

var1 = '1'
try:
    var1 = var1 + 1 # since var1 is a string, it cannot be added to the number 1 
except:
    print(var1, " is not a number") #so we execute this
print(var1) 

 

14.读文件

比如我们有如下文件

I am a test file.
Maybe someday, he will promote me to a real file.
Man, I long to be a real file
and hang out with all my new real file friends.

 通过以下代码读文件的内容

f = open("test.txt","r") #opens file with name of "test.txt"
print(f.read(1)) # 读一个
print(f.read()) #读剩下的
f.close() #关闭文件

当然我们还可以读文件的一行

print(f.readline())

 或者把文件读到某个List中存起来

myList = []
for line in f:
    myList.append(line)
print(myList) 

 我们得到的结果可能是下面带换行符号的字符串

['I am a test file.\n', 'Maybe someday, he will promote me to a real file.\n', 'Man, I long to be a real file\n', 'and hang out with all my new real file friends.'] 

 

 15. 写文件

f = open("test.txt","w") #opens file with name of "test.txt"
f.write("I am a test file.")
f.write("Maybe someday, he will promote me to a real file.")
f.write("Man, I long to be a real file")
f.write("and hang out with all my new real file friends.")
f.write("Maybe someday, he will promote me to a real file.\n") #写一行
f.close()

 

16. 类

类的定义,如下定义了一个叫Calculator类,并且文件的名字叫ClassOne.py

#ClassOne.py
class Calculator(object):
    #define class to simulate a simple calculator
    def __init__ (self):
        #start with zero
        self.current = 0
    def add(self, amount):
        #add number to current
        self.current += amount
    def getCurrent(self):
        return self.current

 接下来是使用这个类

from ClassOne import * #get classes from ClassOne file
myBuddy = Calculator() # make myBuddy into a Calculator object
myBuddy.add(2) #use myBuddy's new add method derived from the Calculator class
print(myBuddy.getCurrent()) #print myBuddy's current instance variable 

 

真的很简单。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics