Python study notes (3): exercises in the process control chapter

1. Use a while loop to traverse lists and tuples

Since the elements of lists and tuples are indexed, all elements of lists and tuples can be traversed through while loops, lists and tuple indexes.

1.1. Use the while loop to traverse the tuples , the code is as follows:

'''
while循环遍历元组
'''
# 定义一个元组
my_tuple = ('Java', 'Python', 'PHP')
i = 0
while i < len(my_tuple):
    print("第", (i + 1), "个元素:", my_tuple[i])
    i += 1

1.2. Use a while loop to traverse the list

Requirement: to classify the elements of an integer list, put the ones that can be divided by 3 into one list; put the ones that are divided by 3 and 1 into another list; and put the ones that are divided by 3 and 2 into the third list

The code is as follows:

'''
while循环遍历列表
实现对一个整数列表的元素进行分类,
能整除3的放入一个列表中;
除以3余1的放入另一个列表中;
除以3余2的放入第三个列表中
'''
# 定义一个列表
my_list = [12, 45, 34, 13, 100, 24, 56, 74, 109]
a_list = [] # 保存能整除3的元素
b_list = [] # 保存除以3余1的元素
c_list = [] # 保存除以3余2的元素

# 第一种方法:
# for i in range(len(my_list)):
#     if my_list[i] % 3 == 0:
#         a_list.append(my_list[i])
#     elif my_list[i] % 3 == 1:
#         b_list.append(my_list[i])
#     elif my_list[i] % 3 == 2:
#         c_list.append(my_list[i])

# 第二种方法:
while len(my_list) >0:
    # 弹出最后一个元素
    ele = my_list.pop();
    if ele % 3 ==0:
        a_list.append(ele)
    elif ele % 3 == 1:
        b_list.append(ele)
    elif ele % 3 ==2:
        c_list.append(ele)

print("a_list:", a_list)
print("b_list:", b_list)
print("c_list:", c_list)

2. Use a for-in loop to traverse lists and tuples

The for-in loop can be used to traverse the elements contained in iterable objects such as ranges, lists, tuples, and dictionaries.

2.1. For-in loop traversal range

Requirements: Use a for-in loop to calculate the factorial of a specified integer. The code is as follows:

'''
for-in循环可用于遍历范围。
例如:使用for-in循环来计算指定整数的阶乘。
'''
max = int(input("请输入你想计算的阶乘:"))
result = 1
for i in range(1, max+1):
    result *= i

print(max, "的阶乘=", result)

2.2. For-in loop to traverse tuples

The code is as follows:

'''
使用for-in循环遍历元组
'''
# 第一种方式:
my_tuple = ('java', 'python', 'php')
# for i in my_tuple:
#     print("当前元素是:", i)

# 第二种方式:
for i in range(len(my_tuple)):
    print("当前元素是:", my_tuple[i])

2.3. For-in loop to traverse the list

Requirements: Calculate the sum and average value of all numerical elements in the list. The code is as follows:

'''
使用for-in循环遍历列表
需求:计算列表中所有数值元素的总和、平均值。
需要用到isInstance()函数:该函数用于判断某个变量是否为指定类型的实例,前一个参数是要判断的变量,后一个参数是类型
'''
my_list = [12, 45, 3.4, 13, 'a', 4, 56, 'crazyit', 109.5]
my_sum = 0
my_count = 0

for i in my_list:
    if isinstance(i, int) or isinstance(i, float):
        # 如果该元素是数值元素,则累加
        my_sum += i
        # 如果该元素是数值元素,则数量加1
        my_count += 1

print("总和:", my_sum)
print("平均值:", my_sum/my_count)

3. Use a for-in loop to traverse the dictionary

The dictionary contains the following three methods:

  • items(): Returns a list of all key-value pairs in the dictionary.
  • keys(): Returns a list of all keys in the dictionary.
  • values(): Returns a list of all values ​​in the dictionary.

The sample code is as follows:

'''
使用for-in循环遍历字典
'''
my_dict = {"语文": 89, "数学": 92, "英语": 80}

# 第一种方式:通过键-值对来遍历字典
# for key, value in my_dict.items():
#     print("key:", key)
#     print("value:", value)

# 第二种方式:通过key来遍历字典
# for key in my_dict.keys():
#     print(key, ":", my_dict[key])

# 第三种方式:通过value来遍历字典
for value in my_dict.values():
    print("value:", value)

Requirements: Count the number of occurrences of each element in the list. The code is as follows:

'''
统计列表中各元素出现的次数
'''
my_list = ['hello', 2, 4, 'hello', 4, 2.5, 4, 2.5]

# 定义一个空字典
my_dict = {}
for i in my_list:
    # 如果字典中包含i代表的key
    if i in my_dict:
        # 则将i元素出现的次数加1
        my_dict[i] += 1
    else:
        my_dict[i] = 1

# 遍历my_dict,打印出各元素出现的次数
for key, value in my_dict.items():
    print("%s出现的次数是%d" %(key, value))

4. Chapter Exercises

4.1. Use the loop to output the nine-nine multiplication table, and output the following results:

1 x 1 = 1
1 x 2 = 2  2 x 2 = 4
1 x 3 = 3  2 x 3 = 6  3 x 3 = 9
...
1 x 9 = 9  2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45 6 x 9 = 54 7 x 9 = 63 8 x 9 = 72 9 x 9 = 81

The code is as follows:
for i in range(1, 10):
    for j in range(1, i + 1):
        print("%d x %d =" %(j, i), j * i, end="\t")
    print()

4.2. Use the loop to output isosceles triangles, for example, given 4, the output is as follows:

   *
  ***
 *****
*******

The code is as follows:

num = int(input("请输入一个整数:"))
for i in range(1, num + 1):
    for j in range(1, num + 1 - i):
        print(" ", end="")
    for k in range(1, 2 * i):
        print("*", end="")
    print()

4.3. The user enters his own score, the program will automatically determine the type of the score: scores ≥ 90 points are represented by A, 80-89 points are represented by B, 70-79 points are represented by C, and others are represented by D. The code is as follows:

'''
3.用户输入自己的成绩,程序会自动判断该成绩的类型:
成绩≥90分用A表示,80~89分用B表示,70~79分用C表示,其他的用D表示。
'''
score = int(input("请输入自己的成绩:"))
if score >= 90:
    print("A")
elif score >= 80 and score <= 89:
    print("B")
elif score >= 70 and score <= 79:
    print("C")
else:
    print("D")

4.4. Determine how many prime numbers are between 101 and 200, and output all prime numbers. The code is as follows:

'''
4.判断101~200之间有多少个素数,并输出所有的质数
'''
count = 0 # 统计素数的个数
my_list = [] # 用来保存所有的素数
for i in range(101, 201):
    j = 2;
    while j < i:
        if i % j == 0:
            break
        else:
            j += 1
    else:
        count += 1
        my_list.append(i)

print("一共有%d个素数" %count)
print("素数:", my_list)

4.5. Print out all the "daffodil numbers". The so-called "daffodil number" refers to a three-digit number whose cube sum is equal to the number itself. For example: 153 is a number of daffodils, because 153=1^3+5^3+3^3. The code is as follows:

'''
5.打印出所有的”水仙花数“。所谓”水仙花数“,是指一个三位数,其各位数字的立方和等于该数本身。例如:153是一个水仙花数,因为153=1^3+5^3+3^3
'''
# 定义一个列表,用来保存所有的水仙花数
my_list = []
# 统计水仙花的个数
count = 0
for i in range(100, 1000):
    # 百位数
    m = int(i/100)
    # 十位数
    n = int((i-m*100)/10)
    # 个位数
    k = int(i-m*100-n*10)
    if i == (m * m * m + n * n * n + k * k * k):
        count += 1
        my_list.append(i)

# 输出所有的水仙花数
print("共有%d个水仙花" %count)
print(my_list)

 

Guess you like

Origin blog.csdn.net/weixin_44679832/article/details/113824327