Python Learning - Two

时间:2023-03-08 21:57:26

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