循环

enumerate

该函数用于在迭代过程中获取每个元素的索引和值,返回一个可迭代对象,该对象生成一个包含索引和值的元组。

1
enumerate(iterable,start=0)

其中,iterable 是要遍历的可迭代对象,例如列表、元组、字符串等。而 start 是可选参数,用于指定开始的索引,默认值是 0。

1
2
3
4
5
6
7
8
fruits = ['apple', 'banana', 'orange']

for index, fruit in enumerate(fruits):
print(f'Index: {index}, Fruit: {fruit}')

# Index: 0, Fruit: apple
# Index: 1, Fruit: banana
# Index: 2, Fruit: orange

在这个例子中,enumerate(fruits) 返回了一个可迭代对象,其中每个元素都是一个包含索引和对应值的元组。通过使用 indexfruit 分别接收索引和值,可以在循环中打印每个水果的索引和值。

除了使用默认的开始索引 0,你还可以使用 start 参数来指定开始的索引值。下面的示例将开始索引设置为 1:

1
2
3
4
5
6
7
8
fruits = ['apple', 'banana', 'orange']

for index, fruit in enumerate(fruits, start=1):
print(f'Index: {index}, Fruit: {fruit}')

# Index: 1, Fruit: apple
# Index: 2, Fruit: banana
# Index: 3, Fruit: orange

例题:获取10-20之间的prime number,如果不是质数,指出他们的因子。

for-else

1
2
3
4
5
6
7
8
for number in range(10, 20):
for factor1 in range(2, number):
if number % factor1 == 0:
factor2 = number / factor1
print(f'{factor1}*{factor2:0.0f}={number}')
break
else:
print(f'{number} is a prime number')

for-if-else

1
2
3
4
5
6
7
8
9
for number in range(10, 20):
for factor1 in range(2, number):
if number % factor1 != 0:
print(f'{number} is a prime number')
break
else:
factor2 = number / factor1
print(f'{factor1}*{factor2:0.0f}={number}')
break

while-else

1
2
3
4
5
6
7
8
9
10
11
12
number = 10
while number < 20:
factor1=2
while factor1<20:
if number%factor1==0:
factor2=number/factor1
print(f'{factor1}*{factor2:0.0f}={number}')
break
factor1+=1
else:
print(f'{number} is a prime number')
number+=1

刷题

第1天的作业打卡

来自quiz_1-2.pdf

待读取的文件内容可以这样写:

1
2
3
John Dick,M
Jane Smith,F
Michael Johnson,M

注意

.strip().removesuffix()都是Python字符串操作,分别用于删除字符串两端的空白字符和指定的后缀,其中,.removesuffix() 是在Python 3.9中引入的。

.strip() 方法用于删除字符串开头和结尾的空白字符,包括空格、制表符、换行符等。

1
2
text = "  Hello, World!  "
print(text.strip()) # 输出: "Hello, World!"

.removesuffix('\n') 方法用于删除字符串末尾的指定后缀。

1
2
text = "Hello, World!\n"
print(text.removesuffix('\n')) # 输出: "Hello, World!"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import sys
from os.path import exists

def print_rhombus(space_number, symbol):
print('Here is a rhombus:')
print()
# 方法一:枚举
# half_layers=2
# print(' ' * (space_number + 2) + '*')
# print(' ' * (space_number + 1) + '*' + ' ' * 1 + '*')
# print(' ' * (space_number + 0) + '*' + ' ' + symbol + ' ' + '*')
# print(' ' * (space_number + 1) + '*' + ' ' * 1 + '*')
# print(' ' * (space_number + 2) + '*')

# 方法二:循环
half_layers=2
print(' ' * (space_number + half_layers) + '*')
for i in range(half_layers-1,0,-1):
print(' '*(space_number+i)+'*'+' '*(2*(half_layers-i)-1)+'*')

# (2*half_layers-2)/2=half_layers-1
print(' ' * (space_number + i-1) + '*' + ' '*(half_layers-1) + symbol + ' '*(half_layers-1) + '*')

for i in range(1,half_layers):
print(' '*(space_number+i)+'*'+' '*(2*(half_layers-i)-1)+'*')

print(' ' * (space_number + half_layers) + '*')
print()

def print_lines(file_name):
print('Here are the people listed in the file:')
with open(file_name) as file:
for line in file:
line = line.strip()
# 判断不是空行并且包含逗号
if line and ',' in line:
name, gender = line.split(',')
last_name, first_name = name.split()
gender = 'Mr.' if gender.strip() == 'M' else "Mrs"
print(f"{gender} {first_name} {last_name}")

if __name__ == '__main__':
try:
space_number = int(input("Enter a positive integer (possibly 0): "))
symbol = input("Input a symbol: ").removesuffix("\n")
if space_number < 0 or symbol is None:
raise ValueError
except ValueError:
print("Input is not an positive integer, giving up.")
sys.exit()
file_name = input('Input the name of a file in the working directory: ').removesuffix('\n')
if not exists(file_name):
print('Incorrect directory, giving up.')
sys.exit()

print_rhombus(space_number, symbol)
print_lines(file_name)

Classifying elements in a list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from random import randint, seed

if __name__ == '__main__':
seed_value = int(input("Input a seed for the random number generator: "))
element_number = int(input("How many elements do you want to generate? "))

res = []
seed(seed_value)
lst = [randint(0, 20) for _ in range(0, element_number)]
print(lst)

first_interval, second_interval, third_interval, forth_interval = 0, 0, 0, 0

for item in lst:
if item <= 4 and item >= 0:
first_interval += 1
elif item <= 9 and item >= 5:
second_interval += 1
elif item <= 14 and item >= 10:
third_interval += 1
else:
forth_interval += 1

print(
f"There is {first_interval} element between 0 and 4." if first_interval > 0 else "There is no element between 0 and 4.")
print(
f"There is {second_interval} element between 5 and 9." if second_interval > 0 else "There is no element between 5 and 9.")
print(
f"There is {third_interval} element between 10 and 14." if third_interval > 0 else "There is no element between 10 and 14.")
print(
f"There is {forth_interval} element between 15 and 19." if forth_interval > 0 else "There is no element between 15 and 19.")