目錄
- Python數據類型
- python的運算符
- Python的循環與判斷語句
- python練習
- Python作業
一. Python的數據類型
1. 整型(int)
<1>. 賦值
1 num1 = 123 # 變量名 = 數字 2 num2 = 456 3 num3 = int(123) # 另外一種賦值的方法 4 print(num1) 5 print(num2)
6 print(num3)
<2>. int類的額外功能
def bit_length(self): # real signature unknown; restored from __doc__
#--------------這個功能主要是計算出int類型對應的二進制位的位數--------------------------------------- """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() 6 """ return 0
例子:
num = 128 # 128的二進制10000000,它占了一個字節,八位 print(num.bit_length()) 顯示: 8
<3>. int的賦值
每一個賦值int類都要重新開辟一段地址空間用來存儲,而不會改變原來地址空間的值。
num1 = 123 num2 = num1 num1 = 456 print(num1) print(num2) 顯示: 456 123
原理:
第一步賦值:開辟了一個空間存入123 ,變量為num1。
第二步賦值:先指向num1,然后通過地址指向了123。
第三部賦值:重新開辟一個地址空間用來存入456,num2的指向不變。
2. 布爾型(bool)
<1>. 真 True
<2>. 假 Flase
3. 字符型(char)
<1>. 索引
對於字符而言索引指的是通過下標找出其對應的字符。准確來說字符其實就是單個字符的集合。每個單個字符對應一個索引值,第一個字符對應的是0。
str = 'hello huwentao.' print(str[1]) # 因為下標是從零開始的,因此答案是e 顯示: e
<2>. 切片
切片其實就是選取字符中的某一段。
# str[1:-1:2] 第一個數代表起始位置,第二個數代表結束位置(-1代表最后),第三個數代表步長(每隔2個字符選擇一個) str = 'hellohuwentao.' print(str[1]) print(str[1:]) print(str[1:-1:2]) 顯示結果: e ellohuwentao. elhwna
<3>. 長度
#長度用的是len這個函數,這個長度可能和c有點不太一樣,是不帶換行符的。所一結果就是14 str = 'hellohuwentao.' print(len(str)) 顯示: 14
<4>. 循環
上面講過,字符串其實就是一連串的字符的集合,因此它可以成為可迭代的,可迭代的都可以用for循環
# print里面的end指的是每輸出一行,在最后一個字符后面加上引號內的內容,此處為空格,默認為換行符 str = 'hellohuwentao.' for i in str: print(i, end=' ') 顯示: h e l l o h u w e n t a o .
<5>. 額外的功能
因為char的功能太多,因此里面有的部分功能沒有講

def capitalize(self): # real signature unknown; restored from __doc__ #------------------首字母大寫------------------------------=------------------------------------- """ S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ #-----------------居中,width代表的是寬度,fillchar是代表填充的字符''.center(50,'*')-------------------- """ S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ #-----------------和列表的count一樣,計算出和sub一樣的字符的個數,start,end帶表起始和結束的位置-------------- """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ #---------------代表指定的編碼,默認為‘utf-8’,如果錯了會強制指出錯誤------------------------------------- """ S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ return b"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ #------------------判斷endswith是不是以suffix這個參數結尾-------------------------------------------- """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ #-----------可以理解為擴展tab鍵,后面的tabsize=8代表默認把tab鍵改成8個空格,可以修改值----------------------- """ S.expandtabs(tabsize=8) -> str Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return "" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ #------------從左往右查找和sub相同的字符,並把所在的位置返回,如果沒有查到返回-1------------------------------ """ S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(self, *args, **kwargs): # known special case of str.format #-----------------指的是格式,也就是在字符中有{}的,都會一一替換 str = 'huwegwne g{name},{age}' print(str.format(name = '111',age = '22')) 結果:huwegwne g111, 22 ------------------------------------------ """ S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ #-------------和find一樣,只是如果沒有查找到會報錯----------------------------------------------------- """ S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 return False def join(self, iterable): # real signature unknown; restored from __doc__ #------------------通過字符來連接一個可迭代類型的數據 li = ['alec','arix','Alex','Tony','rain'] print('*'.join(li)) 結果:alec*arix*Alex*Tony*rain --------------------------------- """ S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ #----------------和center類型,只不過它是向左對齊,而不是居中-------------------------------------------- """ S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): # real signature unknown; restored from __doc__ #--------------------全部轉換成小寫---------------------------------------------------------------- """ S.lower() -> str Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ #-------------------和strip類似,用來刪除指定的首尾字符,默認為空格-------------------------------------- """ S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def partition(self, sep): # real signature unknown; restored from __doc__ #-----------------------------partition() 方法用來根據指定的分隔符將字符串進行分割。 """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ #-------------------替換,用新的字符串去替換舊的字符串------------------------------------------------- """ S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ #-----------和find類似,只不過是從右向左查找---------------------------------------------------------- """ S.rfind(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ #-----------和index類似,只不過是從右向左查找---------------------------------------------------------- """ S.rindex(sub[, start[, end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ #----------------和center類型,只不過它是向右對齊,而不是居中-------------------------------------------- """ S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ #----------------------------和split相似,只不過是從右向左分離--------------------------------------- """ S.rsplit(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ #--------------方法用於移除字符串尾部指定的字符(默認為空格)。--------------------------------------------- """ S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ #--------------------------------方法用於把一個字符串分割成字符串數組默認是以空格隔離---------------------- """ S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ """ S.splitlines([keepends]) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ #---------------------------判斷是不是以prefix字符開頭---------------------------------------------- """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): # real signature unknown; restored from __doc__ #-----------用於移除字符串頭尾指定的字符(默認為空格)。------------------------------------------ """ S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def swapcase(self): # real signature unknown; restored from __doc__ #-------------------------------------- 方法用於對字符串的大小寫字母進行轉換。------------------------- """ S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): # real signature unknown; restored from __doc__ #-----------------------------把每一個單詞的首字母都變成大寫------------------------------------------ """ S.title() -> str Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case. """ return "" def translate(self, table): # real signature unknown; restored from __doc__ """ S.translate(table) -> str Return a copy of the string S in which each character has been mapped through the given translation table. The table must implement lookup/indexing via __getitem__, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted. """ return "" def upper(self): # real signature unknown; restored from __doc__ #-------------------------------把全部的字母變成大寫------------------------------------------------ """ S.upper() -> str Return a copy of S converted to uppercase. """ return ""
4. 列表(list)
<1>. 索引
# 和字符串一樣,列表下標默認也是從0開始 list = ['huwentao','xiaozhou','tengjiang','mayan'] print(list[1]) 顯示 xiaozhou
<2>. 切片
# 和字符換也是一樣的,也是起始位置,結束位置,和步長 list = ['huwentao','xiaozhou','tengjiang','mayan'] print(list[2]) print(list[1:3:1]) 顯示: tengjiang ['xiaozhou', 'tengjiang']
<3>. 長度
# 和字符串一樣,長度代表着元祖里面元素的個數 list = ['huwentao','xiaozhou','tengjiang','mayan'] print(len(list)) 顯示; 4
<4>. 循環
# 和字符串相同,此處就不在進行說明 list = ['huwentao','xiaozhou','tengjiang','mayan'] for i in list: print(i,end=' ') 顯示: huwentao xiaozhou tengjiang mayan
<5>. 額外的功能

# 里面的參數self是代表自身,如果只有self,在調用的時候不用傳遞參數,如果是等於,就代表有默認的傳遞值,可不用傳遞參數 def append(self, p_object): # real signature unknown; restored from __doc__ #--------------在列表后面添加數據-------------------------------------- """ L.append(object) -> None -- append object to end """ pass def clear(self): # real signature unknown; restored from __doc__ #--------------清空列表---------------------------------------------- """ L.clear() -> None -- remove all items from L """ pass def copy(self): # real signature unknown; restored from __doc__ #--------------------復制列表並賦值給a = li.copy()---------------------- """ L.copy() -> list -- a shallow copy of L """ return [] def count(self, value): # real signature unknown; restored from __doc__ # ---------------計算列表中和value相同的字符串的個數--------------------- """ L.count(value) -> integer -- return number of occurrences of value """ return 0 def extend(self, iterable): # real signature unknown; restored from __doc__ # -----------------把一個可迭代類型的數據整天添加到列表中----------------- """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """ pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ #------------------找到和value相同的數據所在列表中的位置,后面的兩個參數代表開始位置和結束位置-------- """ L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__ #--------------------在index這個位置插入p_object值--------------------------------- """ L.insert(index, object) -- insert object before index """ pass def pop(self, index=None): # real signature unknown; restored from __doc__ # ------------------刪除index這個位置的數據,返回給一個變量------------------------ """ L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. """ pass def remove(self, value): # real signature unknown; restored from __doc__ #--------------------刪除value的數據,不會返回給某個變量--------------------------- """ L.remove(value) -> None -- remove first occurrence of value. Raises ValueError if the value is not present. """ pass def reverse(self): # real signature unknown; restored from __doc__ #-------------------------翻轉,就是把最后一個元素放在第一個,依次類推-------------- """ L.reverse() -- reverse *IN PLACE* """ pass def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__ #-------------------------排序-------------------------------------------------- """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """ pass
5. 元組(tuple)
元組和列表非常相近,只不過不可以進行修改,只能夠進行查看。下面不在進行詳細描述,只是簡單的將一下怎么創建,創建的時候要用小括號。
tuple = ('huwentao','xiaozhou','tengjiang','mayan') for i in tuple: print(i, end=' ') 顯示: huwentao xiaozhou tengjiang mayan
6. 字典(dict)
<1>. 索引
# 字典的索引和其他的不太一樣,他的主要是通過鍵值對進行索引的,里面的不是下標,而是他的鍵 dic = { 'k1':'alex', 'k2':'aric', 'k3':'Alex', 'k4':'Tony' } print(dic['k1'])
<2>. 切片
字典沒有切片,因為對於字典而言,他是無序存儲的,和其他的類型不太一樣。
<3>. 長度
print(len(dic))可以輸出字典的長度,代表的是字典的鍵值對長度。
<4>. 循環
# 字典的循環也比較有意思,他循環輸出的不是鍵值對,而是字典的鍵 dic = { 'k1':'alex', 'k2':'aric', 'k3':'Alex', 'k4':'Tony' } for i in dic: print(i)
<5>. 額外的功能

def clear(self): # real signature unknown; restored from __doc__ #------------------清空字典-------------------------------------- """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ #----------------------復制字典給一個變量----------------------------- """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(*args, **kwargs): # real signature unknown """ Returns a new dict with keys from iterable and values equal to value. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ #---------------------得到某個鍵對應的值------------------------------------ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def items(self): # real signature unknown; restored from __doc__ #--------------------------得到字典的鍵值對------------------------------------------ """ D.items() -> a set-like object providing a view on D's items """ pass def keys(self): # real signature unknown; restored from __doc__ #--------------------------得到字典的鍵----------------------------------------- """ D.keys() -> a set-like object providing a view on D's keys """ pass def pop(self, k, d=None): # real signature unknown; restored from __doc__ #---------------------刪除某個鍵值對----------------------------------------- """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ #----------------隨機刪除一個鍵值對------------------------------------------- """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ #------------------和get方法類似, 如果鍵不存在於字典中,將會添加鍵並將值設為默認值-------------- """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update #----------------------- 把一個字典添加到另外一個字典中-------------------------------------- """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ #-----------------------------得到字典的值----------------------------------------------- """ D.values() -> an object providing a view on D's values """ pass
二. Python的運算符
1. 運算符
# 運算符主要有+ - * / ** % // # ** 是冪運算 # % 取模 # // 是整除,不留小數 a = 8 b = 16 print('a + b=',a + b) print('a - b=',a - b) print('a * b=',a * b) print('a / b=',a / b) print('a // b=',a // b) print('a % b=',a % b) print('a ** 2=',a ** 2) 顯示結果: a + b= 24 a - b= -8 a * b= 128 a / b= 0.5 a // b= 0 a % b= 8
2. 比較運算符
# 比較運算符有: > < >= <= == != # == 代表恆等於,一個等號代表賦值 # != 代表不等於 a = 8 b = 16 print('a > b ?', a > b) print('a < b ?', a < b) print('a >= b ?', a >= b) print('a <= b ?', a <= b) print('a == b ?', a == b) print('a != b ?', a != b) 顯示: a > b ? False a < b ? True a >= b ? False a <= b ? True a == b ? False a != b ? True
3. 邏輯運算符
# 邏輯運算值有: and or not # and 代表 與 # or 代表或 # not 代表非 a = 8 b = 16 c = 5 print('c<a<b', c<a<b) print('a > c and a > b', a > c and a > b) print('a > c and a < b', a > c or a < b) print('not a>c ', not a>c) 顯示: c<a<b True a > c and a > b False a > c and a < b Tr
三. Python的判斷循環語句
循環和判斷語句最重要的是要學習他的結構,結構記住了就是往里面套條件就是了,下面先說一下Python的特點
- 縮進 在很多語言里面,每一個結構都是有頭有尾的,不是小括號就是大括號,因此,很多語言通過其自身的結構就會知道程序到哪里結束,從哪里開始,但是Python不一樣,Python本身並沒有一個表示結束的標志(有人會覺得這樣會使程序簡單,但是有人會覺得這樣會使程序變得麻煩),不管怎樣,那Python是通過什么來標志一個程序的結束的呢?那就是縮進,因此縮進對於Python來講還是蠻重要的。尤其對這些判斷循環語句。
1. while循環語句
結構: while condition: statement statemnet if........... 這個while循環只會執行statement,因為后面的if和statement的縮進不一樣,因此當跳出while循環的時候才會執行后面的if語句
事例:執行了三次beautiful,執行了一次ugly num = 3 while num < 6: print('you are beautiful.', num) num += 1 print('you are ugly.') 顯示: you are beautiful. 3 you are beautiful. 4 you are beautiful. 5 you are ugly.
2. for循環語句
結構: for var in condition: statement statement if ............ for后面的跟的是變量,in后面跟的是條件,當執行完for循環之后,才會執行后面的if語句
事例:顯示了三次beautiful,一次ugly,因為他們的縮進不同 i = 1 for i in range(3): print('you are beautiful.', i) print('you are ugly.') 顯示: you are beautiful. 0 you are beautiful. 1 you are beautiful. 2 you are ugly.
3. if判斷語句
結構: if condition: statement statement else: statement1 statement2 statement3........... 當滿足條件,則執行statement,否則執行statement1和2,執行完了之后執行statement3
事例: a = 16 b = 89 if a > b: print('a>b') else: print('a<b') print('you are right.') 顯示: a<b you are right.
四. Python的練習題
1. 使用while循環輸入1 2 3 4 5 6 8 9
num = 1 while num < 10: if num == 7: num += 1 continue print(num, end = ' ') num += 1
2. 求1-100內的所有奇數之和
# -*- coding:GBK -*- # zhou # 2017/6/13 num = 1 sum = 0 while num < 100: if num % 2 == 1: sum += num num += 1 print('所有奇數之和為: ',sum)
3. 輸出1-100內的所有奇數
# -*- coding:GBK -*- # zhou # 2017/6/13 num = 1 sum = 0 while num <= 100: if num % 2 == 1: print(num,end = ' ') num += 1
4. 輸出1-100內的所有偶數
# -*- coding:GBK -*- # zhou # 2017/6/13 num = 1 sum = 0 while num <= 100: if num % 2 == 0: sum += num num += 1 print('所有偶數之和為: ',sum)
5. 求1-2+3-4+5........99的所有數之和
# -*- coding:GBK -*- # zhou # 2017/6/13 num = 1 sum = 0 while num < 100: if num % 2 == 1: sum -= num else: sum += num num += 1 print(sum)
6. 用戶登錄程序(三次機會)
# -*- coding:GBK -*- # zhou # 2017/6/13 name = 'hu' password = 'hu' num = 1 while num <= 3: user_name = input('Name: ') user_password = input('Password: ') if user_name == name and user_password == password: print('you are ok. ') break num += 1 else: print('you are only three chance, now quit.')
五. Python的作業題
1. 有如下值集合{11,22,33,44,55,66,77,88,99.......},將所有大於66的值保存至字典的第一個key中,將小於66 的值保存至第二個key的值中,即:{‘k1’:大於66的所有值,‘k2’:小於66的所有值}
# -*- coding:GBK -*- # zhou # 2017/6/13 dict = {'k1':[],'k2':[]} list = [11,22,33,44,55,66,77,88,99,100] for i in list: if i <= 66: dict['k1'].append(i) else: dict['k2'].append(i) print(dict)
2. 查找列表中的元素,移動空格,並查找以a或者A開頭 並且以c結尾的所有元素
li = ['alec','Aric','Alex','Tony','rain']
tu = ('alec','Aric','Alex','Tony','rain')
dic = {'k1':'alex', 'k2':'Aric', 'k3':'Alex', 'k4':'Tony'}
# -*- coding:GBK -*- # zhou # 2017/6/13 li = ['alec','arix','Alex','Tony','rain'] tu = ('alec','aric','Alex','Tony','rain') dic = {'k1':'alex', 'k2':'aric', 'k3':'Alex', 'k4':'Tony'} print('對於列表li:') for i in li: if i.endswith('c') and (i.startswith('a') or i.startswith('A')): print(i) print('對於元組tu:') for i in tu: if i.endswith('c') and (i.startswith('a') or i.startswith('A')) : print(i) print('對於字典dic:') for i in dic: if dic[i].endswith('c') and (dic[i].startswith('a') or dic[i].startswith('A')): print(dic[i])
3. 輸出商品列表,用戶輸入序號,顯示用戶選中的商品
商品 li = ['手機','電腦','鼠標墊', '游艇']
# -*- coding:GBK -*- # zhou # 2017/6/13 li = ['手機','電腦','鼠標墊', '游艇'] # 打印商品信息 print('shop'.center(50,'*')) for shop in enumerate(li, 1): print(shop) print('end'.center(50,'*')) # 進入循環輸出信息 while True: user = input('>>>[退出:q] ') if user == 'q': print('quit....') break else: user = int(user) if user > 0 and user <= len(li): print(li[user - 1]) else: print('invalid iniput.Please input again...')
4. 購物車
- 要求用戶輸入自己的資產
- 顯示商品的列表,讓用戶根據序號選擇商品,加入購物車
- 購買,如果商品總額大於總資產,提示賬戶余額不足,否則,購買成功
- 附加:可充值,某商品移除購物車
# -*- coding:GBK -*- # zhou # 2017/6/13 name = 'hu' password = 'hu' num = 1 while num <= 3: user_name = input('Name: ') user_password = input('Password: ') if user_name == name and user_password == password: print('you are ok. ') flag = True break num += 1 else: print('you are only three chance, now quit.') shop = { '手機': 1000, '電腦': 8000, '筆記本': 50, '自行車': 300, } shop_car = [] list = [] if flag: salary = input('Salary: ') if salary.isdigit(): salary = int(salary) while True: print('shop'.center(50, '*')) for i in enumerate(shop, 1): print(i) list.append(i) print('end'.center(50, '*')) user_input_shop = input('input shop num:[quit: q]>>:') if user_input_shop.isdigit(): user_input_shop = int(user_input_shop) if user_input_shop > 0 and user_input_shop <= len(shop): if salary >= shop[list[user_input_shop - 1][1]]: print(list[user_input_shop - 1]) salary -= shop[list[user_input_shop - 1][1]] shop_car.append(list[user_input_shop - 1][1]) else: print('余額不足.') else: print('invalid input.Input again.') elif user_input_shop == 'q': print('您購買了一下商品:') print(shop_car) print('您的余額為:', salary) break else: print('invalid input.Input again.') else: print('invalid.')
第二個簡單版本
# -*- coding:GBK -*- # zhou # 2017/6/13 ''' 1. 輸入總資產 2. 顯示商品 3. 輸入你要購買的商品 4. 加入購物車 5. 結算 ''' i1 = input('請輸入總資產:') salary = int(i1) car_good = [] goods = [ {'name':'電腦','price':1999}, {'name':'鼠標','price':10}, {'name':'游艇','price':20}, {'name':'手機','price':998} ] for i in goods: print(i['name'], i['price']) while True: i2 = input('請輸入你想要的商品: ') if i2.lower() == 'y': break else: for i in goods: if i2 == i['name']: car_good.append(i) print(i) #結算 price = 0 print(car_good) for i in car_good: price += i['price'] if price > salary: print('您買不起.....') else: print('您購買了一下商品:') for i in car_good: print(i['name'],i['price']) print('您的余額為:', salary-price)
5. 三級聯動
# -*- coding:GBK -*- # zhou # 2017/6/13 dict = { '河南':{ '洛陽':'龍門', '鄭州':'高鐵', '駐馬店':'美麗', }, '江西':{ '南昌':'八一起義', '婺源':'最美鄉村', '九江':'廬山' } } sheng = [] shi = [] xian = [] for i in dict: sheng.append(i) print(sheng) flag = True while flag: for i in enumerate(dict,1): print(i) sheng.append(i) user_input = input('input your num: ') if user_input.isdigit(): user_input = int(user_input) if user_input > 0 and user_input <= len(dict): for i in enumerate(dict[sheng[user_input - 1]], 1): print(i) shi.append(i) user_input_2 = input('input your num: ') if user_input_2.isdigit(): user_input_2 = int(user_input_2) if user_input_2 > 0 and user_input_2 <= len(shi): for i in dict[sheng[user_input - 1]][shi[user_input_2 - 1][1]]: print(i, end = '') print() else: print('invalid input') else: print('invalid input.') else: print('invalid input. Input again.')