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 ...
随机推荐
- 练习:javascript淡入淡出半透明效果
划过无透明 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...
- UOJ #311「UNR #2」积劳成疾
需要锻炼$ DP$能力 UOJ #311 题意 等概率产生一个长度为$ n$且每个数在[1,n]间随机的数列 定义其价值为所有长度为$ k$的连续子数列的最大值的乘积 给定$ n,k$求所有合法数列的 ...
- Django之Model
一.字段 常用字段: AutoField:int自增列,必须填入参数 primary_key=True.当model中如果没有自增列,则自动会创建一个列名为id的列. IntergerField:一个 ...
- Linux进程组调度机制分析【转】
转自:http://oenhan.com/task-group-sched 又碰到一个神奇的进程调度问题,在系统重启过程中,发现系统挂住了,过了30s后才重新复位,真正系统复位的原因是硬件看门狗重启的 ...
- [NOI2015]软件包管理器-树链剖分
#include<bits/stdc++.h> using namespace std; const int maxn = 1e6+5; int n,m; int e,begin[maxn ...
- ASP.NET Core之依赖注入
本文翻译自:http://www.tutorialsteacher.com/core/dependency-injection-in-aspnet-core ASP.NET Core支持依赖注入,依赖 ...
- 原生js实现无缝轮播
原生js实现无缝轮播 因为要做到无缝,所以就要把第一张图片和最后一张连接起来,在此处采用js克隆了第一张图片的节点,添加到最后,显示图片序号的小圆按钮也是使用js动态添加的. html部分 <d ...
- 字符串(2)KMP算法
给你两个字符串a(len[a]=n),b(len[b]=m),问b是否是a的子串,并且统计b在a中的出现次数,如果我们枚举a从什么位置与匹配,并且验证是否匹配,那么时间复杂度O(nm), 而n和m的范 ...
- 如何在python脚本下启动django程序
直接上图
- Linux什么是挂载?mount的用处在哪?
关于挂载的作用一直不是很清楚,今天在阅读教材时看见了mount这个命令,发现它的用处很隐晦但非常强大.奈何教材说的不明朗,因此在网上整合了一些优秀的解释,看完之后豁然开朗. 1.提一句Windows下 ...