Python的輸入和raw_input()內建函數等以及相關運算符

1. print 輸出


>>> :主提示符,表示解釋器在等你輸入下一個語句

... :次提示符,表示解釋器在提示你它在等你輸入下一個字符。

%s,%d, %f等,分別是用字符串,整數,浮點數替換。

>>> myString = "Hello World"
>>> 
>>> print myString
Hello World
>>> 
>>> myString
'Hello World'
>>> 
>>> 
>>> print "%s is a beautiful girl , she's %d ." % ("Lucy",21)
Lucy is a beautiful girl , she's 21 .
>>> 

其中,print "%s is a beautiful girl , she's %d ."  和C語言中的printf() 函數很相似,從Python與C語言的關係不難看到兩者的相似之處。


>>> yes = "YES"

>>> no = "NO"

>>> 

>>> print "I say ", yes,"u say ",no

I say  YES u say  NO

>>> 

>>> print "I say %s , u say %s" % (yes*3,no*3)

I say YESYESYES , u say NONONO

>>> 


帶有兩個參數的print :

strArray = ["hello","my","name","is","fulairy"]
for s in strArray:
    print(s,len(s))
結果輸出:

/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 /Users/apple/project/PycharmProjects/untitled/python_demo/fibonacci.py
('hello', 5)
('my', 2)
('name', 4)
('is', 2)
('fulairy', 7)

Process finished with exit code 0

2. 

(1)raw_input()內建函數,

該函數接收用戶標準輸入,然後賦值給變量。 下面的輸入信息賦值給了變量pyStr 從hello ---->world

>>> pyStr = raw_input("hello")
helloworld
>>> pyStr
'world'
>>> 

(2) 使用in()函數 : 將數值字符串轉換成整數值

>>> testInt = 0
>>> print testInt
0
>>> testInt = int("2222")
>>> testInt
2222
>>> 

3. 其他

1)註釋: Python中的註釋使用 #號,也支持和java裏面的文檔註釋,但是用的少

2)運算符:

+ - * /  //  **   

注意: / //  兩個都是除法運算符,//表示浮點除法     ** 表示乘方運算

< <= > >= !=<>  

注意: 3<4<5  可以理解爲: 3<4 and 4<5

邏輯運算符: and   or    not   且,或,非

3)變量名:  以大寫或者小寫字母開頭,或者下劃線開頭,其餘可以是數字,字母,下劃線等

4)五種基本數據類型: 

int long    bool(TRUE---非0,FALSE---0)    float    complex (複合類型)

注意: 還有一種數據類型,decimal : 該種數據類型用於十進制浮點數,不是內建類型,需要導入decimal模塊。

5)字符串:包含在單引號,雙引號,三引號中,角標從0開始,最後一個的索引是  -1 

[] :索引運算符

[:] :切片運算符

>>> pythonStr = "Python"
>>> pythonStr[2]
't'
>>> pythonStr[2:4] #半開半閉區間
'th'
>>> 
>>> pythonStr[2:4] #半開半閉區間
'th'
>>> 
>>> pythonStr[2:]
'thon'
>>> pythonStr[0:]
'Python'
>>> 


多元賦值,並且互相交換兩個值:,這裏的交換值的方式和c或者其他語言中的交換方式簡化多了。

    x, y ,z = 1,2,3
    print x,y,z
    #change value x between y
    x , y = y,x
    print x,y,z
輸出分別是:123 和 321


6)列表和元組

列表使用 [] --->中括號  元組使用 ()----->小括號    可以存儲任意數量,任意類型,這個和java中的List有區別

>>> pythonArr = ["hello","FuLaiRy",222,444,TRUE]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'TRUE' is not defined
>>> pythonArr = ["hello","FuLaiRy",222,444]
>>> pythonArr
['hello', 'FuLaiRy', 222, 444]
>>> pythonArr[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> pythonArr[3]
444
>>> pythonArr[0:]
['hello', 'FuLaiRy', 222, 444]
>>> 


注意: 我在上面的列子中加入了true,以及TRUE都提示了錯誤信息; 我去角標爲4的元素,也提示了錯誤信息,越界了。

7)字典:這個和java中的hashMap hashSet 方式有點相似,都是鍵值對的形式。

>>> aDict = {"key1":"value1","key2":"value2"}
>>> aDict
{'key2': 'value2', 'key1': 'value1'}
>>> 
>>> aDict["key3"] = 888
>>> aDict
{'key3': 888, 'key2': 'value2', 'key1': 'value1'}
>>> 

上面列子中:  “key1”:"value1" 既可以用單引號,也可以用雙引號; 

添加元素: aDict["key3"] = 888  添加進去後,在字典的頭部

>>> for key in aDict :
...     print key
... 
key3
key2
key1
>>> 
>>> for key in aDict :
...     print key,aDict[key]
... 
key3 888
key2 value2
key1 value1
>>> 

注意: 此處遇到一個異常錯誤,與代碼的縮進相關、

>>> for k in aDict:

... print k , aDict[k]

  File "<stdin>", line 2

    print k , aDict[k]

        ^

IndentationError: expected an indented block

>>> 


IndentationError: expected an indented block

表示代碼的縮進不對,於是我在print 的前面加了個tab 

代碼就正常了,看來這個縮進還是有點那啥......萬一成百上千行代碼,少了個縮進....不過放心,上面的錯誤會提示到是哪一處,不過好像也不好找啊。

8)if-elif-else注意代碼的縮進

if

if代碼塊

elif

elif代碼塊

else

else代碼塊

9)while循環 , 

注意: 

>>> while count < 9:

後面有個: 表示還有繼續輸入,還有代碼塊

print count 和 count +=1 的首行,都添加了一個空格

>>> count =0

>>> while count < 9:

...  print count

...  count +=1

... 

0

1

2

3

4

5

6

7

8

>>> 


for 和 range函數

>>> strArr = ["u","r","my","sunshine"]

>>> for s in strArr:

...  print s

... 

u

r

my

sunshine

>>> 


>>> print range(5)

[0, 1, 2, 3, 4]

>>> 


range函數的相關介紹:

Help on built-in function range in module __builtin__:


range(...)

    range(stop) -> list of integers

    range(start, stop[, step]) -> list of integers

    

    Return a list containing an arithmetic progression of integers.

    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.

    When step is given, it specifies the increment (or decrement).

    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!

    These are exactly the valid indices for a list of 4 elements.

(END) 


others:
range函數可以攜帶三個參數,其中第三個參數是增量,後面一個數在前一個數的基礎上按照第三個增量參數增加。比如:
print range(0,21,5) #range from 0 to 21
上面這句話打印的是
[0, 5, 10, 15, 20]

10)異常處理

try except   java中用的是catch 用catch多好,非要搞獨立派......

11)列表解析

注意:使用一個for循環將所有的值放到列表中,

>>> s = [x**2 for x in range(4)]

>>> print s

[0, 1, 4, 9]

>>> 

>>> str = [x*2 for x in range(8) if not x % 2]

>>> print str

[0, 4, 8, 12]

>>> 


12)函數

定義一個函數:def func (variable)  

使用def 關鍵字,func是方法名,小括號裏面是參數   

>>> def func(num):

...  if num >0:

...   print "the number is positive"

...  elif num < 0:

...   print "the number is nagative"

... 

>>> 

>>> 12

12

>>> func(43)

the number is positive

>>> 

>>> func(-12)

the number is nagative

>>> 


注意縮進: 靠。。。。。

導入模塊:

import sys

sys.platform

sys.version

13)相關的一些練習

這個後面在添加,發現必須要搞個ide,我下載了Pycharm

/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 /Users/apple/project/PycharmProjects/untitled/python_demo/__init__.py
pls input some characters:sdvasd'
Traceback (most recent call last):
  File "/Users/apple/project/PycharmProjects/untitled/python_demo/__init__.py", line 66, in <module>
    instance.loopChars(testStr)
TypeError: loopChars() takes exactly 1 argument (2 given)

Process finished with exit code 1

這個錯誤,解決辦法就是直接在loopChars的方法生命地方,加一個參數self 

練習: 輸入一段字符串,並使用while 和 for循環打印出來。

class CharactersInput:
        def loopChars(self,strArr):
                if len(strArr) <= 0:
                        print "Error : empty , not suggested."
                else:
                        print  "use while loop"
                        count = len(strArr)
                        i = 0
                        while i < count:
                                s = strArr[i]
                                print "#" + strArr[i],
                                i +=1
                        print  "use for loop :"
                        for s in strArr:
                                print s

testStr =  raw_input("pls input some characters:")
instance = CharactersInput()
instance.loopChars(testStr)


14) Python IDE PyCharm

http://www.jetbrains.com/pycharm/  網站中也有相關教程。 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章