Python Learning - Two
1. Built-in Modules and Functions
1) Function
def greeting(name):
print("Hello,", name) greeting("Alan")
2) import os
import os os.system("dir")
2. Number types
1) int
int, or integer, is a whole number, positive or negative, without decimals, of unlimited length
2) float
containing one or more decimals
3) complex
complex numbers are written with a "j" as the imaginary part:
x = 3 + 5j y = 5j z = -6j print(type(x))
print(type(y))
print(type(z))
4) Boolean
True(1) and False(0)
3. encode( ) and decode( )
1) encode( )
print('$20'.encode('utf-8')) msg = 'This is Alan' print(msg) print(msg.encode()) print(msg.encode('utf-8'))
2) decode( )
print('$20'.encode('utf-8')) msg = '我是艾倫' print(msg) print(msg.encode()) print(msg.encode('utf-8')) msg2 = b'\xe6\x88\x91\xe6\x98\xaf\xe8\x89\xbe\xe5\x80\xab' print(msg2) print(msg2.decode())
4. Python List
1) Python Collections
There are four collection data types in the Python programming language
- List: is a collection which is ordered and changeable. Allow duplicate members
- Tuple: is a collection which is ordered and unchangeable. Allow duplicate members
- Set: is a collection which is unordered and unindexed. No duplicate members
- Dictionary: is a collection which is unordered, changeable and indexed. No duplicate members
2) List
this_list = ['apple', 'banana', 'cherry'] print(this_list)
3) list( )
this_list = list(('apple', 'banana', 'cherry')) # note the double round bracket print(this_list)
4) append( )
using the append( ) method to append an item
this_list = list(('apple', 'banana', 'cherry')) # note the double round bracket print(this_list) this_list.append('pineapple') print(this_list)
5) insert( )
Adds an element at the specified position
this_list = list(('apple', 'banana', 'cherry')) # note the double round bracket print(this_list) this_list.insert(1, 'damson') print(this_list)
6) remove( )
Remove the item with the specified value
this_list = list(('apple', 'banana', 'cherry')) # note the double round bracket print(this_list) this_list.remove('banana')
print(this_list)
7) pop( )
Removes the element at the specified position, by default, remove the last item
this_list = list(('apple', 'banana', 'cherry')) # note the double round bracket this_list_two = ['apple', 'damson', 'pineapple', 'cherry'] print(this_list)
print(this_list_two) this_list.pop()
print(this_list) this_list_two.pop(2)
print(this_list_two)
8) count( )
Returns the numbers of elements with the specified value
this_list_two = ['apple', 'damson', 'pineapple', 'cherry', 'apple'] print(this_list_two.count('apple'))
9) copy( )
Return a copy of the list
this_list_two = ['apple', 'damson', 'pineapple', 'cherry', 'apple'] this_list = this_list_two.copy() print(this_list_two) print(this_list)
10) python slices and slicing
this_list_two = ['apple', 'damson', 'pineapple', 'cherry', 'apple'] print(this_list_two[1]) print(this_list_two[0:3]) print(this_list_two[:3]) print(this_list_two[1:]) print(this_list_two[-2])
5. Python tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets( )
this_tuple = ('apple', 'banana', 'cherry') print(this_tuple)
You can not change the values in a tuple
this_tuple = ('apple', 'banana', 'cherry') this_tuple[1] = 'damson'
1) tuple( )
The tuple( ) constructor
this_tuple = tuple(('apple', 'banana', 'cherry')) print(this_tuple) # note the double round bracket
2) tuple methods
count( ) : returns the number of items a specified value occurs in a tuple
index( ): searchs the tuple for a specified value and returns the position of where it was found
3) Exercise -- shopping cart
product_list = [("iphone", 5800), ("Mac Pro", 9800), ("Bike", 800), ("Watch", 10600), ("Coffee", 31), ("Alan Note", 120)] shopping_list = [] salary = input("Please enter your salary, thanks! >> ")
if salary.isdigit():
salary = int(salary)
while True:
# for item in product_list:
# print(product_list.index(item), item) for index, item in enumerate(product_list):
print(index, item)
user_choice = input("Which item do you want to buy?") if user_choice.isdigit():
user_choice = int(user_choice) if user_choice < len(product_list) and user_choice >=0:
p_item = product_list[user_choice] if p_item[1] < salary: # afford to buy
shopping_list.append(p_item) salary -= p_item[1] print("Added {} into shopping cart, and your current balance is \033[31;1m{}\033[0m.".format(p_item,salary)) print("Added %s into shopping cart, and your current balance is \033[31;1m%s\033[0m." %(p_item,salary)) else:
print("\033[41;1m Your current balance is %s, and can not afford this item.\033[0m" % salary)
else:
print("Product code [%s] do not exist!"% user_choice)
elif user_choice == "q":
print("------ shopping list ------")
for p in shopping_list:
print(p) print("You current balance is", salary) exit() else:
print("Invalid option!")
6. python string
1) Capitalize( )
Uppercase the first letter
name = "my name is alan" print(name.capitalize())
2) count( )
3) center( )
name = "my name is alan" print(name.capitalize()) print(name.center(50, "-"))
4) endswith( )
name = "my name is alan" print(name.capitalize()) print(name.center(50, "-")) print(name.endswith("lan"))
5) expandtabs( )
name = "my name \tis alan" print(name.capitalize()) print(name.center(50, "-")) print(name.endswith("lan")) print(name.expandtabs(tabsize=30))
6) find( )
name = "my name is alan" print(name.find("name")) print(name[name.find("name"):7])
7) format( ) and format_map( )
name1 = "my name is {name} and I am {year} years old." name2 = "my name is {} and I am {} years old." print(name1.format(name="Alan FUNG", year=28)) print(name2.format("Alan", 27)) # Dictionary{} is used in the format_map( ) print(name1.format_map({"name": "alan", "year": 26}))
8) isdigit( )
print("".isdigit())
9) isidentifier( )
# judge the variable name is a legal name or not
print("123fbj".isidentifier()) print("_bnkkd".isidentifier()) print("--hkkbdj".isidentifier())
10) join( )
# print("".join([1,2,3])) An error will occur for this example print("".join(["", "", ""])) print("+".join(["", "", ""]))
11) ljust( ) and rjust( )
name = "my name is Alan, and I am 27 years old." print(name.ljust(50, "*")) print(name.rjust(50, "-"))
12) split( )
print("1 + 2 + 3".split("+"))
7. Python Dictionary
Dictionary is a collection which is unordered, changeable and indexed. No duplicate members
In Python, dictionaries are written with curly brackets, and they have keys and values.
ruits = {"apple": "green", "cherry": "red", "banana": "yellow"} print(fruits)
1) The dict( ) constructor
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} print(fruits) fruit = dict(apple = "green", banana = "yellow", cherry = "red") # note that keywords are not string literal
# note the use of equals rather than colon for the assignment print(fruit)
# note that keywords are not string literal
# note the use of equals rather than colon for the assignment
2) change the value
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} fruits["apple"] = "red" print(fruits)
3) Adding items
Adding an item to the dictionary is done by using a new index key and assigning a value to it
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} fruits["orange"] = "yellow" print(fruits)
4) Removing Items
Removing a dictionary item must be done using the del( ) function in Python
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} fruits["orange"] = "yellow" print(fruits) del (fruits["cherry"]) print(fruits)
5) pop( ) and popitem( )
pop( ): remove the element with the specified key
popitem( ): remove the last key-value pair
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} fruits["orange"] = "yellow" print(fruits) del (fruits["cherry"]) print(fruits) print(fruits.pop("banana")) print(fruits) fruits.popitem() print(fruits)
6) get( )
Returns the value of the specified key
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} fruits["orange"] = "yellow" print(fruits) print(fruits["cherry"]) print(fruits.get("orange"))
7) setdefault( )
Return the value of specified key. If the key does not exist. Insert the key, with the specified value
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} fruits["orange"] = "yellow" print(fruits) print(fruits["cherry"]) print(fruits.get("orange")) print(fruits.setdefault("pineapple")) print(fruits)
8) update( )
Updates the dictionary with the specified key-value pairs
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} b = {"mango": "yellow", "apple": "green"} fruits.update(b) print(fruits)
9) fromkeys( )
Returns a dictionary with the specified keys and values
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} b = {"mango": "yellow", "apple": "green"} fruits.update(b) print(fruits) c = fruits.fromkeys([6,7,8]) d = fruits.fromkeys([1,2,3,4], "test") print(c) print(d) print(fruits)
10) items( )
Retruns a list containing the a tuple for each key-value pair
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} print(fruits.items())
11) Loop through a dictionary
fruits = {"apple": "green", "cherry": "red", "banana": "yellow"} for i in fruits:
print(i, fruits[i]) print("------------------------------------------") for k, v in fruits.items():
print(k, v)
8. Exercise -- Three-level menu
data = {
"Beijing": {
"chenping": {
"沙河": ["oldboy", "test"],
"天通苑": ["鏈家","我愛我家"]
},
"chaoyang": {
"望京": ["奔馳","陌陌"],
"國貿": ["CCIC", "HP"],
"東直門": ["Advent", "飛信"]
},
"haidian": { },
}, "shandong": {
"dezhou": { },
"qingdao": { },
"jinan": { },
}, "canton": {
"dongguang": { },
"huizhou": { },
"foshan": { },
},
} exit_flag = False while not exit_flag:
for i in data:
print(i)
choice = input("Please enter the\033[31;1m Province\033[0m name you choose from the above list! >>>") if choice in data:
while not exit_flag:
for i2 in data[choice]:
print("\t", i2)
choice2 = input(""" Please enter the\033[31;1m District\033[0m name you choose from the above list! Or you can enter the\033[31;1m 'b'\033[0m to return to the upper level and you can enter the\033[31;1m 'q'\033[0m to quit !!! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
""") if choice2 in data[choice]:
while not exit_flag:
for i3 in data[choice][choice2]:
print("\t\t", i3)
choice3 = input("""
Please enter the\033[31;1m Street\033[0m name you choose from the above list! Or you can enter the\033[31;1m 'b'\033[0m to return to the upper level and you can enter the\033[31;1m 'q'\033[0m to quit !!! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
""") if choice3 in data[choice][choice2]:
for i4 in data[choice][choice2][choice3]:
print("\t\t\t", i4)
choice4 = input("""
This is last level, please enter the\033[31;1m 'b'\033[0m to return to the upper level! Or you can enter the\033[31;1m 'q'\033[0m to quit! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """) if choice4 == "b":
# break
pass
elif choice4 == "q":
exit_flag = True if choice3 == "b":
break
elif choice == "q":
exit_flag = True if choice2 == "b":
break
elif choice2 == "q":
exit_flag = True
Python Learning - Two的更多相关文章
- python learning Exception & Debug.py
''' 在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因.在操作系统提供的调用中,返回错误码非常常见.比如打开文件的函数open(),成功时返 ...
- Python Learning Paths
Python Learning Paths Python Expert Python in Action Syntax Python objects Scalar types Operators St ...
- Python Learning
这是自己之前整理的学习Python的资料,分享出来,希望能给别人一点帮助. Learning Plan Python是什么?- 对Python有基本的认识 版本区别 下载 安装 IDE 文件构造 Py ...
- How to begin Python learning?
如何开始Python语言学习? 1. 先了解它,Wiki百科:http://zh.wikipedia.org/zh-cn/Python 2. Python, Ruby等语言来自开源社区,社区的学法是V ...
- Experience of Python Learning Week 1
1.The founder of python is Guido van Rossum ,he created it on Christmas in 1989, smriti of ABC langu ...
- Python Learning: 03
An inch is worth a pound of gold, an inch of gold is hard to buy an inch of time. Slice When the sca ...
- Python Learning: 02
OK, let's continue. Conditional Judgments and Loop if if-else if-elif-else while for break continue ...
- Python Learning: 01
After a short period of new year days, I found life a little boring. So just do something funny--Py ...
- Python Learning - Three
1. Set Set is a collection which is unordered and unindexed. No duplicate members In Python sets ar ...
随机推荐
- Choreographer解析
Choreographer_舞蹈编导 为什么叫舞蹈编导,因为舞蹈是由节奏的,节奏是每个点位动作的快慢控制,跳舞时节奏很重要,编舞者控制节奏.视图刷新也是如此,不是说你想刷就能刷,一切要按照底层信号要求 ...
- python学习第26天
自定义模块和包 软件开发规范
- JVM·垃圾收集器与内存分配策略之垃圾回收算法!
1.垃圾回收算法 1.1.标记-清除算法(Mark-Sweep): 过程分为“标记”和“清除”两个过程.先将所有需要回收的目标统一标记,然后再统一清除. ...
- jade模板 注意事项
1. jade模板 语法 doctype html html head body header div 2. 添加内容:直接在标签后边加空格 直接写内容 如下: div 我要写的内容 3. ...
- python中关于变量名失效的案例
案例一:传参动态导入模块. selectModule = input("please input your module name") app_name = input(" ...
- 末学者笔记--Linux中RAID磁盘阵列及centos7启动过程
<一>RAID概念 磁盘阵列(Redundant Arrays of Independent Disks,RAID),有“独立磁盘构成的具有冗余能力的阵列”之意. 磁盘阵列是由很多价格较便 ...
- 14.并发与异步 - 1.线程处理Thread -《果壳中的c#》
14.2.1 创建一个线程 实例化一个Thread对象,然后调用它的Start方法,就可以创建和启动一个新的线程.最简单的Thread构造方法是接受一个ThreadStart代理:一个无参方法,表示执 ...
- [原创]Xilinx工具关联UEStudio
UE安装目录如下: C:\Program Files (x86)\IDM Computer Solutions\UEStudio\UEStudio.exe 对于ISE工具,在Editor -> ...
- SQL反模式学习笔记6 支持可变属性【实体-属性-值】
目标:支持可变属性 反模式:使用泛型属性表.这种设计成为实体-属性-值(EAV),也可叫做开放架构.名-值对. 优点:通过增加一张额外的表,可以有以下好处 (1)表中的列很少: (2)新增属性时,不需 ...
- Python中append()与extend()的区别
列表方法append()和extend()之间的差异: append:在最后追加对象 x = [1, 2, 3] x.append([4, 5]) print (x) 结果 [1, 2, 3, [4, ...