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. vue构造函数(根实例化时和组件实例对象选项)参数:选项详解

    实例选项(即传给构造函数的options):数据,DOM,生命周期钩子函数,资源,组合,其他 数据 data 属性能够响应数据变化,当这些数据改变时,视图会进行重渲染. 访问方式: 1.通过 vm.$ ...

  2. DeepLearning.ai学习笔记(五)序列模型 -- week2 序列模型和注意力机制

    一.基础模型 假设要翻译下面这句话: "简将要在9月访问中国" 正确的翻译结果应该是: "Jane is visiting China in September" ...

  3. 本地ssh设置多个git项目访问

    前因: 自己本地的~/.ssh里原本有个id_rsa,到了公司后新的git项目配置后,把自己原有的文件覆盖了,导致github和公司的项目我只能选一个,郁闷,怎么区分开呢? 大致逻辑是新生成一对密钥文 ...

  4. windows下实现定时重启Apache与MySQL方法

    采用at命令添加计划任务.有关使用语法可以到window->“开始”->运行“cmd”->执行命令“at /”,这样界面中就会显示at命令的语法.下面我们讲解下如何让服务器定时启动a ...

  5. SpringMVC+Spring+Hibernate整合开发

    最近突然想认真研究下java web常用框架,虽然现在一直在用,但实现的整体流程不是很了解,就在网上搜索资料,尝试自己搭建,以下是自己的搭建及测试过程. 一.准备工作: 1/安装并配置java运行环境 ...

  6. 【原创】大叔经验分享(12)如何程序化kill提交到spark thrift上的sql

    spark 2.1.1 hive正在执行中的sql可以很容易的中止,因为可以从console输出中拿到当前在yarn上的application id,然后就可以kill任务, WARNING: Hiv ...

  7. lombok @Getter @Setter 使用注意事项

    lombok是一个帮助简化代码的工具,通过注解的形式例如@Setter @Getter,可以替代代码中的getter和setter方法,虽然eclipse自带的setter.getter代码生成也不需 ...

  8. jade模板 注意事项

    1.   jade模板 语法 doctype html html head body header div 2.  添加内容:直接在标签后边加空格 直接写内容 如下: div  我要写的内容 3.  ...

  9. scrapy相关 通过设置 FEED_EXPORT_ENCODING 解决 unicode 中文写入json文件出现`\uXXXX`

    0.问题现象 爬取 item: 2017-10-16 18:17:33 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.hu ...

  10. 你好!酷痞Coolpy 之 Linux篇

    欢迎你进入酷痞的物联网世界.这里有着自由的空气和自然的气息.接下来我将告诉你如果一步步建立一个自己专属的物联网平台. 由于目前的酷痞的官方域名还没有通过备案所以现在用临时域名解说本说明. 最终酷痞的官 ...