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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM