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

  1.   List: is a collection which is ordered and changeable. Allow duplicate members
  2.   Tuple: is a collection which is ordered and unchangeable. Allow duplicate members
  3.   Set: is a collection which is unordered and unindexed. No duplicate members
  4. 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的更多相关文章

  1. python learning Exception & Debug.py

    ''' 在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因.在操作系统提供的调用中,返回错误码非常常见.比如打开文件的函数open(),成功时返 ...

  2. Python Learning Paths

    Python Learning Paths Python Expert Python in Action Syntax Python objects Scalar types Operators St ...

  3. Python Learning

    这是自己之前整理的学习Python的资料,分享出来,希望能给别人一点帮助. Learning Plan Python是什么?- 对Python有基本的认识 版本区别 下载 安装 IDE 文件构造 Py ...

  4. How to begin Python learning?

    如何开始Python语言学习? 1. 先了解它,Wiki百科:http://zh.wikipedia.org/zh-cn/Python 2. Python, Ruby等语言来自开源社区,社区的学法是V ...

  5. 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 ...

  6. 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 ...

  7. Python Learning: 02

    OK, let's continue. Conditional Judgments and Loop if if-else if-elif-else while for break continue ...

  8. Python Learning: 01

    After a short period of  new year days, I found life a little boring. So just do something funny--Py ...

  9. Python Learning - Three

    1. Set  Set is a collection which is unordered and unindexed. No duplicate members In Python sets ar ...

随机推荐

  1. Studio 5000指令IN_OUT管脚实现西门子风格

    习惯了西门子博途编辑风格的同学,乍一看到Studio 5000的编辑界面,一时不适应,尤其是功能块或指令的IN和OUT管脚在一起,不好分辨,本文简单几步搞定,实现像西门子IN和OUT分左右显示风格. ...

  2. Gradle part1 HelloWorld

    (https://spring.io/guides/gs/gradle/#scratch) ----gradle helloworld----- 1.下载后安装 Unzip the file to y ...

  3. 【算法】K最近邻算法(K-NEAREST NEIGHBOURS,KNN)

    K最近邻算法(k-nearest neighbours,KNN) 算法 对一个元素进行分类 查看它k个最近的邻居 在这些邻居中,哪个种类多,这个元素有更大概率是这个种类 使用 使用KNN来做两项基本工 ...

  4. iOS app内打开safari完成google的OAuth2认证

    最近使用google的oauth认证,发现不再允许使用UIWebview进行认证了,必须使用系统游览器,使用游览器也不一定要在app之间跳转,ios使用SFSafariViewController就可 ...

  5. Mysql 常用SQL语句集锦

    基础篇 //查询时间,友好提示 $sql = "select date_format(create_time, '%Y-%m-%d') as day from table_name" ...

  6. Java实现大数加法运算的几种方法

    大数加法 思路一:定义String变量str1和str2分别存储输入的两个大数,定义num1[]和num2[]两个int型数组,将两个字符串分别逐个字符逆序存入数组,定义sum[]数组存放求和结果,使 ...

  7. Linux超级守护进程——xinetd

    Linux超级守护进程--xinetd 一 Linux守护进程 Linux 服务器在启动时需要启动很多系统服务,它们向本地和网络用户提供了Linux的系统功能接口,直接面向应用程序和用户.提供这些服务 ...

  8. Oracle中和mysql中函数的区别

    oracle                  -->                 mysqlto_char(sysdate,'yyyy-mm-dd')-->date_format(s ...

  9. iOS开发多线程之NSOperation

    NSInvocationOperation The NSInvocationOperationclass is a concrete subclass of NSOperationthat you u ...

  10. highcharts的dataLabels如何去处阴影

    问题: 在使用highcharts生成的图标中dataLabels是有阴影的,通常是影响美观,那么如何去除阴影呢? 原因:是因为highcharts将dataLabels生成的标签是tspan,里面有 ...