您的位置:首页 > 编程语言 > Python开发

python入门

2015-11-16 00:00 711 查看

                                                        基本python语法
python程序可以通过任何文本编辑器来处理,并且以.py作为扩展名。python程序不一定需要第一行或者最后一

行,但是可以给出python环境路径作为第一行:#!/usr/bin/python,并且可以可执行。另外,python程序可以从

命令提示符运行,python file.py。在python中,没有花括号或者分号。它是一种高级程序设计语言。它通过块

功能来标识代码段的缩进。
#!/usr/bin/python
if (x > y):
   print("x is greater than y")
   x = x -1
else:
   print("x is less than or equal to y")
                                                       变量和数据类型
python变量命名以字母或者下划线开头,并且变量名是大小写敏感的。变量不需要声明,数据类型可以从赋值语

句中推断出来。python支持的数据类型:
boolean,integer,long,float,string,list,object,None
例如:
bool = True
name = "Craig"
age = 26
pi = 3.14159
print(name + ' is ' + str(age) + ' years old.')
-> Craig is 26 years old.
变量范围:python中的大多数变量在它们自己的函数或者类中是局部变量。
全局变量:可以通过global关键字定义。
a = 1
b = 2
def Sum():
   global a, b
   b = a + b
Sum()
print(b)
-> 3

                                                        语句和表达式
常用的python语句:
print
赋值语句
输入语句
raw_input:允许用户输入字符串,如果是需要数值型,可以使用int或者float函数将string转化为相应的类型
import:导入模块到python中
print "Hello World"
print('Print works with or without parenthesis')
print("and single or double quotes")
print("Newlines can be escaped like\nthis.")
print("This text will be printed"),
print("on one line becaue of the comma.")
name = raw_input("Enter your name: ")
a = int(raw_input("Enter a number: "))
print(name + "'s number is " + str(a))
a = b = 5
a = a + 4
print a,b
9 5
python表达式包括:
a = b = 5 #赋值表达式
b += 1 #复合赋值表达式
c = "test"
import os,math #导入os和math模块中的所有函数

                                                          操作符和数学运算
操作符:
算术+, -, *, /, %
比较 ==, !=, <, >, <=, >=
逻辑and, or, not
乘方**
系统调用os.system('ls -l')  需要导入os模块
数学运算:
绝对值: a = abs(-7.5)
反正玄函数: x = asin(0.5) #returns in rads
向上近似计算: print(ceil(4.2))
余弦: a = cos(x) #x in rads
计算角度: a = degrees(asin(0.5)) #a=30
e: y = exp(x) #y=e^x
向下近似计算: a = floor(a+0.5)
自然对数: x = log(y); #Natural Log
   x = log(y,5); #Base-5 log
以10为底的对数: x = log10(y)
最大值: mx = max(1, 7, 3, 4) #7
   mx = max(arr) #max value in array
最小值: mn = min(3, 0, -1, x) #min value
乘方: x = pow(y,3) #x=y^3
弧度: a = cos(radians(60)) #a=0.5
随机数 #: Random number functions require import random
   random.seed() #Set the seed based on the system time.
   x = random() #Random number in the range [0.0, 1.0)
   y = randint(a,b) #Random integer in the range [a, b]

近似: print round(3.793,1; #3.8 - rounded to 1 decimal
   a = round(3.793,0) #a=4.0
sin: a = sin(1.57) #in rads
平方根: x = sqrt(10) #3.16...
                                                           字符串
字符串是被单引号或者双引号定义。如果在字符串前加上r,那么可以不考虑特殊字符转换。
 print 'I\'ll be back.'.
print r'The newline \n will not expand'
a = "Gators"
print "The value of a is \t" + a
-> The value of a is       Gators

如果没有使用原字符r处理,则需要使用转义字符\n, \r, \t, \\ 和 \" 等等。另外, """可以使字符串跨多行

表示。
print """
This is an example of a string in the heredoc syntax.
This text can span multiple lines
"""
字符串运算符:==, !=, <, >, <=和 >=
s = str(3.5)
name = "Lee"
print name + "'s number is " + str(24)
字符串函数:
s = "Go Gators! Come on Gators!"
子串抽取:x = s[3:9] #x = "Gators"
  x = s[:2] #x = "Go"
  x = s[19:] #x = "Gators!"
  x = s[-7:-2] #x = "Gator"
子串计算;x = s.count("Gator") #x = 2
判断是否以某字符串结束: x = s.endswith("Gators") #x = False
查找:x = s.find("Gator") #x = 3
  x = s.find("gator") #x = -1
连接: a = ['abc','def','ghi']
  t = "--"
  x = t.join(a) #x = abc--def--ghi
长度:x = len(s) #x = 26
小写:print s.lower() #go gators! come on gators!
替换:x = s.replace("Gators","Tigers",1) #x = Go Tigers! Come on Gators!
从右边开始寻找:x = s.rfind("Gator") #x = 19
拆分:a = s.split() #a=['Go', 'Gators!', 'Come', 'on', 'Gators!']
判断是否以某字符串开始:x = s.startswith("Go") #x = True
去除头尾字符,默认空格:strip([chars])
转换为大写:upper()

                                                              数组

list = [2, 4, 7, 9]
list2 = [3, "test", True, 7.4]
a = range(5) #a = [0,1,2,3,4]
a = range(10,0,-2) #a = [10,8,6,4,2]

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: