python基础(变量,续行符,is,round,if,字符串,日期,数学,参数)


1 #coding=utf-8 2 #print函数 3 print 3, -1, 3.14159, -2.8 4 #type函数 5 print type(3), type(3.14159), type("123") 6 #类型转换 7 print int(3.14159), int(-2.8) 8 print float(3), float(-1) 9 #输出字符串 10 print "span" + "and" + "eggs" 11 str1 = "teacher" 12 str2 = "student" 13 print "I'm a %s, not a %s"%(str1, str2) 14 s = "123" 15 print type(s) == str 16 #次方 17 print 3 ** 3 18 print 81 ** 0.5

一.变量

 1 #coding=utf-8
 2 #变量
 3 meal = 40
 4 tip = 0.5
 5 total = meal * (1 + tip)
 6 print "%.2f"%total
 7 
 8 fifth_letter = "MONTY"[4]
 9 print fifth_letter
10 
11 #正常除,地板除
12 print 1 / 2.0
13 print 1 // 2.0
14 
15 #复数
16 x = 2.4 + 5.6j
17 print x.imag
18 print x.real
19 print x.conjugate()

二.续行符

 1 #coding=utf-8
 2 #续行符
 3 a = "aaaaaa"\
 4     "bbbbbbb"
 5 print a
 6 print "---------------"
 7 #(),[],{},'''可以不用续行
 8 a = ("aaaaa"
 9 "bbbbb")
10 print a
11 print "---------------"
12 a = ["aaaaa"
13      "bbbbbbb"]
14 print a
15 print "---------------"
16 a = {"aaaaaa"
17      "bbbbbbb"}
18 print a
19 print "---------------"
20 a = '''aaaaaaaaa
21 bbbbbbbbb'''
22 print a
23 print "---------------"

三.is,round函数

 1 #coding=utf-8
 2 #is是通过对象id判断
 3 a = 100.0
 4 b = 100
 5 c = 100
 6 print a == b
 7 print a is b
 8 print c is b
 9 print "------------"
10 #四舍五入
11 print round(3.4)
12 print round(3.5)
13 print "------------"
14 #函数
15 def spam():
16     eggs = 12
17     return eggs
18 print spam()

四.if结构,函数

 1 if True:
 2     pass
 3 elif True:
 4     pass
 5 else:
 6     pass
 7 #continue,break
 8 
 9 print 8 > 4 > 2
10 print 8 > 4 == 4
11 print "-----------"
12 
13 def f(x, y):
14     pass
15 print f(68, False)
16 print f(y = False, x = 68)
17 #print f(y = False, 68),error

五.局部全局变量

 1 #coding=utf-8
 2 """
 3 全局,局部变量
 4 """
 5 num = 4
 6 def f():
 7     num = 3
 8 f()
 9 print num #4
10 
11 def g():
12     global num
13     num = 3
14 g()
15 print num #3

 六.字符串

 1 #coding=utf-8
 2 #字符串
 3 a = "Xsxx"
 4 print len(a)
 5 print a.lower()
 6 print a.upper()
 7 print a.isalpha()
 8 print a.istitle()#首字母大写,其他字母小写s
 9 print a[0]
10 print a[1:3]
11 print type(str(3.14))

 

七.键盘输入

1 #coding=utf-8
2 #从键盘输入
3 num = raw_input("what's the number?")

八.日期

1 #coding=utf-8
2 #日期
3 from datetime import datetime
4 now = datetime.now()
5 print now
6 print now.year
7 print now.month
8 print now.day
9 print "%s:%s:%s"%(now.hour, now.minute, now.second)

九.数学

 1 #coding=utf-8
 2 #数学
 3 from math import *
 4 print sqrt(25)
 5 a = [1,2,3,4,5]
 6 print max(a)
 7 print min(a)
 8 print abs(-5)
 9 #print dir(math),error:no math
10 
11 import math
12 print dir(math)

十.参数

 1 #coding=utf-8
 2 #参数不确定时,*args,**kwargs(**kwargs有key值)
 3 a = [1, 2, 3, 4]
 4 b = 4
 5 c = '111'
 6 
 7 def f(*args):
 8     for i in args:
 9         print i
10 f(a,b,c)
11 
12 def g(**kwargs):
13     print kwargs
14 g(z = 1, k = 2, l = 3)

posted @ 2016-03-05 11:37  早杰  阅读(7101)  评论(0编辑  收藏  举报