Category:python study
Article From:

Last class review

Review of the last class:
A tuple is equivalent to an immutable list
When we want to store multiple values and multiple values are not modified, we should use tuples.
t=('name',) #t=tuple(('name'))

1、A number of arbitrary types of values can be stored
3、Immutable type
It is used to store multiple values, but each value has a corresponding key, and key has a descriptive value.
When the value stored is in different states (age, height, sex, weight), it can be clearly defined in the dictionary.
Use of different values
d={'name':'egon','age':18} #d=dict(...)

del d['a']


for k in d:

for k in d.keys():

for v in d.values():

for k,v in d.items():


Today's content:
Set & relation operation
File processing


Character coding

1 Character coding
Encoding or converting human characters into computer recognizes numbers.
This conversion must follow a set of fixed standards, which is nothing more than a standard.
The correspondence between human characters and numbers is called character encoding table.

A---->0000 0000
B---->0000 0001
c---->0000 0002
d---->0000 0003

bit:Binary digit

ASCIICode table: an English character is represented with 1Bytes
1English character =8bit=1Bytes

GBK:Use 2Bytes to represent a Chinese character and 1Bytes to represent English characters.

unicode:The Unicode code is used in memory, and Unicode establishes the corresponding relationship between the characters in the world.
Using 2Bytes to represent a character

0000 0000 0000 0000

utf-8 #unicode tranform format-8
utf-8 To express English in 1Bytes and to express Chinese in 3Bytes

#The concept of character coding that needs to be remembered
#01 The Unicode code is used in memory, and the only code we can change to the hard disk.
#02 If you want to ensure that the file is not garbled, you should ensure that the document is stored in what encoding format, and what encoding format should be used to read it.

#03 python3The interpreter's default encoding is UTF-8 (so if the file is GBK stored, it is wrong to load it from hard disk to memory).
python2The interpreter default encoding is ASCII

There are two string encoding formats in python2
2、unicodeResults after coding
x='If the file header is coding:utf-8, then "up" is saved into binary format in UTF-8 format.

There is only one string encoding format in python3:
x='Up '

#04 Encoding and decoding coding correspond from memory to hard disk, decoding from hard disk to memory.
unicode-------Encoding encode--------> GBK
unicode<-------Decode decode--------gbk

x='Up '


#In python3 (* * * * *)
xCan only be coded

Summing up python2 and python3:
The string type STR in python2 is the result of encoding after Unicode is specified according to the header of the file.
Unicode encoded strings can also be produced in python2. You need to add u before the string

The string type STR in python3 is all Unicode encoded.
So the string type in python3 can be encoded into other character encoding formats, encoding results.
It's the bytes type



#Job 1: three level menusRequest:Print three level menus in province, city and countyCan return to the upper levelExit the program at any time

menu = {
    'Beijing': {
        'Haidian': {
            'Wudaokou': {
                'soho': {},
                'NetEase': {},
                'google': {}
            'Zhongguancun': {
                'Iqiyi': {},
                'Car home': {},
                'youku': {},
            'Land': {
                'Baidu': {},
        'Changping': {
            'Shahe': {
                'Old boy': {},
                'North Airlines': {},
            'Tian Tong Yuan': {},
            'Huilongguan': {},
        'Sunrise': {},
        'East City': {},
    'Shanghai': {
        'Minhang': {
            "People's Square": {
                'Fried chicken shop': {}
        'a section of Shanghai': {
            'Train war': {
                'Ctrip': {}
        'Pudong': {},
    'Shandong': {},
tag = True
while tag:
    for l1 in menu:
        l1_info = 'Province:%s' % l1
        print(, ' '))
    province = input('Please enter the province > >').strip()
    if province == 'quit':
        tag = False
    elif province == 'back':
        print('This is the first layer and can't return to the upper level')
    elif province not in menu:
        print('Input the provincial error, please input from the new input')
        while tag:
            for l2 in menu[province]:
                l2_info = 'City:%s' % l2
                print(, ' '))
            city = input('Please enter the city > >').strip()
            if city == 'quit':
                tag = False
            elif city == 'back':
            elif city not in menu[province]:
                print('Enter the city error, please enter the new input')
                while tag:
                    for l3 in menu[province][city]:
                        l3_info = 'County:%s' % l3
                        print(, ' '))
                    county = input('Please enter the county > >').strip()
                    if county == 'quit':
                        tag = False
                    elif county == 'back':
                    elif county not in menu[province][city]:
                        print('Input County error, please input from new input')
                        while tag:
                            for l4 in menu[province][city][county]:
                                l4_info = 'Area:%s' % l4
                                print(, ' '))
                            cmd = input('Exit or return to > >')
                            if county == 'quit':
                                tag = False
                            elif county == 'back':
                                print('Input error from new input')

View Code

#Assignment two: please close your eyes and write the shopping cart programDemand:The user name and password are stored in the file in the form of egon|egon123.After starting the program, log in first, login successfully, let the user input wages, then print the list of goods, fail to login again, more than three times, quit the program.Allow users to buy goods according to the number of goodsIf the user chooses the merchandise, he checks whether the balance is enough or not, enough for direct deduction, not enough for reminding.You may withdraw at any time, when you exit, print the purchased merchandise and balance.

product_list = [['Iphone7', 5800],
                ['Coffee', 30],
                ['Dough Drop and Assorted Vegetable Soup', 10],
                ['Python Book', 99],
                ['Bike', 199],
                ['ViVo X9', 2499],

# A list of commodity numbers is constructed to determine whether the user's input number is within this scope.
product_number_list = []
for i in range(len(product_list)):

shopping_cart = []  # Create an empty list to store the dictionary, the shopping cart information
number = 1  # The number of goods is initialized to 1

name_db = 'egon'
pwd_db = 'egon123'
count = 1
while count <= 3:
    name_inp = input('username>>: ').strip()
    pwd_inp = input('password>>: ')
    if name_db == name_inp and pwd_db == pwd_inp:
        salary = input('your salary>>: ').strip()  # 1 If the wage is floating point type, it is not judged 2. If it is plastic, it can add isDigit judgment.
        salary = int(salary)
        while True:
            for i in range(len(product_list)):
                info = 'Commodity number:%s product:%s price:%s' % (i, product_list[i][0], product_list[i][1])
                print(info.ljust(50, ' '))
            product_number = input('Please enter the commodity number > >').strip()
            if product_number not in product_number_list:
                print('If the item number is incorrect, please reenter > >::')
                product_number = int(product_number)
                product = product_list[product_number][0]
                price = product_list[product_number][1]
                if salary >= product_list[product_number][1]:
                    salary -= product_list[product_number][1]
                    for item in shopping_cart:
                        if item['product'] == product:
                            item['number'] += 1
                            item['salary'] = salary
                        info = {'product': product, 'number': number, 'price': price, 'salary': salary}
                    print('Sorry, your credit is running low')
                cmd = input('Please enter Y/y and press any key.').strip()
                if cmd == 'Y' or cmd == 'y':
                    count = 4
        print('wrong username or password ')
        count += 1

View Code

Preview: file processing, function

Link of this Article: python-study-07

Leave a Reply

Your email address will not be published. Required fields are marked *