Old Boys python learning stage practice

One problem: naming conventions

answer:

Requirements:
1. numbers, letters, underscores
2. Do not start with a number
3 can not contain python's
recommendations:
1. See-known name meaning
2. If you need to use multiple words with an underscore
added:
do not use hump style naming convention

The relationship between bits and bytes: Question two

answer:

Byte (byte): the computer smallest unit of storage
bits (bit): represents the smallest unit of the computer
1byte = 8bit

Question three: look at the code written results

name = 'wupeiqi'
result = name.upper()
print(name)
print(result)

answer:

print(name):'wupeiqi'
print(result):'WUPEIQI'

Question 4: When 'Quan' using utf-8 encoded bits and bytes occupied, the use gbk encoding, and byte occupies bits

answer:

utf-8: occupy 6 bytes, 48
gbk: 4 bytes, 32-bit

Question 5: describe briefly the difference between the two codes

Code One:

n1 = 'wupeiqi'
n2 = n1

Code II:

n1 = 'wupeiqi'
n2 = 'wupeiqi'

answer:

Code a: n1 and n2 points to the same memory address.
Code two: n1 and n2 are pointing to different memory addresses.

Question six: the default string of frequently used functions and describes the role

answer:

1.upper: String uppercase turn
2.lower: small letter string
3.strip: removing the spaces on both sides / line feed / tab / other specified contents to be removed
4.split: the specified string delimiter be segmented
5.replace: replacement string
6.join: string concatenation, to a bit string may be connected to a concatenated iterative content objects, each item must be a string
7.startswith: Analyzing string What beginning
8.endswith: determining what string ends
9.count: calculation of the number of times a character appears in a string
10.index: returns a position of a character string appearing in
11.isdigit: Analyzing string whether the content is a purely digital
12.isalpha: string determines whether the contents of the letter pure
13.isspace: determining whether the contents of the string blank pure

Question seven: common values ​​are written as a Boolean value of false

answer:

0、None、''、[]、()、{}

Question eight: the difference between writing and python3 of python2

answer:

1. The default encoding interpreter
Py2: ASCII
Py3:. 8 UTF-

2.输入
py2:raw_input
py3:input

3. Output
py2: print content to be output
py3: print (contents to be output)

4. division
py2: reserved only integer bit
py3: can save all

5. Integer
py2: After beyond the length will become long type
py3: int not only long, all the numbers are of type int

Question nine: Description copy depth

answer:

Shallow copy: no matter how complex data structures, shallow copy will only copy layer.

Deep copy: copy all types nested hierarchy variable

Question 10: respectively and while loops implemented for 1-2 + 3-4 + 99 + 5 -....

answer:

for loop:

total = 0
for i in range(1, 100):
    if i % 2 == 0:
        total -= i
    else:
        total += i
print(total)

while loop:

total = 0
i = 1
while i < 100:
    if i % 2 == 0:
        total -= i
    else:
        total += i
    i += 1
print(total)

Question 11: 1,0 print 100,99,98 ... with range to achieve

answer:

for i in range(100, -1, -1):
    print(i)

Problem 12: Write Code to see results

n1 = [11, 22, 33]
n2 = n1
n3 = n1.copy()
n1[1] = 666

print(n1)
print(n2)
print(n3)

answer:

[11,666,33]
[11,666,33]
[11,22,33]

Question Thirteen: 9 * 9 print multiplication table

answer:

for i in range(1, 10):
    for j in range(1, i + 1):
        print('%d * %d = %d' % (j, i, i * j), end=' ')
    print()

Question 14: determine the following code is correct, if the error is corrected, or write results

name = '你{0},{1}无理取闹'
n1 = name.format('冷酷','无情')
print(n1)
n2 = name.format(**['冷酷','无情'])
print(n2)
name = '你{xx},{oo}无理取闹'
n3 = name.format(oo='冷酷',xx='无情')
print(n3)
n4 = name.format(*{'xx':'冷酷','oo':'无情'})
print(n4)

answer:

print (n1): You cold, callous vexatious
correct code is as follows:

n2 = name.format(*['冷酷','无情'])
print(n2)

print (n2): You cold, callous vexatious
print (n3): You heartless, callous vexatious
correct code is as follows:

n4 = name.format(**{'xx':'冷酷','oo':'无情'})
print(n4)

print (n4): You cold, callous vexatious

Fifteen questions: calculating user input index value is an odd number and the number of

answer:

num = 0
content = input('请输入内容:')
for i in range(0, len(content)):
    if i % 2 != 0 and content[i].isdigit():
        num += 1
print(num)

Question six: realization cart

Functional requirements:

It requires the user to input the total assets they own, such as: 2000.
Show product list, allowing users to choose according to number of goods, Add to Cart purchase,
if the total is greater than the total commodity assets, suggesting insufficient account balance, otherwise, the purchase is successful.
When the purchase is successful, you need to print a shopping list
Product List:
Goods = [
{ 'name': 'computer', '. Price': 1999},
{ 'name': 'mouse', '. Price': 10},
{ 'name' : 'boat', '. price': 20 is},
{ 'name': 'beautiful', 'price': 998} ]

answer:

# ! /usr/bin/env python
# -*- coding:utf-8 -*-
goods = [
    {'name': '电脑', 'price': 1999},
    {'name': '鼠标', 'price': 10},
    {'name': '游艇', 'price': 20},
    {'name': '美女', 'price': 998}
]

goods_dict = {}  # 构建空字典存储商品信息
goods_buy_dict = {}  # 构建空字典存储用户的购买信息
total = 0  # 存储商品总额

sum_amount = input('请输入您拥有的总资产:').strip()

# 打印商品列表
for index, item in enumerate(goods, start=1):
    goods_dict[str(index)] = list(item.values())
print('商品列表如下:')
for dict_index, dict_content in goods_dict.items():
    print('%s:%s %d' % (dict_index, dict_content[0], dict_content[1]))

# 让用户输入购买信息,并存入到goods_buy_dict中,以购买商品序号为键,以购买数量为值
while True:
    buy_index = input('请输入要购买的物品序号:').strip()
    if goods_dict.get(buy_index):
        while True:
            buy_count = input('请输入要购买的物品数量:').strip()
            if buy_count.isdigit():
                goods_buy_dict[buy_index] = int(buy_count)
                break
            else:
                print('输入有误,请重新输入!')
                continue
    else:
        choice = input('您输入的商品序号不在商品列表中,是否继续购买(Y/N):').strip()
        if choice.upper() == 'Y':
            continue
        else:
            break

# 合计商品总额,并与用户输入总资产进行对比,如果商品总额大于总资产,提示账户余额不足,否则,购买成功,并打印购物清单
for buy_dict_index, buy_dict_count in goods_buy_dict.items():
    total += goods_dict[buy_dict_index][1] * buy_dict_count
if total > int(sum_amount):
    print('账户余额不足!')
elif len(goods_buy_dict) == 0:
    print('您的购物车是空的!')
else:
    print('购买成功!\n')
    print('购物清单如下:')
    for k, v in goods_buy_dict.items():
        print('%s:购买%s个' % (goods_dict[k][0], v))
    print('合计金额:%s元' % (total))

The 17-: look at the code written results

for i in range(0, 5):
    print(i)
    for j in (0, i):
        print(j)

answer:

0
0
0
1
0
1
2
0
2
3
0
3
4
0
4

Question eight: look at the code written results

while True:
    for i in range(10):
        print(i)
        if i == 5:
            continue
    else:
        break

answer:

0
1
2
3
4
5
6
7
8
9

Question nine: supplementary code

There follows a list [11, 22, 33, 44, 55, 66, 77, 88, 99, 90], all values ​​greater than 66 in the first key stored in the dictionary, the 66 will be less than the value saved to the second the value of a key.

That is: { 'k1': a list of all values ​​greater than 66, 'k2': a list of all values ​​less than 66}

Code:

li = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
result = {}
for row in li:

answer:

li = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
result = {}
for row in li:
    if row > 66:
        if result.get('k1'):
            result['k1'].append(row)
        else:
            result['k1'] = [row]
    elif row < 66:
        if result.get('k2'):
            result['k2'].append(row)
        else:
            result['k2'] = [row]
print(result)

The twenty-: write code

The list li = [11, 22, 33, 44, 55] of the first and last values ​​together and inserting an index of 3

answer:

li = [11, 22, 33, 44, 55]
li.insert(3,li[0]+li[-1])
print(li)

The twenty-first: write code

The following numbers: 6, 7, 8 digits, how many other with no repeat of the composition can be a double-digit

answer:

li = ['1', '2', '3', '4', '5', '6', '7', '8']
result = []
for i in li:
    for j in li:
        if i != j:
            if i + j not in result:
                result.append(i + j)
            elif j + i not in result:
                result.append(j + i)
print(result)

Second problem 12: write code

The following list, the list to find any two numbers is equal to the index of the element 9
nums = [2, 7, 11 , 15, 1, 8, 7]
the result is: [(0, 1), (0, 6), (4, 5)]

answer:

nums = [2, 7, 11, 15, 1, 8, 7]
result = []
for i in range(len(nums)):
    for j in range(i, len(nums)):
        if nums[i] + nums[j] == 9:
            result.append((i, j))
print(result)

The twenty-four: file-based user login achieve program

It prompts the user to enter a user name and password, check the user name and password are correct

Save username and password file user.txt

answer:

#创建文件
li = ['alex|123123', 'root|89788fs', 'eric|mimimi']
f = open(file='user.txt', encoding='utf-8', mode='w')
for i in li:
    f.writelines(i + '\n')
f.close()

#读取文件
message = '登录失败'
f = open(file='user.txt', encoding='utf-8', mode='r')
input_name = input('请输入用户名:')
input_pwd = input('请输入密码:')
for j in f:
    l = j.strip().split('|')
    if input_name == l[0] and input_pwd == l[1]:
        message = '登录成功'
        break
print(message)
f.close()

Question two five: look at the code written results

name = '海娇'
userlist = ['老狗', '方惊鸿']
userlist.extend(name)
print(userlist)

answer:

[ 'Old dog', 'fleeting side', 'sea', 'Johnson']

Question two six: enumeration int, bool, str, list, tuple, dict, set the type of the dictionary can be used as key

answer:

int、bool、str、tuple

Question two seven: Conversion

a. the string s = 'alex' is converted into a list
b. Place the string s = 'alex' is converted into a tuple
c. Set list li = [ 'alex', ' seven'] is converted into tuples
d. Place meta group tu = ( 'alex', ' seven') is converted into a list of
e. Insert list li = [ 'alex', ' seven'] converted into a dictionary, and the dictionary 10 in accordance with the key begins incrementing rearwardly

answer:

a.

s = 'alex'
print(list(s))

b.

s = 'alex'
print(tuple(s))

c.

li = ['alex', 'seven']
print(tuple(li))

d.

tu = ('alex', 'seven')
print(list(tu))

e.

li = ['alex', 'seven']
d = {}
k = 10
for i in li:
    d[k] = i
    k += 1
print(d)

Guess you like

Origin www.cnblogs.com/zhanglongfei/p/11718579.html